diff --git "a/2984.jsonl" "b/2984.jsonl" new file mode 100644--- /dev/null +++ "b/2984.jsonl" @@ -0,0 +1,629 @@ +{"seq_id":"33827810","text":"from enum import Enum\r\n\r\nfrom domain.distance import Distance, EuclideanDistance\r\n\r\n\r\nclass Instance:\r\n def __init__(self, row):\r\n self.row = row\r\n self.group = -1\r\n\r\n # Update row group and returns if group has been changed\r\n def update_group(self, centroids: [], distance_fun: Distance) -> bool:\r\n current_group = self.group\r\n means = [distance_fun.calc_dist(self.row, centroid) for centroid in centroids]\r\n # means to enumerate: (position, mean)\r\n new_group = min([a for a in enumerate(means)], key=lambda instance: instance[1])[0]\r\n self.group = new_group\r\n return new_group == current_group\r\n\r\n def __repr__(self) -> str:\r\n return '\\nGroup: ' + str(self.group) + '\\t Row: ' + str(self.row)\r\n\r\n\r\nclass VanillaDataset:\r\n def __init__(self, data, columns, rows, missing_data):\r\n self.data = data\r\n self.missing_values = len(missing_data)\r\n self.missing_data = missing_data\r\n self.columns = columns\r\n self.rows = rows\r\n\r\n\r\nclass InstanceDataset:\r\n def __init__(self, instances: [Instance]):\r\n self.instances = instances\r\n self.columns = len(instances[0].row)\r\n self.rows = len(instances)\r\n\r\n def get(self, pos: int = 0):\r\n return self.instances[pos]\r\n\r\n\r\nclass FillMode(Enum):\r\n MEAN = 0\r\n MODE = 1\r\n\r\n\r\nif __name__ == '__main__':\r\n i = Instance([1, 2, 4])\r\n for t in range(10):\r\n g = i.update_group([[5, 6, 7], [12, -1, 15], [1, 2, 5]], EuclideanDistance())\r\n print(g)\r\n","sub_path":"Atividade6/rafael/domain/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"261482728","text":"import wikipedia\nimport tweepy\nfrom flickrapi import FlickrAPI\nimport os\n\n\n# 0: Twitter\n# 1: Wikipedia\n# 2: Flickr\n\ndef get_result(api_raw, search_text):\n\n\n result_text = []\n result_images = []\n\n api_raw = str(api_raw)\n api = get_api(api_raw.lower())\n if api == 0:\n # Twitter\n\n ACCESS_KEY = os.environ.get('ACCESS_KEY')\n ACCESS_SECRET = os.environ.get('ACCESS_SECRET')\n CONSUMER_KEY = os.environ.get('CONSUMER_KEY')\n CONSUMER_SECRET = os.environ.get('CONSUMER_SECRET')\n\n\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\n api = tweepy.API(auth)\n twitter_search = api.search(search_text)\n index = 0\n for result in twitter_search:\n if index <10:\n result_text.append(result.text)\n index += 1\n\n\n elif api == 1:\n # Wikipedia\n try:\n wikiPage = wikipedia.page(search_text)\n result_text = wikiPage.summary\n result_images = wikiPage.images\n #handles if a search term could have more than one result, chooses the first suggested one\n except wikipedia.exceptions.DisambiguationError as e:\n print(e.options)\n search_text = e.options[0]\n print(search_text)\n wikiPage = wikipedia.page(search_text)\n result_text = wikiPage.summary\n result_images = wikiPage.images\n\n\n elif api == 2:\n # Flickr\n FLICKR_PUBLIC = os.environ.get('FLICKR_PUBLIC')\n FLICKR_SECRET = os.environ.get('FLICKR_SECRET')\n flickr = FlickrAPI(FLICKR_PUBLIC, FLICKR_SECRET, format='parsed-json')\n extras = 'url_c,url_l,url_o'\n results = flickr.photos.search(tags=search_text, per_page=25, extras=extras)\n for rslt in results['photos']['photo']:\n if 'url_l' in rslt:\n result_images.append(rslt['url_l'])\n elif 'url_c' in rslt:\n result_images.append(rslt['url_c'])\n elif 'url_o' in rslt:\n result_images.append(rslt['url_o'])\n if 'title' in rslt:\n title = str(rslt['title'])\n if len(title) > 0:\n lines = title.splitlines()\n\n\n\n return result_text,result_images\n\n\ndef get_api(api_raw):\n if api_raw.startswith('t'):\n return 0\n if api_raw.startswith('w'):\n return 1\n if api_raw.startswith('f'):\n return 2\n if api_raw.startswith('0'):\n return 0\n if api_raw.startswith('1'):\n return 1\n if api_raw.startswith('2'):\n return 2\n","sub_path":"Results.py","file_name":"Results.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"378902666","text":"import sys\n\nfrom utils import *\n\ndef approach():\n args = sys.argv\n\n data_path = args[1]\n score_path = args[2]\n approach_name = args[3]\n drop_months_end = int(args[4])\n num_test_commits = int(args[5])\n\n ######################################\n # Loop for within project prediction #\n # Loads only one project at a time #\n ######################################\n \n for project_name in list_all_projects(path=data_path):\n print(project_name)\n data = load_project(path=data_path, project_name=project_name)\n\n train_df, test_df = prepare_within_project_data(data, drop_months_end=drop_months_end, num_test_commits=num_test_commits)\n\n #########################################\n # Build Classifier #\n # (should be adopted for your approach) #\n #########################################\n\n y_test = test_df['is_inducing']\n y_pred = y_test.copy().values\n y_pred.fill(0) \n\n ######################################################\n # DO NOT TOUCH FROM HERE #\n # This is where the scores are calculated and stored #\n ######################################################\n\n scores = score_model(test_df, y_pred)\n print_summary(train_df, test_df, scores)\n write_scores(score_path, approach_name, project_name, scores)\n\n \nif __name__ == '__main__':\n approach()","sub_path":"approaches/baseline_none/approach.py","file_name":"approach.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"334885272","text":"import logging\nimport logging.handlers\n\nimport build_flat_files\nimport build_tables\nimport describe_db\n\n#*******change these to your own settings **************\n\n#path to the data as downloaded from DropBox\n#NB: I'm using shortened versions of the scenario directory names\n# as these are part of the names in the DB\n\n#If rerunning build_all.py, please ensure that the scratch directories are empty - or, \n# if you want to retain the existing ones, that you provide new directory names. \n# The tables are built from all contents of the scratch directories. More surgical \n# construction of the database tables is possible by running\n# build_flat_files.build_flat_files() and build_tables.build_tables() separately.\n\n#Data directories and output directories. \ndirs = [#{'data': '/home/pat/mary/NoRed-YesHwy', 'scratch': '/home/pat/flat_NoRed-YesHwy'},\n #{'data': '/home/pat/mary/NoRed-NoHwy', 'scratch': '/home/pat/mary/flat_NoRed-NoHwy'},\n {'data': '/home/pat/mary/YesRed-YesHwy', 'scratch': '/home/pat/mary/flat_YesRed-YesHwy'},\n #{'data': '/home/pat/mary/yesRedNoHwyTest', 'scratch': '/home/pat/mary/yesRedNoHwyTest_flatoutx'},\n #{'data': '/home/pat/mary/Fares', 'scratch': '/home/pat/mary/flat_Fares'},\n # {'data': '/home/pat/mary/Test-NoRed-YesHwy', 'scratch': '/home/pat/mary/junkdir'},\n ]\n\n#database name\nDB='naacp'\n#log file name - lives in the script directory\nLOG_FILE='db_loader.log'\n#set to 'WARN' to capure only data loading issues. 'DEBUG' is verbose.\nLOG_LEVEL='DEBUG' \n\n#**** login credentials need to be updated in database.py ***\n\n\n#**********************************************************\n\nlogger = logging.getLogger('trans_logger')\nh = logging.handlers.RotatingFileHandler(LOG_FILE, \n 'a', \n maxBytes=10*1024*1024, \n backupCount=5)\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - '\n '%(filename)s:%(lineno)s - %(message)s',\n datefmt=\"%Y-%m-%d %H:%M:%S\")\nh.setFormatter(formatter)\nlogger.addHandler(h)\nlogger.setLevel(LOG_LEVEL)\n\nif __name__=='__main__':\n 'main execution start'\n #leave these statements here - logging info imported from settings\n for ix, d in enumerate(dirs, start=1):\n data_dir=d['data']\n scratch_dir = d['scratch']\n msg='Data loading from {} \\n...to database {}. \\n...Logging to {} \\n'\n print(msg.format(data_dir, DB, LOG_FILE))\n #create the flat files for import\n #build_flat_files.build_flat_files(data_dir, scratch_dir)\n #create tables from header info in tables, then load data\n build_tables.build_tables(db=DB, pdir = scratch_dir, drop_old=True, data_dir=data_dir)\n if ix != len(dirs):\n logger.info(\"*******************************\")\n logger.info(\"Beginning new scenario\")\n logger.info(\"*******************************\")\n\n describe_db.describe_db(db=DB) \n\n","sub_path":"build_one.py","file_name":"build_one.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"52725208","text":"import tkinter\r\nimport tkinter as ttk\r\nfrom tkinter import *\r\nfrom tkinter.ttk import *\r\nfrom tkinter import ttk\r\nfrom database import MyClass\r\nfrom mongoDB import MyMongo\r\nimport sys\r\nimport urllib\r\nimport csv\r\nsys.setrecursionlimit(5000)\r\n\r\n\r\nclass Chang(tkinter.Tk):\r\n def __init__(self, parent) :\r\n tkinter.Tk.__init__(self, parent)\r\n self.iconbitmap('./watermelon.ico')\r\n self.parent = parent\r\n self.searching()\r\n self.title('WATERMELON')\r\n self.geometry('750x1000')\r\n self.frame()\r\n self.Mydb = MyClass()\r\n\r\n def searching(self):\r\n # 기간설정버튼\r\n period_option = LabelFrame(self, text=\"검색하실 기간을 설정하세요 \")\r\n period_option.pack(fill='x', padx=5, pady=5, ipady=5)\r\n day_format = [\"일간\", \"주간\", \"월간\"]\r\n day_format = ttk.Combobox(period_option, state=\"readonly\", values=day_format, width=20)\r\n # combobox 값 return\r\n def btncmd():\r\n day = day_format.get()\r\n MyClass().create_table()\r\n MyClass().insert_m(day)\r\n c = MyMongo()\r\n c.insert_db()\r\n singer = c.s_count()\r\n c.singer_visualize(singer)\r\n like = c.l_count()\r\n c.like_visualize(like)\r\n\r\n day_format.current(0)\r\n day_format.pack(side=\"left\", padx=5, pady=5)\r\n button_period = tkinter.Button(period_option, bg='lightpink', padx=5, pady=5, width=12, text='기간설정', command = btncmd)\r\n button_period.pack(side=\"right\", padx=5, pady=5)\r\n\r\n # 워드클라우드\r\n word_frame = LabelFrame(self, text=\"Wordcloud\")\r\n word_frame.pack(fill='x', padx=3, pady=3)\r\n btn_image = tkinter.Button(word_frame, bg='ivory', padx=5, pady=5, text=\"순위권 내 가수\", width=12, command=self.pop_up)\r\n btn_image.pack(side=\"right\", padx=5, pady=5)\r\n btn_image2 = tkinter.Button(word_frame, bg='ivory', padx=5, pady=5, text=\"가수별 좋아요 수\", width=12, command=self.pop_up2)\r\n btn_image2.pack(side=\"right\", padx=5, pady=5)\r\n\r\n # 검색창\r\n search_option = LabelFrame(self, text=\"가수 혹은 제목을 입력하세요 \")\r\n search_option.pack(fill='x',padx=5, pady=5, ipady=5)\r\n self.entryValue = tkinter.StringVar()\r\n self.entry = tkinter.Entry(search_option, textvariable=self.entryValue)\r\n self.entry.pack(fill = 'x', padx = 5, pady =3, ipady =3)\r\n self.entry.bind('', self.onPressEnter)\r\n # 검색버튼\r\n button_add_item = tkinter.Button(search_option,bg='lightpink',padx=5, pady=5, width = 12, text='검색', command = self.onButtonClick or self.onPressEnter )\r\n button_add_item.pack(side=\"right\",padx=5, pady=5)\r\n\r\n #라벨창\r\n self.labelValue = tkinter.StringVar()\r\n self.label = tkinter.Label(self, fg='IndianRed1', bg='lightgreen', textvariable=self.labelValue)\r\n self.label.pack(fill = 'x', padx = 5, pady =3, ipady =3)\r\n self.entryValue.set(' ')\r\n self.labelValue.set(' ')\r\n self.entry.focus_set()\r\n self.entry.select_range(0, tkinter.END)\r\n # 검색결과 프레임\r\n tree_frame = LabelFrame(self , text=\"검색결과\")\r\n tree_frame.pack(fill='x', padx=3, pady=3)\r\n self.tree = ttk.Treeview(self)\r\n tree_add_item = tkinter.Button(tree_frame,bg='ivory', padx=5, pady=5, width = 12, text='조회', command = self.treeview)\r\n tree_add_item.pack(side=\"right\", padx=5, pady=5)\r\n tree_add_item = tkinter.Button(tree_frame,bg='ivory', padx=5, pady=5, width=12, text='새로고침', command=self.treedelete)\r\n tree_add_item.pack(side=\"right\", padx=5, pady=5)\r\n\r\n # 컬럼\r\n self.tree[\"columns\"] = (\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\")\r\n self.tree.heading(\"#1\", text=\"순위\")\r\n self.tree.heading(\"#2\", text=\"제목\")\r\n self.tree.heading(\"#3\", text=\"가수\")\r\n self.tree.heading(\"#4\", text=\"앨범\")\r\n self.tree.heading(\"#5\", text=\"좋아요\")\r\n self.tree.heading(\"#6\", text=\"뮤비\")\r\n self.tree.heading(\"#7\", text=\"앨범자켓\")\r\n self.tree.column(\"#0\", width=1)\r\n self.tree.column(\"#1\", width=50)\r\n self.tree.column(\"#2\", width=90)\r\n self.tree.column(\"#3\", width=90)\r\n self.tree.column(\"#4\", width=100, anchor=\"w\")\r\n self.tree.column(\"#5\", width=100, anchor=\"w\")\r\n self.tree.column(\"#6\", width=100, anchor=\"w\")\r\n self.tree.column(\"#7\", width=100, anchor=\"w\")\r\n self.tree.pack(expand=True,fill='both')\r\n\r\n #실행\r\n btn_close = tkinter.Button(self,bg='ivory', padx=5, pady=5, text=\"닫기\", width=12, command=self.quit)\r\n btn_close.pack(side=\"right\", padx=5, pady=5)\r\n btc_start = tkinter.Button(self, bg='ivory', padx=5, pady=5, text=\"csv file 저장\", width=12, command=self.save_text)\r\n btc_start.pack(side=\"right\", padx=5, pady=5)\r\n btn_start = tkinter.Button(self,bg='ivory', padx=5, pady=5, text=\"사진저장\", width=12, command=self.save_pic)\r\n btn_start.pack(side=\"right\", padx=5, pady=5)\r\n\r\n\r\n def get_opr(self):\r\n return self.opr\r\n # 검색시 기능 function\r\n def onPressEnter(self, event):\r\n self.labelValue.set(self.entryValue.get() + '를 조회하시겠어요?')\r\n self.opr = self.entryValue.get()\r\n self.entryValue.set('')\r\n\r\n # 검색시 기능 function\r\n def onButtonClick(self):\r\n self.labelValue.set(self.entryValue.get() + '를 조회하시겠어요?')\r\n self.opr = self.entryValue.get()\r\n\r\n #검색창 Values\r\n def treeview(self):\r\n j = self.Mydb.find_all(self.opr)\r\n for i in j:\r\n self.tree.insert('','end',values= i)\r\n\r\n #사진 저장\r\n def save_pic(self):\r\n j = self.Mydb.find_all(self.opr)\r\n lst = []\r\n for i in range(0,len(j)):\r\n lst.append(j[i][6])\r\n for idx, p in enumerate(lst,1):\r\n # 다운 받을 폴더 경로 입력\r\n urllib.request.urlretrieve(p, \"c:/image/\" + str(idx) + \".jpg\")\r\n\r\n #csv file 저장\r\n def save_text(self):\r\n f = open('WaterMelon.csv', 'w', encoding='utf-8', newline='')\r\n wr = csv.writer(f)\r\n j = self.Mydb.find_all(self.opr)\r\n lst = []\r\n for i in range(0,len(j)):\r\n lst.append(j[i])\r\n for i in lst :\r\n wr.writerow([i])\r\n f.close()\r\n\r\n def treedelete(self): # <---treeview 삭제...\r\n for i in self.tree.get_children():\r\n self.tree.delete(i)\r\n self.tree.update()\r\n\r\n # Word cloud 저장\r\n def singer_word(self):\r\n img = PhotoImage(file='singer_visualize.gif') # <----여기에다가 클라우드 들어가는 경로 넣으면 됨!!\r\n lbl = Label(image=img)\r\n lbl.image = img\r\n lbl.pack(padx=1, pady=1,expand=True,fill='x')\r\n def like_word(self):\r\n img = PhotoImage(file='like_visualize.gif') # <----여기에다가 클라우드 들어가는 경로 넣으면 됨!!\r\n lbl = Label(image=img)\r\n lbl.image = img\r\n lbl.pack(padx=1, pady=1,expand=True,fill='x')\r\n\r\n def pop_up(self):\r\n self.pop_up = Toplevel()\r\n self.pop_up.title(\"순위권 내 가수\")\r\n self.f = Frame(self.pop_up, height=500, width=550, cursor=\"hand2\")\r\n self.f.pack()\r\n self.photo = PhotoImage(file='singer_visualize.gif')\r\n self.pop_image = Label(self.f, cursor=\"hand2\", image=self.photo)\r\n self.pop_image.image = self.photo\r\n self.pop_image.place(x=23, y=0)\r\n self.pop_up.mainloop()\r\n self.reload()\r\n\r\n def pop_up2(self):\r\n self.pop_up = Toplevel()\r\n self.pop_up.title(\"가수별 좋아요 수\")\r\n self.f = Frame(self.pop_up, height=500, width=550, cursor=\"hand2\")\r\n self.f.pack()\r\n self.photo = PhotoImage(file='like_visualize.gif')\r\n self.pop_image = Label(self.f, cursor=\"hand2\", image=self.photo)\r\n self.pop_image.image = self.photo\r\n self.pop_image.place(x=23, y=0)\r\n self.pop_up.mainloop()\r\n self.reload()\r\n\r\nif __name__ == '__main__':\r\n m1 = Chang(None)\r\n m1.resizable(True,True)\r\n m1.mainloop()","sub_path":"Watermelon_chart/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":8268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"482902291","text":"\"\"\"Extra tools to validate an execution graph.\"\"\"\nfrom .graph import Graph\n\n\ndef starting_point(graph: Graph):\n \"\"\"Check graph starting point.\n\n Since a graph is designed to work with a unique starting point, the user\n has to make sure to specify a single one, since the starting point is\n identified only by a 0 priority (i.e. top-priority).\n\n The execution of a graph with multiple starting points has to be considered\n undefined behavior.\n\n \"\"\"\n candidates = []\n\n for task in graph.tasks():\n if task.action.priority == 0:\n candidates.append(task)\n\n if len(candidates) != 1:\n return False\n\n return True\n","sub_path":"src/qibocal/auto/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"239693770","text":"from distutils.log import warn as printf\nfrom random import randrange as rand\nfrom pymongo import errors\n\n\nCOLSIZE=10\nDBNAME='test'\nFIELDS=('login','userid','projid')\n\ntformat=lambda s:str(s).title().ljust(COLSIZE)\ncformat=lambda s:s.upper().ljust(COLSIZE)\n\ndef randName():\n\tpick=set(NAMES)\n\twhile pick:\n\t\tyield pick.pop()\n\nNAMES=(\n\t('aaron',8312),('angela',7603),('dave',7306),('davina',7902),('elliot',7911)\n)","sub_path":"untitled/ushuffle_mongo.py","file_name":"ushuffle_mongo.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"26177128","text":"import numpy as np\nimport pandas as pd\n\nclass StratifiedKFolds():\n\n def __init__(self, data, k, target_attribute):\n self.k = k\n self.folds = self._split_folds(data, target_attribute)\n\n def _split_fold_group(self, data_group):\n split_idx = [int(len(data_group)*float(i)/self.k) for i in range(1, self.k)]\n return np.split(data_group.sample(frac=1), split_idx)\n\n def _split_folds(self, data, target_attribute): \n split_data = data.groupby(target_attribute).apply(self._split_fold_group)\n\n class_count = len(data[target_attribute].unique())\n folds = []\n for j in range(self.k):\n current_fold = []\n for i in range(class_count):\n current_fold.append(split_data.iloc[i][j])\n folds.append(pd.concat(current_fold))\n return folds\n\n def get_folds(self, join_train=True):\n for i in range(self.k):\n training = pd.concat([x for j,x in enumerate(self.folds) if j != i])\n test = self.folds[i]\n yield training, test \n","sub_path":"neural_net/evaluation/kfold.py","file_name":"kfold.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"464573698","text":"#!/usr/bin/env python\n\nimport sys\nimport numpy as np\nimport pystan as pystan\n\n# Plotting packages\nimport plotly\n# from plotly import tools \nimport plotly.plotly as py\nfrom plotly.offline import plot\nimport plotly.graph_objs as go\n\n## Import the cell data\nstemCellDataSet = np.genfromtxt('../Data/stemcelldata.csv', delimiter=',')\ntransitCellDataSet = np.genfromtxt('../Data/transitcelldata.csv', delimiter=',')\ndifferentiatedCellDataSet = np.genfromtxt('../Data/differentiatedcelldata.csv', delimiter=',')\n\ntimes = stemCellDataSet[:,0] # Get the times\n\n# Get the cell population numbers\nstemCellData = stemCellDataSet[1:-1,1:-1]\ntransitCellData = transitCellDataSet[1:-1,1:-1]\ndifferentiatedCellData = differentiatedCellDataSet[1:-1,1:-1]\n\n\nnumberOfTimesteps = len(times[1:-1])\nnumberOfSamples = len(stemCellData[0,:])\n\n# Set the initial population\ninitialPopulation = [10.0, 300.0, 200.0]\n\nstanDat = {'N0' : initialPopulation, 't0' : times[0], 'ts' : times[1:-1], 'numberOfTimesteps' : numberOfTimesteps,\\\n\t\t\t'numberOfSamples' : numberOfSamples, 'stemCells' : stemCellData, 'transitCells' : transitCellData,\n\t\t\t'differentiatedCells' : differentiatedCellData}\n\nnumberOfIterations = int(sys.argv[1])\nnumberOfChains = int(sys.argv[2])\nfit = pystan.stan(file='CryptOdeModel.stan', data=stanDat, iter=numberOfIterations, chains=numberOfChains)\n\n### Plot the posterior distributions\nparameters = fit.extract(permuted=True)\n\nfor key in parameters:\n\tparameterDistribution = parameters[key]\n\tnp.savetxt('../Output/HMC' + str(key) + '.csv', parameterDistribution, delimiter=',')\n","sub_path":"Broadening/BayesianInferenceForResearchers/Code/HMCForCrypt.py","file_name":"HMCForCrypt.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"505496709","text":"DEBUG = True\nTEMPLATE_DEBUG = DEBUG\nDATABASE_ENGINE = 'sqlite3'\nDATABASE_NAME = ':memory:'\nINSTALLED_APPS = ( \n 'django.contrib.contenttypes',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'publish',\n )\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n# 'django.template.loaders.eggs.load_template_source',\n)\n \nTESTING_PUBLISH=True\n \n# enable this for coverage (using django test coverage\n# http://pypi.python.org/pypi/django-test-coverage )\n#TEST_RUNNER = 'django-test-coverage.runner.run_tests'\n#COVERAGE_MODULES = ('publish.models', 'publish.admin', 'publish.actions', 'publish.utils', 'publish.signals')\n","sub_path":"tests/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"417922147","text":"import RPi.GPIO as GPIO #Importing GPIO module\nimport paho.mqtt.client as mqtt #Importing Mosquitto Module\nimport time #Importing time to use delays\nimport random #Importing random to use generator of random numbers\n \n \nGPIO.setmode(GPIO.BCM) #Deciding whether our GPIO pin numeration is BCM or BOARD\nGPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Declaring 21 pin as INPUT with Pullup Resistor\n\n \n\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n \n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n client.subscribe(\"$SYS/#\")\n \n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n \nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n \nclient.connect(\"127.0.0.1\", 1883, 60)\n \n\n \n# The activity after the interrupt on 21 pin\ndef interrupt_big_red_button(pin):\n\tclient.publish('home-assistant/lottery/number', 'triggered' )\n\ttime.sleep(1)\n\tclient.publish('home-assistant/lottery/number', 'disarmed' )\n\t \n#Setup the interrupt on 21 pin with detection of falling edge \nGPIO.add_event_detect(21, GPIO.FALLING, callback = interrupt_big_red_button)\n \n \nwhile True:\n time.sleep(1)\n\n \n\n# Blocking call that processes network traffic, dispatches callbacks and\n# handles reconnecting.\n# Other loop*() functions are available that give a threaded interface and a\n# manual interface.\nclient.loop_forever()\n","sub_path":"RaspberryPi/gpio/buttonscript.py","file_name":"buttonscript.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"354244170","text":"import pymunk as pm\nimport pygame as pg\nimport pymunk.pygame_util as pm_pg_util\n\nclass WorldBody(pm.Body):\n def __init__(self, parent, mass=0, moment=0, body_type=pm.Body.DYNAMIC):\n super().__init__(mass, moment, body_type)\n self.parent = parent\n\nclass WorldObj():\n def __init__(self):\n self.id = 0\n self.colour = (255,255,255)\n self.sound = 0\n self.drag = None\n\n self.smart = False\n self.consumes = None\n self.consumable = False\n\n self.name = None\n\n def _init_body(self, mass, radius, drag, colour, name):\n self.moment = pm.moment_for_circle(mass, 0, radius)\n self.body = WorldBody(self, mass, self.moment)\n self.shape = pm.Circle(self.body, radius)\n self.drag = drag\n self.colour = colour\n self.name = name\n\n def _init_consumption(self, consumes, consumable):\n self.consumes = consumes\n self.consumable = consumable\n\n def set_position(self, x, y):\n self.body.position = x, y\n\n def get_body(self):\n return self.body\n\n def display(self, screen):\n p = pm_pg_util.to_pygame(self.body.position, screen)\n pg.draw.circle(screen, self.colour, p, int(self.shape.radius), 2)\n return p\n","sub_path":"worldobj.py","file_name":"worldobj.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"96500354","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\" \n if(head==None): return (False) #no elements\n if (head.next == None): return (False) #single element\n\n fast = slow = head\n while(fast and slow and fast.next):\n #important case of setting fast.next is not None :: https://stackoverflow.com/questions/28972098/nonetype-object-has-no-attribute-next-error\n fast = fast.next.next\n slow = slow.next\n if(fast == slow):\n return(True)\n return(False)\n\n ## My original brute force::\n # if(head==None): return (False)\n # print(head)\n # if (head.next == None): #single element\n # # print('returning false for sure ', head, head.next)\n # return (False)\n\n # arr = []\n # while(head):\n # if (head in arr):\n # return (True)\n # arr.append(head)\n # head = head.next\n\n # return(False)\n\n'''\nother method: \n1. fast and slow way:: https://leetcode.com/problems/linked-list-cycle/solutions/1829489/c-easy-to-understand-2-pointer-fast-slow/\n2. \n'''\n","sub_path":"LC_141_linked_list_cycle.py","file_name":"LC_141_linked_list_cycle.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"16272033","text":"class LCD:\n\n #Sets color and message on LCD Display\n def lcd_message(self, color, message):\n lcd.clear()\n color_codes = {'red':[[1],[0],[0]], 'green':[[0],[1],[0]], 'blue':[[0],[0],[1]], 'purple':[[1],[0],[1]], 'yellow':[[1],[1],[0]], 'white':[[1],[1],[1]]}\n for colors in color_codes:\n if color == colors:\n colorcode = color_codes.get(color)\n lcd.set_color(int(''.join(map(str,colorcode[0]))),int(''.join(map(str,colorcode[1]))),int(''.join(map(str,colorcode[2]))))\n # elif color != colors and colors == 'red':\n # print \"Sorry, color was not found!\"\n lcd.message(str(message))\n","sub_path":"Lcd.py","file_name":"Lcd.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"486643246","text":"\"\"\"Storage respone objects.\"\"\"\n\nfrom typing import Any, Mapping, Optional\n\nfrom requests import Response\n\nfrom ambra_sdk.exceptions.storage import (\n AmbraResponseException,\n NotFound,\n PermissionDenied,\n)\n\n\ndef check_response(\n response: Response,\n url: str,\n errors_mapping: Optional[Mapping[int, Any]] = None,\n) -> Response:\n \"\"\"Check response on errors.\n\n :param response: response obj\n :param url: full url str\n :param errors_mapping: map of error name and exception\n\n :return: response object\n\n :raises AmbraResponseException: Unknown exception\n :raises PermissionDenied: Permission denied\n :raises NotFound: Url or args is wrong\n :raises exception: Some ambra storage response exception\n\n \"\"\"\n status_code = response.status_code\n if status_code == 200:\n return response\n # 202 - Accepted\n if status_code == 202:\n return response\n\n if errors_mapping is not None and status_code in errors_mapping:\n exception = errors_mapping[status_code]\n raise exception\n elif status_code == 404:\n description = 'Url is wrong: {url}' \\\n .format(url=url)\n raise NotFound(description)\n elif status_code == 403:\n description = 'Access denied or wrong sid'\n raise PermissionDenied(description)\n raise AmbraResponseException(\n code=status_code,\n description='Unknown status code',\n )\n","sub_path":"ambra_sdk/storage/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"635090474","text":"class EnetpulseProtocol(WebSocketServerProtocol):\n\n DEFAULT_HEARTBEAT_INTERVAL = 10\n\n def __init__(self, heartbeat_interval=None):\n WebSocketServerProtocol.__init__(self)\n self.heartbeat_interval = heartbeat_interval or self.DEFAULT_HEARTBEAT_INTERVAL\n self.start_position = 0\n self.authenticated = False\n self.stopped = False\n\n def onConnect(self, request):\n print('* onConnect [request = {}]'.format(request))\n\n if 'startPosition' in request.params:\n try:\n self.start_position = int(request.params['startPosition'][0])\n except (ValueError, TypeError):\n pass\n\n def onOpen(self):\n print('* Connection initiated.')\n\n self.factory.register(self)\n\n thread_heartbeat = Timer(self.heartbeat_interval, self.send_heartbeat_message)\n thread_heartbeat.daemon = True\n thread_heartbeat.start_input_reader()\n\n def onMessage(self, payload, is_binary=False):\n print('* Recv : [{}]'.format(payload))\n\n if 'auth' in payload and not self.authenticated:\n msg = '{\"message\":\"Authorisation accepted\"}'\n self.send_text(msg)\n self.authenticated = True\n self.send_previously_sent_messages()\n\n def send_previously_sent_messages(self):\n print('* Sending messages with ID {} and up...'.format(self.start_position))\n for m in self.factory.message_session.get_messages(self.start_position):\n self.send_text(m.value)\n\n def onClose(self, was_clean, code, reason):\n print('* onClose [wasClean: {}, code: {}, reason: {}]'.format(was_clean, code, reason))\n self.stopped = True\n\n def connectionLost(self, reason):\n WebSocketServerProtocol.connectionLost(self, reason)\n self.factory.unregister(self)\n\n def send_text(self, text):\n self.sendMessage(text)\n\n if 'Heartbeat sent at ' not in text:\n print('* Sent : [{}]'.format(text))\n\n def send_heartbeat_message(self):\n if self.stopped:\n return\n\n timestamp = '{}Z'.format(datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3])\n msg = '{{\"message\":\"Heartbeat sent at {}\"}}'.format(timestamp)\n self.send_text(msg)\n\n thread_heartbeat = Timer(self.heartbeat_interval, self.send_heartbeat_message)\n thread_heartbeat.daemon = True\n thread_heartbeat.start_input_reader()\n\n def disconnect(self):\n self.sendClose(code=1000, reason='Closed by request.')\n","sub_path":"Scripts/feeds-solution/feeds_provider_mock_v2/enetpulse_server/enetpulse_protocol.py","file_name":"enetpulse_protocol.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"212084255","text":"import adsk.core, adsk.fusion, traceback\nimport os.path, sys\n\ndef export_body(body, output_dir, export_mgr):\n fileName = output_dir + \"/\" + body.name\n stlExportOptions = export_mgr.createSTLExportOptions(body, fileName)\n stlExportOptions.sendToPrintUtility = False\n export_mgr.execute(stlExportOptions)\n \ndef make_body_name_prefix(project_name):\n # design name \n docName = project_name.rsplit(' ',1)[0]\n\n # make docName camel case\n docName = docName.lower()\n docName = docName.replace(' ', '_')\n docName = docName.replace('-', '_')\n\n return docName\n \ndef run(context):\n ui = None\n try:\n app = adsk.core.Application.get()\n ui = app.userInterface\n \n # get active design \n product = app.activeProduct\n design = adsk.fusion.Design.cast(product)\n\n if not design:\n ui.messageBox('No active Fusion design', 'No Design')\n return\n\n \n # get root component in this design\n rootComp = design.rootComponent\n \n # create a single exportManager instance\n exportMgr = design.exportManager\n \n # get the script location\n scriptDir = os.path.dirname(os.path.realpath(__file__)) \n\n # export dir\n stlDir = os.path.join(scriptDir, 'stl')\n\n # create folder if it does not exist\n if not os.path.exists(stlDir):\n os.makedirs(stlDir)\n\n # make sure the timeline is at the very end\n design.timeline.moveToEnd()\n \n # turn the project name e.g. Pixel Pump v251 into pixel_pump\n name_prefix = make_body_name_prefix(rootComp.name)\n\n exportedFileCount = 0\n\n # export the body one by one in the design to a specified file\n for body in rootComp.bRepBodies:\n # check if componentName starts with docName so we only export the components we want\n if body.name.startswith(name_prefix):\n export_body(body, stlDir, exportMgr)\n exportedFileCount += 1\n\n\n # export the occurrence one by one in the root component to a specified file\n for i in range(0, rootComp.allOccurrences.count):\n occ = rootComp.allOccurrences.item(i)\n bodies = occ.component.bRepBodies\n for body in bodies:\n if body.name.startswith(name_prefix):\n export_body(body, stlDir, exportMgr)\n exportedFileCount += 1\n\n\n\n ui.messageBox('Successfully exported {} STL files'.format(exportedFileCount))\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))","sub_path":"export-stl.py","file_name":"export-stl.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"91195395","text":"from jax import numpy as jnp, random as jrandom\nfrom jax import jit, grad, vmap, lax, ops\n\nfrom dataset_reduction.opt_design.greedy.common import jnp_order_to_inds_wrapper\n\n\n__all__ = ['run']\n\n\ndef _loss_fn(G, g0, alpha, beta, chosen, i: int, w: float):\n g = G[chosen].sum(axis=0) + g0\n\n v = G[i]\n H_new_i = jnp.linalg.inv(H + w * v[:, None] * v[None, :])\n g_new = g + w * v\n\n return jnp.trace(H_new_i) * beta + g_new.dot(H_new_i).dot(H_new_i).dot(g_new) * (1 - beta)\n\n\n_g_loss_fn_map = jit(\n vmap(\n lambda G, g0, alpha, beta, chosen, v: grad(_loss_fn, -1)(G, g0, alpha, beta, chosen, v, 0.),\n (None, None, None, None, None, 0),\n ),\n static_argnums=(4,),\n)\n\n\ndef prototype_with_asserts(\n G: jnp.ndarray, g0: jnp.ndarray, alpha: float, beta: float, n_elems: int, forbidden: jnp.ndarray\n) -> jnp.ndarray:\n choose_order = jnp.ones(len(G), dtype=jnp.int32) * -1\n\n if g0 is None:\n g0 = jnp.zeros(G.shape[1])\n g = g0\n\n M = jnp.identity(G.shape[1]) * alpha\n Mi = jnp.identity(G.shape[1]) / alpha\n G_Mi = G.dot(Mi)\n\n for step in range(n_elems):\n vals_1 = (G_Mi * G_Mi).sum(axis=-1)\n\n first = Mi.dot(g)\n second = G_Mi - G_Mi * (G * Mi.dot(g)[None, :]).sum(axis=-1, keepdims=True)\n vals_2 = 2 * (first[None, :] * second).sum(axis=-1)\n\n vals = vals_1 * beta - vals_2 * (1 - beta)\n\n assert jnp.allclose(vals, -_g_loss_fn_map(G, g0, alpha, beta, choose_order != -1, jnp.arange(len(G))), rtol=1e-2)\n assert jnp.allclose(\n Mi,\n jnp.linalg.inv(alpha * jnp.identity(G.shape[1]) + (G[choose_order != -1, :, None] * G[choose_order != -1, None, :]).sum(axis=0)),\n rtol=1e-2,\n )\n assert jnp.allclose(g, g0 + G[choose_order != -1].sum(axis=0))\n\n ind = jnp.argmax(jnp.where(jnp.logical_or(choose_order != -1, forbidden), jnp.min(vals) - 1, vals))\n assert choose_order[ind] == -1\n\n choose_order = ops.index_update(choose_order, ind, step)\n\n v = G[ind]\n\n M += v[None, :] * v[:, None]\n g += v\n a = Mi.dot(v)\n Mi -= a[None, :] * a[:, None] / (1 + v.dot(a))\n G_Mi -= a[None, :] * G.dot(a)[:, None] / (1 + v.dot(a))\n\n return choose_order\n\n\n@jit\ndef jitted(\n G: jnp.ndarray, g0: jnp.ndarray, alpha: float, beta: float, n_elems: int, forbidden: jnp.ndarray\n) -> jnp.ndarray:\n choose_order = jnp.ones(len(G), dtype=jnp.int32) * -1\n\n if g0 is None:\n g0 = jnp.zeros(G.shape[1])\n g = g0\n\n Mi = jnp.identity(G.shape[1]) / alpha\n G_Mi = G.dot(Mi)\n\n def body(step, args):\n Mi, g, G_Mi, choose_order = args\n\n vals_1 = (G_Mi * G_Mi).sum(axis=-1)\n\n first = Mi.dot(g)\n second = G_Mi - G_Mi * (G * Mi.dot(g)[None, :]).sum(axis=-1, keepdims=True)\n vals_2 = 2 * (first[None, :] * second).sum(axis=-1)\n\n vals = vals_1 * beta - vals_2 * (1 - beta)\n\n ind = jnp.argmax(jnp.where(jnp.logical_or(choose_order != -1, forbidden), jnp.min(vals) - 1, vals))\n choose_order = ops.index_update(choose_order, ind, step)\n\n v = G[ind]\n\n g += v\n a = Mi.dot(v)\n Mi -= a[None, :] * a[:, None] / (1 + v.dot(a))\n G_Mi -= a[None, :] * G.dot(a)[:, None] / (1 + v.dot(a))\n\n return Mi, g, G_Mi, choose_order\n\n return lax.fori_loop(0, n_elems, body, (Mi, g, G_Mi, choose_order))[-1]\n\n\nrun = jnp_order_to_inds_wrapper(jitted)\n","sub_path":"dataset_reduction/opt_design/greedy/A_with_delta.py","file_name":"A_with_delta.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"578735454","text":"\nimport os\nimport shutil\nimport tempfile\nimport unittest\nfrom phloem.conf import BackupConfException\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nfrom phloem.conf import BackupConf\n\n__dir__ = os.path.abspath(os.path.dirname(__file__))\n\nclass TestBackupConf(unittest.TestCase):\n def test_read_good_conf_file(self):\n \"\"\"\n Read the configuration file, creating a valid configuration object.\n \"\"\"\n\n good_configuration = \"\"\"[main]\ntype = mysql\nschedule = * */2 * * *\n\n[backup]\nsomething = here\n\"\"\"\n good_dict = {'main': {'type': 'mysql', 'schedule': '* */2 * * *'}, 'backup': {'something': 'here'}}\n\n good_conf_fd, good_conf_path = tempfile.mkstemp()\n os.write(good_conf_fd, good_configuration)\n\n good_parser = BackupConf()\n good_parsed = good_parser.parse_config(good_conf_path)\n\n self.assertEqual(good_dict, good_parsed)\n\n os.remove(good_conf_path)\n\n def test_read_bad_conf_file(self):\n \"\"\"\n Read the configuration file, failing on bad options or formatting.\n \"\"\"\n\n bad_configuration = \"\"\"[main]\ntype = mysql\nschedule * */2 * * *\n\n[backup\nsomething = here\n\"\"\"\n bad_conf_fd, bad_conf_path = tempfile.mkstemp()\n os.write(bad_conf_fd, bad_configuration)\n\n bad_parser = BackupConf()\n\n self.assertRaises(BackupConfException, bad_parser.parse_config, bad_conf_path)\n\n os.remove(bad_conf_path)\n\n def test_parse_backups(self):\n \"\"\"\n Read backup definition files and parse structure\n \"\"\"\n\n mysql_conf = \"\"\"[loader]\nloader = phloem.loaders.mysql.MySQLLoader\nhosts = db1a, db2a\nexcluded_tables = test\nexcluded_databases = test\nuser = root\npasswd = root\n\n[generations]\ndaily = 0 0 * * *\n\n[gz]\ntube = phloem.tubes.gzip_tube.GZTube\nparent = loader\ncompression_level = 5\n\n[gpg]\nparent = gz\ntube = phloem.tubes.gpg_tube.GPGTube\nkey = 'asdf'\n\"\"\"\n tmp_backup_path = tempfile.mkdtemp()\n mysql_f = os.path.join(tmp_backup_path, 'mysql')\n\n with open( mysql_f, 'w') as mysql_file_handle:\n mysql_file_handle.write(mysql_conf)\n\n logger.debug(\"Tempfiles in %s: %s\" % (tmp_backup_path, os.listdir(tmp_backup_path)) )\n\n parser = BackupConf()\n parsed = parser.parse_backups(path=tmp_backup_path)\n\n logger.debug(\"Parsed backups are: %s\" % parsed)\n\n shutil.rmtree(tmp_backup_path)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"src/phloem/test/test_conf.py","file_name":"test_conf.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"474926506","text":"''''' \nInsert dict into database \n@author: longfellow \n''' \n#-*- encoding:utf-8 -*-\n \nimport pymysql \n \ndef InsertData(TableName,dic): \n\ttry: \n\t\tdb = pymysql.connect('localhost','root','3660033','dota')\n\t\tcursor = db.cursor() \n\t\tCOLstr='' #列的字段 \n\t\tROWstr='' #行字段 \n\n\t\tColumnStyle=' VARCHAR(20)' \n\t\tfor key in dic.keys(): \n\t\t\tCOLstr=COLstr+' '+key+ColumnStyle+','\n\t\t\tROWstr=(ROWstr+'\"%s\"'+',')%(dic[key])\n\t\n\t\ttry:\n\t\t\tcursor.execute(\"SELECT * FROM %s\"%(TableName))\n\t\t\tcursor.execute(\"INSERT INTO %s VALUES (%s)\"%(TableName,ROWstr[:-1]))\n\t\t\tdb.commit()\n\t\t\tdb.close()\n\t\texcept:\n\t\t\tdb.rollback()\n\texcept:\n\t\tprint(\"异常报错!\")\n\nif __name__ == '__main__':\n\tdic={\"a\":\"b\",\"c\":\"d\"}\n\tInsertData('test',dic)\n","sub_path":"py_dic_insert.py","file_name":"py_dic_insert.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"114676807","text":"from flask_restful import Resource, reqparse\nfrom ..models.usuario import UsuarioModel\nfrom ..models.movimentacao import MovimentacaoModel\nimport bcrypt\nfrom flask import jsonify\n\natributos = reqparse.RequestParser()\natributos.add_argument('nome')\natributos.add_argument('login')\natributos.add_argument('senha')\n\nclass Usuarios():\n def get():\n return jsonify([usuario.json() for usuario in UsuarioModel.query.filter(UsuarioModel.idusuario!=15).order_by(UsuarioModel.idusuario.desc())])\n\nclass NovoUsuario():\n def post():\n dados = atributos.parse_args()\n\n if UsuarioModel.find_loginUsuario(dados.login):\n return {\"message\": \"Usuário com login: '{}' já cadastrado!\".format(dados.login)}, 400\n\n usuario = UsuarioModel(None, dados.nome, dados.login, bcrypt.hashpw(dados.senha.encode('utf8'), bcrypt.gensalt()))\n\n try:\n usuario.save_usuario()\n except:\n return {\"message\": \"Ocorreu um erro ao salvar o usuário!\"}, 500\n return usuario.json()\n\nclass Usuario():\n\n def get(id):\n usuario = UsuarioModel.find_usuario(id)\n if usuario:\n return usuario.json()\n return {\"message\": \"Usuário não encontrado.\"}, 404\n\n def put(id):\n dados = atributos.parse_args()\n\n usuarioLogin = UsuarioModel.find_loginUsuario(dados.login)\n if usuarioLogin:\n if usuarioLogin.idusuario != id:\n return {\"message\": \"Login: '{}' já usado para outro usuário\".format(dados.login)}, 400\n\n usuarioEncontrado = UsuarioModel.find_usuario(id)\n if usuarioEncontrado:\n usuarioEncontrado.update_usuario(dados.nome, dados.login, bcrypt.hashpw(dados.senha.encode('utf8'), bcrypt.gensalt()))\n usuarioEncontrado.save_usuario()\n return usuarioEncontrado.json(), 200\n usuario = UsuarioModel(None, dados.nome, dados.login, bcrypt.hashpw(dados.senha.encode('utf8'), bcrypt.gensalt()))\n try:\n usuario.save_usuario()\n except:\n return {\"message\": \"Ocorreu um erro ao gravar o usuário\"}, 500\n return usuario.json(), 201\n\n def delete(id):\n usuario = UsuarioModel.find_usuario(id)\n if usuario:\n movimentacao = MovimentacaoModel.find_movimentacaoUsuario(usuario.idusuario)\n if movimentacao:\n return {\"message\": \"Não é possível excluir um usuário que já lançou movimentação!\"}, 400\n usuario.delete_usuario()\n try:\n usuario.delete_usuario()\n except:\n return {\"message\": \"Ocorreu um erro ao excluir o usuário\"}, 500\n return {\"message\": \"Usuário removido\"}\n return {\"message\": \"Usuário não encontrado\"}, 404\n","sub_path":"api/resources/usuario.py","file_name":"usuario.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"212884183","text":"import matplotlib.pyplot as plt\nimport csv\n\nvoltage = []\ncurrent = []\n\n# read data from text file\nwith open('data/sample.txt') as file:\n\treader = csv.reader(file, delimiter='\\t')\n\t# trow away first line with labels\n\tnext(reader)\n\tfor line in reader:\n\t voltage.append(float(line[3]))\n\t current.append(float(line[2]))\n\n# set font similar to latex\nplt.rc('font', family='serif')\n\n# plot data\nplt.plot(current, voltage, '.')\n\n# add labels to plot\nplt.xlabel('Current [A]')\nplt.ylabel('Voltage [V]')\nplt.title('Ebike battery data', fontsize='16')\nplt.show()\n\n","sub_path":"python/plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134637699","text":"import requests\nimport base64\nimport cv2\nfrom threading import Thread\nfrom datetime import datetime\nimport time\nfrom pygame import mixer\nimport tkinter\nimport pickle\nimport pymysql\nimport pyzbar.pyzbar as pyzbar\nimport numpy\nfrom tkinter import *\nimport tkinter.ttk as ttk\nfrom PIL import Image, ImageDraw, ImageFont,ImageTk\nfrom tkinter import ttk\nfrom twilio.rest import Client\nfrom MXMqtt import MXMqtt\nimport time\nimport os\nimport win32com.client\n\nspeaker = win32com.client.Dispatch(\"SAPI.SpVoice\")\nMQTTMOST = \"mqtt.16302.com\"\nMQTTPORT = 1883\nmqtt = MXMqtt(MQTTMOST,MQTTPORT)\n\ntopic = \"sp\"\nmqtt.SUB(topic)\nc=[('6928820071755', '欧莱雅男士洁面乳', 37.05, 1, '2020-07-01 14:42'), ('6921168509256', '农夫山泉', 1.9, 1, '2020-07-01 14:42')]\n\n\nisbn=['6928820071755','6933211451924','6921168509256','7208061645','7302275491','6920487503808','9787506366649','6902088113143']\nname=['欧莱雅男士洁面乳','九制陈皮','农夫山泉550ml','《追风筝的人》','《阿波罗是如何飞到月球的》','德生牌收音机PL-380','《生死疲劳》','清扬洗发露200g']\nprice=[39,29,2,29,69,399,39,28]\nnumber=[1,1,1,1,1,1,1,1]\ndic=dict(i6928820071755=0,i6933811788338=1,i6921168509256=2,i9787208061644=3,i9787302275497=4,i6920487503808=5,i9787506366649=6,i6902088113143=7)\n\ncap=cv2.VideoCapture(0)\n\ndef play1():\n mixer.init()\n mixer.music.load('iphone.mp3')\n mixer.music.play()\ndef play():\n mixer.init()\n mixer.music.load('11750.mp3')\n mixer.music.play()\n\ndef normal(i):\n d=(isbn[i],name[i],price[i],number[i],datetime.now().strftime('%Y-%m-%d %H:%M'))\n return d\ndef normal_loacl(i):\n d=(name[i],price[i],number[i])\n return d\ndef member(i):\n d=(isbn[i],name[i],0.95*price[i],number[i],datetime.now().strftime('%Y-%m-%d %H:%M'))\n return d\ndef member_loacl(i):\n d=(name[i],round(0.95*price[i],2),number[i])\n return d\ndef note(i):\n d=name[i]+'—'+str(number[i])+'—'+str(round(0.95*price[i],2))+'元\\n'\n return d\ndef HA_send(i):\n d=[name[i],str(number[i])]\n return d\ndef mq(bill_HA):\n m=''\n for i in bill_HA:\n m = m+i+','\n return m\n\ndef message(x):\n account_sid = \"ACa349b9fa5e92483e512cb6f9ca284134\"\n auth_token = \"c8e6f0c54286167e12fc62b094d1c47b\"\n client = Client(account_sid, auth_token)\n message = client.messages.create(\n to=\"+8618217148825\", \n from_=\"+12058528426\",\n body=x)\n print(x)\n print(type(x))\ndef decodeDisplay(imagex1):\n gray = cv2.cvtColor(imagex1, cv2.COLOR_BGR2GRAY)\n barcodes = pyzbar.decode(gray)\n global barcodeData\n global ii\n global bill,bill_HA,bill_note,sign_up_pay\n global judge\n global pay\n for barcode in barcodes:\n (x, y, w, h) = barcode.rect\n cv2.rectangle(imagex1, (x, y), (x + w, y + h), (0, 255, 0), 2)\n barcodeData = barcode.data.decode(\"utf-8\")\n barcodeType = barcode.type\n #更换为:\n img_PIL = Image.fromarray(cv2.cvtColor(imagex1, cv2.COLOR_BGR2RGB)) \n imagex1 = cv2.cvtColor(numpy.asarray(img_PIL), cv2.COLOR_RGB2BGR)\n print(barcodeData)\n print(type(barcodeData))\n \n if barcodeData=='莉俶ャセ' or barcodeData=='蜿冶エァ':\n # play1()\n break\n elif len(barcodeData)>2 and judge==0:\n play()\n ii+=1\n a=dic.get('i'+barcodeData)\n bill+=[normal(a)]\n bill_HA+=HA_send(a)\n pay+=price[a]\n bill_note+=(note(a))\n tkinter.Label(sign_up_pay, text=('总额:'+str(round(pay,1))), font=('黑体', 15),bg='white').place(x=379, y=617)\n print(bill)\n insert(normal_loacl(a))\n time.sleep(1)\n elif len(barcodeData)>2 and judge==1:\n play()\n ii+=1\n a=dic.get('i'+barcodeData)\n bill+=[member(a)]\n bill_HA+=HA_send(a)\n pay+=round(0.95*price[a],2)\n bill_note+=note(a)\n tkinter.Label(sign_up_pay, text=('总额:'+str(round(pay,1))), font=('黑体', 15),bg='white').place(x=373, y=617)\n print(mq(bill_HA))\n print('------')\n insert(member_loacl(a))\n time.sleep(1)\n cv2.imshow(\"camera\", imagex1)\ndef insert(x):\n print('aa')\n print(x)\n print('aa')\n global tree\n tree.insert('',0,values=(x))\ndef detect():\n cv2.namedWindow(\"camera\",cv2.WINDOW_NORMAL)\n camera = cv2.VideoCapture(0)\n global barcodeData\n global bill,bill_HA,bill_note\n global ii,pay\n bill=[]\n ii=0\n bill_HA=[]\n barcodeData=0\n pay=0\n bill_note='\\n'\n while True:\n ret, frame = camera.read()\n #print(ret.shape)\n decodeDisplay(frame)\n if(cv2.waitKey(5)==27):\n break\n elif barcodeData=='莉俶ャセ':\n play1()\n #bill_note+=('总额'+str(round((pay),2))+'元')\n time=datetime.now().strftime('%Y-%m-%d %H:%M')\n bill_note='亲爱的顾客:\\n 本次到店消费总额'+str(round((pay),2))+'元,祝您生活愉快。\\n'+str(time)\n print(bill_note)\n print(type(bill_note))\n info(ii)\n def finish():\n sign_up_finish= tkinter.Toplevel(top)\n global sign_up_count,w6,h6,background_image6,aaa\n #sign_up_finish = tkinter.Toplevel(top)\n sign_up_finish.geometry('%dx%d+526+0' % (w6,h6))\n background_label = tkinter.Label(sign_up_finish, image=background_image6)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n tkinter.Label(sign_up_finish, text='成支\\n功付' ,font=('隶书', 32),bg='lavenderblush').place(x=217, y=200)\n aaa=('本次消费'+str(round((pay),1))+'元')\n tkinter.Label(sign_up_finish, text=(aaa) ,font=('隶书', 18),bg='lavenderblush').place(x=187, y=430)\n tkinter.Label(sign_up_finish, text=('消费满100元,可免费停车2小时') ,font=('隶书', 18),bg='lavenderblush').place(x=95, y=460)\n finish()\n def bye():\n global aaa\n speaker.Speak((aaa+',祝您生活愉快'))\n Thread(target=bye).start()\n mqtt.PUB(topic,mq(bill_HA))\n # message(bill_note)\n print(len(bill_note))\n break\n elif barcodeData=='蜿冶エァ':\n global sign_up_out\n def bye_out():\n speaker.Speak('这是你的外卖,路上注意安全')\n Thread(target=bye_out).start()\n tkinter.Label(sign_up_out, text='成取\\n功货' ,font=('隶书', 32),bg='lavenderblush').place(x=217, y=200)\n play1()\n break\n camera.release()\n cv2.destroyAllWindows()\ndef finish():\n sign_up_finish= tkinter.Toplevel(top)\n global sign_up_count,w6,h6,background_image6\n #sign_up_finish = tkinter.Toplevel(top)\n sign_up_finish.geometry('%dx%d+0+0' % (w6,h6))\n background_label = tkinter.Label(sign_up_finish, image=background_image6)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n tkinter.Label(sign_up_finish, text='出示付款码即可付款 折扣95%' ,font=('黑体', 16),bg='white').place(x=47, y=617)\n\n \ndef info(i):\n global bill\n conn = pymysql.connect('localhost', 'root', '', '无人超市')\n cursor = conn.cursor()\n sql = \"INSERT INTO 收银(ISBN,商品名,价格,数量,时间) VALUES (%s,%s,%s,%s,%s)\"\n try:\n for x in range(0,i):\n print(x)\n cursor.execute(sql,bill[x])\n print('done')\n conn.commit()\n except:\n conn.rollback()\n conn.close()\ndef info_count():\n conn = pymysql.connect('localhost', 'root', '', '无人超市')\n cursor = conn.cursor()\n sql = 'SELECT * FROM 收银'\n global results\n try:\n cursor.execute(sql)\n results = cursor.fetchall()\n for row in results:\n id = row[0]\n name = row[1]\n age = row[2]\n address = row[3]\n create_time = row[4]\n except:\n conn.rollback()\n conn.close()\n\ndef local():\n global sign_up_pay\n global tree\n style = ttk.Style()\n style.configure(\"Treeview\",font=(None, 12,'bold'))\n style.configure(\"Treeview.Heading\",font=('楷体', 13))\n columns = ('商品名','价格','数量')\n tree = ttk.Treeview(sign_up_pay,show = \"headings\",columns = columns)\n tree.column(\"商品名\",width=160,anchor='center')\n tree.column(\"价格\",width=40,anchor='center')\n tree.column(\"数量\",width=20,anchor='center')\n tree.heading(\"商品名\",text=\"商品名\")\n tree.heading(\"价格\",text=\"价格\")\n tree.heading(\"数量\",text=\"数量\")\n tree.pack(expand='y',ipadx=105,ipady=109)\n tree.quit\n\ndef local_count():\n global sign_up_count\n global tree_count,results\n count=0\n info_count()\n style = ttk.Style()\n style.configure(\"Treeview\",font=(None, 10))\n style.configure(\"Treeview.Heading\",font=(None, 12,'bold'))\n columns = ('ISBN','商品名','价格','数量','消费时间')\n tree_count = ttk.Treeview(sign_up_count, show = \"headings\", columns = columns)\n tree_count.column(\"ISBN\",width=90)\n tree_count.column(\"商品名\",width=120)\n tree_count.column(\"价格\",width=50,anchor='center')\n tree_count.column(\"数量\",width=25,anchor='center')\n tree_count.column(\"消费时间\",width=100)\n tree_count.heading(\"ISBN\",text=\"ISBN\")\n tree_count.heading(\"商品名\",text=\"商品名\")\n tree_count.heading(\"价格\",text=\"价格\")\n tree_count.heading(\"数量\",text=\"数量\")\n tree_count.heading(\"消费时间\",text=\"消费时间\")\n for row in results:\n a = row[0]\n b = row[1]\n c = row[2]\n d = row[3]\n e = row[4]\n count+=c\n tree_count.insert('',0,values=(a,b,c,d,e))\n time=datetime.now().strftime('%m-%d %H:%M')\n tkinter.Label(sign_up_count, text=('销售总额:'+str(round(count,2))+'元' ),font=('黑体', 17),bg='white').place(x=18, y=637)\n tkinter.Label(sign_up_count, text=('更新时间:'+str(time)) ,font=('黑体', 17),bg='white').place(x=18, y=666)\n\n print(count)\n print('cccc')\n tree_count.pack(expand='y',ipadx=57,ipady=129)\n tree_count.quit\ndef enter():\n global sign_up_pay,w1,h1,background_image1\n sign_up_pay = tkinter.Toplevel(top)\n sign_up_pay.geometry('%dx%d+0+0' % (w1,h1))\n background_label = tkinter.Label(sign_up_pay, image=background_image1)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n tkinter.Label(sign_up_pay, text='出示付款码即可付款 折扣95%' ,font=('黑体', 16),bg='white').place(x=47, y=617)\n\n local()\n global judge\n judge=1\n Thread(target=detect).start()\n\ndef feedback():\n sign_up = tkinter.Toplevel(top) \n global w0,h0,background_image0,ww,hh,background_imagee,w3,h3,background_image3,over\n over=0\n image0 =Image.open('logo1.gif')\n background_image0 = ImageTk.PhotoImage(image0)\n w0 = background_image0.width()\n h0 = background_image0.height() \n def no():\n global judge,sign_up_pay,w0,h0,background_image0\n sign_up_pay = tkinter.Toplevel(top)\n sign_up_pay.geometry('%dx%d+0+0' % (w0,h0))\n background_labe0 = tkinter.Label(sign_up_pay, image=background_image0)\n background_labe0.place(x=0, y=0, relwidth=1, relheight=1)\n tkinter.Label(sign_up_pay, text='出示付款码即可付款' ,font=('黑体', 16),bg='white').place(x=47, y=617)\n local()\n judge=0\n Thread(target=detect).start()\n # finish()\n def yes():\n sign_up = tkinter.Toplevel(top)\n global w3,h3,background_image3\n sign_up.geometry('%dx%d+0+0' % (w3,h3))\n background_label3 = tkinter.Label(sign_up, image=background_image3)\n background_label3.place(x=0, y=0, relwidth=1, relheight=1)\n var_usr_name = tkinter.StringVar()\n entry_usr_name = tkinter.Entry(sign_up, textvariable=var_usr_name, font=('Arial', 18),width=13)\n entry_usr_name.place(x=172,y=410)\n tkinter.Label(sign_up, text='请输入会员号' ,font=('隶书', 20),bg='white',fg='darkgoldenrod').place(x=165, y=350)\n def login(): \n if entry_usr_name.get()=='18217148825':\n enter()\n # login = tkinter.Button(sign_up, text='确定',font=('Times', 20,'bold'), command=login)\n login = tkinter.Button(sign_up, text='确定',font=('楷体', 23,'bold'),bg='orange',fg='white', command=login)\n login.place(x=210, y=510)\n print('我在这里')\n sign_up.geometry('%dx%d+0+0' % (ww,hh))\n background_labell = tkinter.Label(sign_up, image=background_imagee)\n background_labell.place(x=0, y=0, relwidth=1, relheight=1)\n login = tkinter.Button(sign_up, text='会员用户',font=('楷体', 23,'bold'),bg='orange',fg='white', command=yes)\n login.place(x=180, y=350)\n login = tkinter.Button(sign_up, text='普通用户',font=('楷体', 23,'bold'),bg='orange',fg='white', command=no)\n login.place(x=180, y=470)\n tkinter.Label(sign_up, text='会员用户享9.5折优惠!' ,font=('隶书', 19),bg='white',fg='red').place(x=133, y=570)\n if over==1:\n finish()\ndef admin():\n login=tkinter.Toplevel(top)\n global w3,h3,background_image3\n login.geometry('%dx%d+0+0' % (w3,h3))\n background_label3 = tkinter.Label(login, image=background_image3)\n background_label3.place(x=0, y=0, relwidth=1, relheight=1)\n var_usr_name = tkinter.StringVar()\n \n## canvas=tkinter.Canvas(login)\n## imagefile=tkinter.PhotoImage(file='logo.gif')\n## image=canvas.create_image(0,0,anchor='nw',image=imagefile)\n## canvas.pack(side='top')\n password = StringVar()\n name = tkinter.Entry(login, font=('Times', 18,'bold'),width=12)\n name.place(x=200,y=385)\n password = StringVar()\n e = tkinter.Entry(login,font=('Times', 18,'bold'), width=12,textvariable=password, show='*')\n e.place(x=200,y=460)\n tkinter.Label(login, text='用户名:' ,font=('黑体', 17),bg='white',fg='olive').place(x=105, y=385)\n tkinter.Label(login, text='密码:' ,font=('黑体', 17),bg='white',fg='olive').place(x=128, y=460)\n\n def yes():\n if e.get()=='11111111'and name.get()=='caojiayang': \n global sign_up_count,w1,h1,background_image1\n sign_up_count = tkinter.Toplevel(top)\n sign_up_count.geometry('%dx%d+0+0' % (w1,h1))\n background_label = tkinter.Label(sign_up_count, image=background_image1)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n tkinter.Label(sign_up_count, text='收银记录:' ,font=('黑体', 18),bg='white').place(x=20, y=123)\n local_count()\n login = tkinter.Button(login, text='登陆',font=('楷体', 21,'bold'),bg='orange',fg='white', command=yes)\n login.place(x=225, y=530)\ndef take_out():\n global w6,h6,background_image6,sign_up_out\n sign_up_out= tkinter.Toplevel(top)\n sign_up_out.geometry('%dx%d+522+0' % (w6,h6))\n background_label = tkinter.Label(sign_up_out, image=background_image6)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n tkinter.Label(sign_up_out, text=('请出示外卖平台取货码') ,font=('隶书', 18),bg='lavenderblush').place(x=140, y=460)\n def bye_out():\n speaker.Speak('请出示取货码')\n Thread(target=bye_out).start()\n Thread(target=detect).start()\ntop = tkinter.Tk()\ntop.title('自助收银机')\nglobal ww,hh,background_imagee,w3,h3,background_image3,w1,h1,background_image1,w6,h6,background_image6\nimage6 =Image.open('logo6.gif')\nbackground_image6 = ImageTk.PhotoImage(image6)\nw6 = background_image6.width()\nh6 = background_image6.height()\nimage1 =Image.open('logo1.gif')\nbackground_image1 = ImageTk.PhotoImage(image1)\nw1 = background_image1.width()\nh1 = background_image1.height()\nimage3 =Image.open('logo3.gif')\nbackground_image3 = ImageTk.PhotoImage(image3)\nw3 = background_image3.width()\nh3 = background_image3.height()\nimagee =image3\nbackground_imagee = background_image3\nww = w3\nhh = h3\nimage =Image.open('logo5.gif')\nbackground_image = ImageTk.PhotoImage(image)\nw = background_image.width()\nh = background_image.height()\ntop.geometry('%dx%d+0+0' % (w,h))\nbackground_label = Label(top, image=background_image)\nbackground_label.place(x=0, y=0, relwidth=1, relheight=1)\ntkinter.Label(top, text='欢迎使用\\n多功能收银机' ,font=('隶书', 26),bg='whitesmoke',fg='darkgoldenrod').place(x=150, y=210)\nbtn_login = tkinter.Button(top, text='自助收银',font=('楷体', 23,'bold'),bg='lightslategray',fg='white',cursor='clock',command=feedback)\nbtn_login.place(x=180, y=340)\nbtn_login = tkinter.Button(top, text='我是骑手',font=('楷体', 23,'bold'),bg='tomato',fg='white',command=take_out)\nbtn_login.place(x=180, y=440)\nbtn_login = tkinter.Button(top, text='我是员工',font=('楷体', 23,'bold'),bg='darkorange',fg='white',command=admin)\nbtn_login.place(x=180, y=540)\ndef welcome():\n speaker.Speak('欢迎使用多功能收银机')\nThread(target=welcome).start()\ntop.mainloop()\n","sub_path":"team/team3/无人超市/多功能自助收银机/收银系统_终.py","file_name":"收银系统_终.py","file_ext":"py","file_size_in_byte":17083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"517627363","text":"\"\"\"Methods for generating ASR artifacts.\"\"\"\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nimport typing\nfrom pathlib import Path\n\nimport networkx as nx\nimport rhasspynlu\nfrom rhasspynlu.g2p import PronunciationsType\n\n_DIR = Path(__file__).parent\n_LOGGER = logging.getLogger(__name__)\n\n# -----------------------------------------------------------------------------\n\n\ndef get_kaldi_dir() -> Path:\n \"\"\"Get directory to Kaldi installation.\"\"\"\n # Check environment variable\n if \"KALDI_DIR\" in os.environ:\n return Path(os.environ[\"KALDI_DIR\"])\n\n return _DIR / \"kaldi\"\n\n\n# -----------------------------------------------------------------------------\n\n\ndef train(\n graph: nx.DiGraph,\n pronunciations: PronunciationsType,\n model_dir: typing.Union[str, Path],\n graph_dir: typing.Union[str, Path],\n dictionary: typing.Optional[typing.Union[str, Path]] = None,\n language_model: typing.Optional[typing.Union[str, Path]] = None,\n dictionary_word_transform: typing.Optional[typing.Callable[[str], str]] = None,\n g2p_model: typing.Optional[typing.Union[str, Path]] = None,\n g2p_word_transform: typing.Optional[typing.Callable[[str], str]] = None,\n missing_words_path: typing.Optional[Path] = None,\n vocab_path: typing.Optional[typing.Union[str, Path]] = None,\n language_model_fst: typing.Optional[typing.Union[str, Path]] = None,\n base_language_model_fst: typing.Optional[typing.Union[str, Path]] = None,\n base_language_model_weight: typing.Optional[float] = None,\n mixed_language_model_fst: typing.Optional[typing.Union[str, Path]] = None,\n balance_counts: bool = True,\n kaldi_dir: typing.Optional[Path] = None,\n):\n \"\"\"Re-generates HCLG.fst from intent graph\"\"\"\n g2p_word_transform = g2p_word_transform or (lambda s: s)\n\n # Determine directory with Kaldi binaries\n if kaldi_dir is None:\n kaldi_dir = get_kaldi_dir()\n\n assert kaldi_dir is not None\n _LOGGER.debug(\"Using kaldi at %s\", str(kaldi_dir))\n\n vocabulary: typing.Set[str] = set()\n if vocab_path:\n vocab_file = open(vocab_path, \"w+\")\n else:\n vocab_file = typing.cast(\n typing.TextIO, tempfile.NamedTemporaryFile(suffix=\".txt\", mode=\"w+\")\n )\n vocab_path = vocab_file.name\n\n # Language model mixing\n is_mixing = False\n base_fst_weight = None\n if (\n (base_language_model_fst is not None)\n and (base_language_model_weight is not None)\n and (base_language_model_weight > 0)\n ):\n is_mixing = True\n base_fst_weight = (base_language_model_fst, base_language_model_weight)\n\n # Begin training\n with tempfile.NamedTemporaryFile(mode=\"w+\") as lm_file:\n with vocab_file:\n # Create language model\n _LOGGER.debug(\"Converting to ARPA language model\")\n rhasspynlu.arpa_lm.graph_to_arpa(\n graph,\n lm_file.name,\n vocab_path=vocab_path,\n model_path=language_model_fst,\n base_fst_weight=base_fst_weight,\n merge_path=mixed_language_model_fst,\n )\n\n # Load vocabulary\n vocab_file.seek(0)\n vocabulary.update(line.strip() for line in vocab_file)\n\n if is_mixing:\n # Add all known words\n vocabulary.update(pronunciations.keys())\n\n assert vocabulary, \"No words in vocabulary\"\n\n # Write dictionary to temporary file\n with tempfile.NamedTemporaryFile(mode=\"w+\") as dictionary_file:\n _LOGGER.debug(\"Writing pronunciation dictionary\")\n rhasspynlu.g2p.write_pronunciations(\n vocabulary,\n pronunciations,\n dictionary_file.name,\n g2p_model=g2p_model,\n g2p_word_transform=g2p_word_transform,\n missing_words_path=missing_words_path,\n )\n\n # -----------------------------------------------------------------\n\n dictionary_file.seek(0)\n if dictionary:\n # Copy dictionary over real file\n shutil.copy(dictionary_file.name, dictionary)\n _LOGGER.debug(\"Wrote dictionary to %s\", str(dictionary))\n else:\n dictionary = Path(dictionary_file.name)\n dictionary_file.seek(0)\n\n lm_file.seek(0)\n if language_model:\n # Copy language model over real file\n shutil.copy(lm_file.name, language_model)\n _LOGGER.debug(\"Wrote language model to %s\", str(language_model))\n else:\n language_model = Path(lm_file.name)\n lm_file.seek(0)\n\n # Generate HCLG.fst\n train_kaldi(\n model_dir, graph_dir, dictionary, language_model, kaldi_dir=kaldi_dir\n )\n\n\n# -----------------------------------------------------------------------------\n\n\ndef train_kaldi(\n model_dir: typing.Union[str, Path],\n graph_dir: typing.Union[str, Path],\n dictionary: typing.Union[str, Path],\n language_model: typing.Union[str, Path],\n kaldi_dir: typing.Union[str, Path],\n):\n \"\"\"Generates HCLG.fst from dictionary and language model.\"\"\"\n\n # Convert to paths\n model_dir = Path(model_dir)\n graph_dir = Path(graph_dir)\n kaldi_dir = Path(kaldi_dir)\n\n # -------------------------------------------------------------------------\n # Kaldi Training\n # ---------------------------------------------------------\n # 1. prepare_lang.sh\n # 2. format_lm.sh\n # 3. mkgraph.sh\n # 4. prepare_online_decoding.sh\n # ---------------------------------------------------------\n\n # Extend PATH\n egs_utils_dir = kaldi_dir / \"egs\" / \"wsj\" / \"s5\" / \"utils\"\n extended_env = os.environ.copy()\n extended_env[\"PATH\"] = (\n str(kaldi_dir) + \":\" + str(egs_utils_dir) + \":\" + extended_env[\"PATH\"]\n )\n\n # Create empty path.sh\n path_sh = model_dir / \"path.sh\"\n if not path_sh.is_file():\n path_sh.write_text(\"\")\n\n # Delete existing data/graph\n data_dir = model_dir / \"data\"\n if data_dir.exists():\n shutil.rmtree(data_dir)\n\n if graph_dir.exists():\n shutil.rmtree(graph_dir)\n\n data_local_dir = model_dir / \"data\" / \"local\"\n\n _LOGGER.debug(\"Generating lexicon\")\n dict_local_dir = data_local_dir / \"dict\"\n dict_local_dir.mkdir(parents=True, exist_ok=True)\n\n # Copy phones\n phones_dir = model_dir / \"phones\"\n for phone_file in phones_dir.glob(\"*.txt\"):\n shutil.copy(phone_file, dict_local_dir / phone_file.name)\n\n # Copy dictionary\n shutil.copy(dictionary, dict_local_dir / \"lexicon.txt\")\n\n # Create utils link\n model_utils_link = model_dir / \"utils\"\n\n try:\n # Can't use missing_ok in 3.6\n model_utils_link.unlink()\n except Exception:\n pass\n\n model_utils_link.symlink_to(egs_utils_dir, target_is_directory=True)\n\n # 1. prepare_lang.sh\n lang_dir = data_dir / \"lang\"\n lang_local_dir = data_local_dir / \"lang\"\n prepare_lang = [\n \"bash\",\n str(egs_utils_dir / \"prepare_lang.sh\"),\n str(dict_local_dir),\n \"\",\n str(lang_local_dir),\n str(lang_dir),\n ]\n\n _LOGGER.debug(prepare_lang)\n subprocess.check_call(prepare_lang, cwd=model_dir, env=extended_env)\n\n # 2. format_lm.sh\n lm_arpa = lang_local_dir / \"lm.arpa\"\n lm_arpa.parent.mkdir(parents=True, exist_ok=True)\n shutil.copy(language_model, lm_arpa)\n\n gzip_lm = [\"gzip\", str(lm_arpa)]\n _LOGGER.debug(gzip_lm)\n subprocess.check_call(gzip_lm, cwd=lm_arpa.parent, env=extended_env)\n\n format_lm = [\n \"bash\",\n str(egs_utils_dir / \"format_lm.sh\"),\n str(lang_dir),\n str(lm_arpa.with_suffix(\".arpa.gz\")),\n str(dict_local_dir / \"lexicon.txt\"),\n str(lang_dir),\n ]\n\n _LOGGER.debug(format_lm)\n subprocess.check_call(format_lm, cwd=model_dir, env=extended_env)\n\n # 3. mkgraph.sh\n mkgraph = [\n \"bash\",\n str(egs_utils_dir / \"mkgraph.sh\"),\n str(lang_dir),\n str(model_dir / \"model\"),\n str(graph_dir),\n ]\n _LOGGER.debug(mkgraph)\n subprocess.check_call(mkgraph, cwd=model_dir, env=extended_env)\n\n # 4. prepare_online_decoding.sh\n train_prepare_online_decoding(model_dir, lang_dir, kaldi_dir)\n\n\ndef train_prepare_online_decoding(\n model_dir: typing.Union[str, Path],\n lang_dir: typing.Union[str, Path],\n kaldi_dir: typing.Union[str, Path],\n):\n \"\"\"Prepare model for online decoding.\"\"\"\n model_dir = Path(model_dir)\n kaldi_dir = Path(kaldi_dir)\n\n # prepare_online_decoding.sh (nnet3 only)\n extractor_dir = model_dir / \"extractor\"\n if extractor_dir.is_dir():\n # Extend PATH\n egs_utils_dir = kaldi_dir / \"egs\" / \"wsj\" / \"s5\" / \"utils\"\n extended_env = os.environ.copy()\n extended_env[\"PATH\"] = (\n str(kaldi_dir) + \":\" + str(egs_utils_dir) + \":\" + extended_env[\"PATH\"]\n )\n\n # Create empty path.sh\n path_sh = model_dir / \"path.sh\"\n if not path_sh.is_file():\n path_sh.write_text(\"\")\n\n # Create utils link\n model_utils_link = model_dir / \"utils\"\n\n try:\n # Can't use missing_ok in 3.6\n model_utils_link.unlink()\n except Exception:\n pass\n\n model_utils_link.symlink_to(egs_utils_dir, target_is_directory=True)\n\n # Generate online.conf\n mfcc_conf = model_dir / \"conf\" / \"mfcc_hires.conf\"\n egs_steps_dir = kaldi_dir / \"egs\" / \"wsj\" / \"s5\" / \"steps\"\n prepare_online_decoding = [\n \"bash\",\n str(egs_steps_dir / \"online\" / \"nnet3\" / \"prepare_online_decoding.sh\"),\n \"--mfcc-config\",\n str(mfcc_conf),\n str(lang_dir),\n str(extractor_dir),\n str(model_dir / \"model\"),\n str(model_dir / \"online\"),\n ]\n\n _LOGGER.debug(prepare_online_decoding)\n subprocess.run(\n prepare_online_decoding,\n cwd=model_dir,\n env=extended_env,\n stderr=subprocess.STDOUT,\n check=True,\n )\n\n\n# -----------------------------------------------------------------------------\n","sub_path":"rhasspyasr_kaldi/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"528359843","text":"#!/App/tools/anaconda3/bin/python\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport datetime\nimport pandas as pd\nfrom pandas import DataFrame\n# user define package import\n# user define package import\nimport sys\nsys.path.append('./')\nfrom msgbot.favisbot import favisbot\nimport util.favis_util as fu\nimport pymysql\n# set config\n###################################################################################\ntry:\n conn = fu.get_favis_mysql_connection()\nexcept pymysql.Error as e:\n print (\"error %s\" % e.args[0])\n\n\ncur = conn.cursor()\n\n\nday = (datetime.datetime.today() - datetime.timedelta(1)).strftime('%Y%m%d')\n#day = '20160801'\n\nquery = \"select (@order:=@order+1) as s_order, t.* \\\n\t\t\tfrom( \\\n\t\t\tselect si.name, si.market, si.sector, (a.roa_num + b.per_num) as sum, a.code, a.roa_num, b.per_num, a.roa, b.per \\\n\t\t\tfrom \\\n\t\t\t(select (@roa_order:=@roa_order+1) as roa_num, code, roe, roa, per, pbr from financial_info \\\n\t\t\twhere (@roa_order :=0) = 0 and date = '201603' and roa != 0 order by roa desc) a, \\\n\t\t\t(select (@per_order:=@per_order+1) as per_num, code, per, eps, bps, pbr, dividend_rate from daily_stock_index \\\n\t\t\twhere (@per_order :=0) = 0 and date = '\" + day + \"' and per != 0 order by per asc) b, \\\n\t\t\t(select * from stock_info) si \\\n\t\t\twhere a.code = b.code and a.code = si.code \\\n\t\t\torder by (a.roa_num + b.per_num) asc \\\n\t\t\tlimit 10) t \\\n\t\t\twhere (@order :=0) = 0\"\ncur.execute(query)\n\ndf = pd.read_sql(query, conn)\nprint(df)\nif conn:\n conn.close()\n\nret = \"\"\nfor d in df.iterrows():\n\tret = ret + str(d[1]['s_order'])+\"|\"+ str(d[1]['code'])+\"|\"+ str(d[1]['name'])+\"|\"+ str(d[1]['sector'])+\"|\"+ str(d[1]['per'])+\"|\"+ str(d[1]['roa']) + \"\\n\"\n#\tprint(\"%2d|%s|%s|%s|%f|%f\" % (d[1]['s_order'], str(d[1]['code']), str(d[1]['name']), str(d[1]['sector']), d[1]['per'], d[1]['roa']))\n\n\nprint(ret)\nbot = favisbot()\nbot.whisper('plain',\"day_top10(%s) \\n %s\" % (day, ret))\n\n","sub_path":"analytics/send_top10.py","file_name":"send_top10.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"377575337","text":"# -*- coding:utf-8 -*-\nimport smtplib, os,datetime,random\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.application import MIMEApplication\nfrom base.base_log import BaseLogger\nfrom config import settings\n\nlogger = BaseLogger(__name__).get_logger()\n\n\nclass BaseMail(object):\n\n def __init__(self):\n self.report_dir_path = settings.REPORT_DIR_PATH\n self.image_dir_path = './image/'\n self.report_file = self._get_new_report()\n\n def _get_new_report(self):\n \"\"\"\n 获取最新测试报告\n :return:\n \"\"\"\n lists = os.listdir(self.report_dir_path)\n lists.sort(key=lambda fn: os.path.getmtime(self.report_dir_path + '/' + fn))\n file_new = os.path.join(self.report_dir_path, lists[-1])\n logger.info('The latest test report is a success.')\n logger.info('Report path:{0}'.format(os.path.abspath(file_new)))\n return file_new\n\n def send_mail(self):\n \"\"\"\n 发送测试报告附件邮件\n :return:\n \"\"\"\n msg = MIMEMultipart()\n msg['Subject'] = settings.MAIL_HEADER\n msg['From'] = settings.MAIL_FROM\n msg['To'] = settings.MAIL_TO\n msg['Accept-Language'] = 'zh-CN'\n msg[\"Accept-Charset\"] = \"ISO-8859-1,utf-8\"\n\n # 测试报告H5源码为邮件主体\n html_msg = open(self.report_file,'r',encoding=\"utf-8\").read()\n msg.attach(MIMEText(html_msg, 'html', 'utf-8'))\n\n # 邮件主体与附件之间通过一张随机图片隔开\n image_dir_list = os.listdir(self.image_dir_path)\n num = random.randint(0,len(image_dir_list) - 1)\n image = os.path.join(self.image_dir_path,image_dir_list[num])\n image_file = open(image,'rb')\n msg_image = MIMEImage(image_file.read())\n image_file.close()\n msg_image.add_header('Content-ID', '')\n msg.attach(msg_image)\n\n # 测试报告附件的描述\n pure_text = MIMEText('详细测试报告请见附件!',_charset='utf-8')\n pure_text['Accept-Language'] = 'zh-CN'\n pure_text[\"Accept-Charset\"] = \"ISO-8859-1,utf-8\"\n msg.attach(pure_text)\n\n # HTML格式的附件\n html_application = MIMEApplication(open(self.report_file, 'rb').read())\n file_name = '自动化测试报告详细版-{0}.html'.format((datetime.datetime.now()).strftime(\"%Y%m%d\"))\n html_application.add_header('Content-Disposition', 'attachment', filename=file_name)\n msg.attach(html_application)\n\n try:\n # 链接163邮箱服务器\n client = smtplib.SMTP()\n client.connect(settings.MAIL_SERVER)\n logger.info('SMTP Server connection succeeded.')\n # 登录163邮箱\n client.login(settings.MAIL_FROM, settings.MAIL_FROM_PASSWORD)\n logger.info('SMTP Server login succeeded.')\n # 发送邮件\n client.sendmail(settings.MAIL_FROM, settings.MAIL_TO, msg.as_string())\n logger.info('Email sent to {0} successfully!'.format(settings.MAIL_TO))\n # 关闭链接\n client.quit()\n except Exception:\n logger.error('Email sent failed!')\n pass","sub_path":"base/base_email.py","file_name":"base_email.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483371948","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 25 21:02:18 2019\r\n\r\n@author: jankos\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pdb\r\n\r\n\r\ndef str2num(series):\r\n \"\"\"Replace string categorical variables with numerical \"\"\"\r\n dictionary = dict(zip(series.unique(), range(len(series))))\r\n series2 = series.replace(dictionary)\r\n return series2\r\n\r\ndef split_hands(data):\r\n \"\"\"Take df with data for both hands and return two DFs with hands separated \"\"\"\r\n LH = data[data['hand'] == 'LH']\r\n RH = data[data['hand'] == 'RH']\r\n LH = LH.reset_index(drop=True)\r\n RH = RH.reset_index(drop=True)\r\n\r\n return LH,RH\r\n\r\n\r\ndef event_to_numlist(dfcol, taskdict):\r\n #taskdict = {'grab': 0, 'move':1, 'hold still':2, 'transport':3, 'NV':4}\r\n num = dfcol.apply(lambda x: taskdict[x])\r\n numlist = np.int32(np.array(list(num.values)))\r\n\r\n return numlist\r\n\r\n\r\ndef map_segments(frames, segment_borders, segment_names):\r\n \"\"\"digitize frame ranges with segment borders, rename with segment names \"\"\"\r\n segment_borders[0] = frames.min()\r\n segment_borders[-1] = frames.max() #just in case annotations for last and first frame didn't match exactly\r\n bins = np.digitize(frames, segment_borders)\r\n num_segments = np.unique(bins)\r\n if len(num_segments) > len(segment_names):\r\n segment_names = segment_names + [segment_names[-1]]*(len(num_segments)-len(segment_names))\r\n mapping = dict(zip(np.unique(bins), segment_names))\r\n named_values = [mapping[value] for value in bins]\r\n\r\n return named_values\r\n\r\n\r\n\r\ndef create_value_count_df(values):\r\n value_counts = values.value_counts()\r\n value_counts = value_counts.to_frame()\r\n value_counts = value_counts.reset_index()\r\n value_counts = value_counts.T\r\n value_counts.columns = value_counts.iloc[0]\r\n value_counts = value_counts.reset_index(drop=True)\r\n value_counts = value_counts.drop(index=0)\r\n value_counts = value_counts.astype(float)\r\n\r\n return value_counts\r\n\r\ndef switch_cols(suture_cols, switch_dict):\r\n cols = suture_cols\r\n for key, value in switch_dict.items():\r\n cols[suture_cols.index(key)], cols[value] = suture_cols[value], suture_cols[suture_cols.index(key)]\r\n\r\n return cols\r\n\r\ndef classification_type(true_col='true_skill', neg_col='novice', pos_col='expert', data=None):\r\n if data is None:\r\n print(\"Data required\")\r\n return None\r\n positives = data[data[true_col] == pos_col]\r\n negatives = data[data[true_col] == neg_col]\r\n\r\n TN = negatives[neg_col].sum()\r\n TE = positives[pos_col].sum()\r\n FN = positives[neg_col].sum()\r\n FE = negatives[pos_col].sum()\r\n\r\n return np.array([[TN, FN],[FE, TE]])\r\n\r\ndef calc_accuracy(cm):\r\n accuracy = (cm[0][0] + cm[1][1])/cm.sum()\r\n return accuracy\r\n\r\ndef drop_duplicate_comparisons(df):\r\n df['set'] = df.apply(lambda x: {x['p_compared'],\r\n x['p_compared_to'],\r\n x['suture'],\r\n x['segment'],\r\n x['hand']}, axis=1)\r\n df2=df[~df['set'].astype(str).duplicated(keep='first')]\r\n return df2.reset_index(drop=True)\r\n\r\n","sub_path":"helpers/biman_helpers.py","file_name":"biman_helpers.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"183114496","text":"import asyncio\n\nfrom src import mc_mivs\n\n\nasync def main():\n product = ['10716', '10729']\n drug_qnty_req = [10, 15]\n input_capital = 100000000\n cash = 0\n perech = 100000000\n supplier = ['10']\n cash_cost = [[100000000], [100000000]]\n pred_100 = [[19980], [19586]]\n pred_50 = [[100000000], [100000000]]\n pred_25 = [[100000000], [100000000]]\n prices_title = [\"cash_cost\", [\"pred_100\", \"pred_50\", \"pred_25\"]]\n\n result = await mc_mivs.main(product,\n drug_qnty_req,\n input_capital,\n cash,\n perech,\n supplier,\n cash_cost,\n pred_100,\n pred_50,\n pred_25,\n prices_title)\n # print(\"result: \\n>>>\", result)\n # print(\"_Execution Time: \", time() - start, ' (secs)')\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"src/tests/mumtoz_main.py","file_name":"mumtoz_main.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"47677388","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"EDMtoMEConvert\")\nprocess.load(\"DQMServices.Core.DQM_cfg\")\n\nprocess.load(\"CondCore.DBCommon.CondDBSetup_cfi\")\n\nprocess.load(\"DQMServices.Components.DQMEnvironment_cfi\")\nprocess.load(\"DQMServices.Components.EDMtoMEConverter_cff\")\n\nprocess.load(\"DQMOffline.Trigger.EgHLTOfflineClient_cfi\")\nprocess.load(\"DQMOffline.Trigger.EgHLTOfflineSummaryClient_cfi\")\n#process.load(\"Configuration.StandardSequences.Geometry_cff\")\n#process.load(\"Geometry.CaloEventSetup.CaloGeometry_cfi\")\n#process.load(\"Geometry.CaloEventSetup.CaloTopology_cfi\")\n#process.load(\"Geometry.CMSCommonData.cmsIdealGeometryXML_cfi\")\n\n#process.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(1)\n)\n\n# initialize MessageLogger and output report\nprocess.load(\"FWCore.MessageLogger.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkSummary = cms.untracked.PSet(\n reportEvery = cms.untracked.int32(1),\n limit = cms.untracked.int32(10000000)\n)\nprocess.MessageLogger.cerr.FwkReport = cms.untracked.PSet(\n reportEvery = cms.untracked.int32(1),\n limit = cms.untracked.int32(10000000)\n)\n\n \n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(),\n processingMode = cms.untracked.string(\"RunsLumisAndEvents\"),\n)\nprocess.source.fileNames=cms.untracked.vstring('file:test/relVal_350pre2Test.root')\n#process.source.processingMode = cms.untracked.string(\"RunsLumisAndEvents\"),\n\n#process.source.processingMode = cms.untracked.string(\"RunsAndLumis\")\nprocess.source.processingMode = cms.untracked.string(\"Runs\")\n\n\nprocess.qTester = cms.EDFilter(\"QualityTester\",\n qtList = cms.untracked.FileInPath('DQMOffline/Trigger/data/EgHLTOffQualityTests.xml'),\n verboseQT = cms.untracked.bool(True),\n qtestOnEndJob =cms.untracked.bool(False),\n qtestOnEndRun =cms.untracked.bool(True), \n \n )\n\n\nprocess.DQMStore.collateHistograms = True\nprocess.EDMtoMEConverter.convertOnEndLumi = False\nprocess.EDMtoMEConverter.convertOnEndRun = True\n\nprocess.p1 = cms.Path(process.EDMtoMEConverter*process.egHLTOffDQMClient*process.qTester*process.egHLTOffDQMSummaryClient*process.dqmSaver)\n\n\nprocess.DQMStore.verbose = 1\nprocess.DQM.collectorHost = ''\nprocess.dqmSaver.convention = cms.untracked.string('Offline')\nprocess.dqmSaver.saveByRun = cms.untracked.int32(1)\nprocess.dqmSaver.saveAtJobEnd = cms.untracked.bool(False)\nprocess.dqmSaver.workflow = cms.untracked.string('/BeamData09/MinBias/RECO')\nprocess.dqmSaver.forceRunNumber = cms.untracked.int32(1)\n\n","sub_path":"DQMOffline/Trigger/test/egHLTOffDQMClientTest_cfg.py","file_name":"egHLTOffDQMClientTest_cfg.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"238936562","text":"import pywifi\nfrom pywifi import const # 引用一些定义\nimport time\n\n\ndef getwifi():\n wifi = pywifi.PyWiFi() # 抓取网卡接口\n ifaces = wifi.interfaces()[0] # 获取网卡\n ifaces.scan()\n bessis = ifaces.scan_results()\n list = []\n for data in bessis:\n list.append((data.ssid, data.signal))\n return len(list), sorted(list, key=lambda st: st[1], reverse=True)\n\n\ndef getsignal():\n while True:\n n, data = getwifi()\n time.sleep(1)\n if n is not 0:\n return data[0:10]\n\n\ndef ssidnamelist():\n ssidlist = getsignal()\n namelist = []\n for item in ssidlist:\n namelist.append(item[0])\n return namelist\n\n\ndef testwifi(ssidname, password):\n wifi = pywifi.PyWiFi() # 抓取网卡接口\n ifaces = wifi.interfaces()[0] # 获取网卡\n ifaces.disconnect() # 断开无限网卡连接\n\n profile = pywifi.Profile() # 创建wifi连接文件\n profile.ssid = ssidname # 定义wifissid\n profile.auth = const.AUTH_ALG_OPEN # 网卡的开放\n profile.akm.append(const.AKM_TYPE_WPA2PSK) # wifi加密算法\n profile.cipher = const.CIPHER_TYPE_CCMP ##加密单元\n profile.key = password # wifi密码\n\n ifaces.remove_all_network_profiles() # 删除其他所有配置文件\n tmp_profile = ifaces.add_network_profile(profile) # 加载配置文件\n\n ifaces.connect(tmp_profile) # 连接wifi\n time.sleep(5) # 5秒内能否连接上\n if ifaces.status() == const.IFACE_CONNECTED:\n print(\"[-]WiFi connection success!\")\n else:\n print(\"[-]WiFi connection failure!\")\n\n ifaces.disconnect() # 断开连接\n time.sleep(1)\n\n return True\n\n\ndef main():\n print(\" ____ _ __ _____ _____ ___ \")\n print(\" / ___|_ __ __ _ ___| | _\\ \\ / /_ _| ___|_ _|\")\n print(\"| | | '__/ _` |/ __| |/ /\\ \\ /\\ / / | || |_ | | \")\n print(\"| |___| | | (_| | (__| < \\ V V / | || _| | | \")\n print(\" \\____|_| \\__,_|\\___|_|\\_\\ \\_/\\_/ |___|_| |___|\")\n path = r\"F:\\文档\\项目比赛\\WIFI\\wpa2pjzd_115964\\破解字典\\wordlist\\wordlist.txt\"\n files = open(path, 'r')\n while True:\n f = files.readline()\n for ssidname in ssidnamelist():\n ret = testwifi(ssidname, f)\n print('Current WIFIname:', ssidname)\n print('Current password:', f)\n files.close()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycode/ten objective.py","file_name":"ten objective.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"93610","text":"# %%\nimport time\nwith open(\"/mnt/c/Users/Ryan/Documents/aoc2020/day9/input.txt\") as f:\n lines = f.read().split(\"\\n\")\n\n\ndef loopThrough(new_list, val):\n for ipos, i in enumerate(new_list):\n i = int(i)\n for j in new_list[ipos+1:]:\n j = int(j)\n if i + j == val:\n print(f\"Sum found: {i} + {j} = {i + j} ({val})\")\n return True\n return False\n\n\ndef findSet(new_list, err_num):\n err_list = []\n for number in new_list:\n err_list.append(number)\n\n while sum(err_list) > err_num:\n err_list.pop(0)\n if sum(err_list) == err_num:\n print(f\"sum({err_list}) = {err_num}\")\n return min(err_list) + max(err_list)\n\n\n# %%\nlines = [int(i) for i in lines]\nstart = time.time()\npreamble = 25\nnew_list = lines[:preamble]\nfor val in lines[preamble:]:\n val = int(val)\n sum_found = loopThrough(new_list, val)\n new_list.pop(0)\n new_list.append(val)\n if not sum_found:\n print(f\"No sum found for {val}. Calculating Weakness\")\n weakness = findSet(lines, val)\n break\n\nprint(f\"Weakness of {weakness} found\")\nprint(f\"Code executed in {time.time() - start} seconds\")\n# %%\n","sub_path":"day9/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"31330536","text":"from pandas import read_csv\nfrom flask import Flask, request\nfrom flask_restful import Resource,Api\n\napp = Flask (__name__)\napi = Api(app)\n\nclass HelloWorld (Resource):\n def get(self):\n data = read_csv('preprocessedDataset.csv')\n data = data.to_dict()\n return {'data':data},200\n\n def post(self):\n some_json = request.get_json()\n return {'you sent': some_json }, 201\n\napi.add_resource(HelloWorld, '/')\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"data/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"440809328","text":"import gym\nimport numpy as np\nimport torch\nimport ptan\nfrom tensorboardX import SummaryWriter\nimport shutil\nfrom torch import optim\nfrom torch import tensor\nfrom torch import nn\nimport collections\n\n\nGAMMA = 0.99\nLEARNING_RATE = 0.01\nEPISODES_TO_TRAIN = 4\n\nclass PGN(nn.Module): # Policy network\n def __init__(self, input_size, nb_actions):\n super(PGN, self).__init__()\n self.net = nn.Sequential(\n nn.Linear(input_size, 128),\n nn.ReLU(),\n nn.Linear(128, nb_actions)\n )\n\n def forward(self, x):\n return self.net(x)\n\ndef calc_qvals(rewards):\n res = []\n sum_r = 0.0\n for r in rewards:\n sum_r *= GAMMA\n sum_r += r\n res.append(sum_r)\n return list(reversed(res))\n\n\nExperience = collections.namedtuple('Experience', field_names=['state', 'action', 'reward', 'next_state', 'done'])\n\n\ndef iterate_experience(net, env):\n state = env.reset()\n while True:\n proba_action = nn.functional.softmax(net(torch.FloatTensor([state])), dim=1)\n action = np.random.choice(env.action_space.n, p=proba_action.data.numpy()[0])\n next_state, reward, done, _ = env.step(action)\n if done:\n next_state = env.reset()\n yield Experience(state=state, action=action, reward=reward, next_state=next_state, done=done)\n state = next_state\n\n\nif __name__==\"__main__\":\n env = gym.make('CartPole-v0')\n tx_folder_name = 'runs_cartpole_policy_gradient'\n\n try:\n shutil.rmtree(tx_folder_name)\n writer = SummaryWriter(tx_folder_name)\n except:\n writer = SummaryWriter(tx_folder_name)\n\n net = PGN(env.observation_space.shape[0], env.action_space.n)\n\n # agent = ptan.agent.PolicyAgent(net, preprocessor=ptan.agent.float32_preprocessor, apply_softmax=True)\n #\n # exp_source = ptan.experience.ExperienceSourceFirstLast(env, agent, gamma=GAMMA)\n\n optimizer = optim.Adam(params=net.parameters(), lr=LEARNING_RATE)\n\n total_rewards = []\n done_episodes = 0\n\n batch_episodes = 0\n cur_rewards = []\n batch_states, batch_actions, batch_qvals = [], [], []\n\n for i, exp in enumerate(iterate_experience(net, env)):\n batch_states.append(exp.state)\n batch_actions.append(int(exp.action))\n cur_rewards.append(exp.reward)\n\n if exp.done:\n new_qvals = calc_qvals(cur_rewards)\n batch_qvals.extend(new_qvals)\n reward = np.sum(cur_rewards)\n cur_rewards.clear()\n batch_episodes += 1\n done_episodes += 1\n total_rewards.append(reward)\n mean_rewards = float(np.mean(total_rewards[-100:]))\n print(\"%d: reward: %6.2f, mean_100: %6.2f, episodes: %d\" % (i, reward, mean_rewards, done_episodes))\n writer.add_scalar(\"reward\", reward, i)\n writer.add_scalar(\"reward_100\", mean_rewards, i)\n writer.add_scalar(\"episodes\", done_episodes, i)\n if mean_rewards>195:\n print(\"Solved in %d steps and %d episodes!!!\" % (i, done_episodes))\n break\n\n if batch_episodes < EPISODES_TO_TRAIN:\n continue\n\n optimizer.zero_grad()\n states_v = torch.FloatTensor(batch_states)\n batch_actions_t = torch.LongTensor(batch_actions)\n batch_qvals_v = torch.FloatTensor(batch_qvals)\n\n logits_v = net(states_v)\n log_prob_v = nn.functional.log_softmax(logits_v, dim=1)\n log_prob_actions_v = batch_qvals_v * log_prob_v[range(len(batch_states)), batch_actions_t]\n loss_v = -log_prob_actions_v.mean()\n\n loss_v.backward()\n optimizer.step()\n\n batch_episodes = 0\n batch_states.clear()\n batch_actions.clear()\n batch_qvals.clear()\n\n writer.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"policy gradient/reinforce_cartpole_perso.py","file_name":"reinforce_cartpole_perso.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"502180876","text":"#!/usr/bin/env python\n\nimport credstash\nimport json\nimport sys\nimport yaml\n\nwith open('/etc/ansible/credstash.yml', 'r') as f:\n config = yaml.load(f)\n\ntable = config.get('table')\nregion = config.get('region')\n\ninventory = dict()\n\nif len(sys.argv) > 1 and sys.argv[1] == '--list':\n table_contents = credstash.getAllSecrets(region=region, table=table)\n for key, value in table_contents.items():\n group_name = key\n group_vars = yaml.load(value)\n inventory[group_name] = dict(hosts=[], vars=group_vars)\n\nprint(json.dumps(inventory))\n","sub_path":"ansible/inventory/credstash_group_vars.py","file_name":"credstash_group_vars.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"194806757","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom bs4 import BeautifulSoup\nimport requests,time,string\nbaseurl = \"http://loksabhaph.nic.in/Members/lokprev.aspx\"\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\nchrome_options.add_argument('--no-sandbox')\nchrome_options.add_argument('--disable-dev-shm-usage')\nout = open(\"lok_sabha_member_profile.tsv\",\"w+\")\n\ndriver = webdriver.Chrome(chrome_options=chrome_options)\ndriver.implicitly_wait(3)\ndriver.get(baseurl)\nfor i in string.ascii_uppercase:\n st = \"ContentPlaceHolder1_\" + i\n driver.find_element_by_id(st).click()\n wait = WebDriverWait(driver, 90)\n select = Select(driver.find_element_by_id(\"ContentPlaceHolder1_drdpages\"))\n select.select_by_value('5000')\n try:\n wait.until(EC.presence_of_element_located((By.CLASS_NAME,'sl_no')))\n names = driver.find_elements_by_xpath('//*[@id=\"ContentPlaceHolder1_tblMember\"]/tbody/tr/td/table/tbody/*/td[2]/a')\n exper = driver.find_elements_by_xpath('//*[@id=\"ContentPlaceHolder1_tblMember\"]/tbody/tr/td/table/tbody/*/td[5]')\n party = driver.find_elements_by_xpath('//*[@id=\"ContentPlaceHolder1_tblMember\"]/tbody/tr/td/table/tbody/*/td[3]')\n for j in range(len(exper)):\n sp = exper[j].text.strip().split(\",\")\n if \"16\" in sp:\n c = 0\n page = requests.get(names[j].get_attribute(\"href\"))\n soup = BeautifulSoup(page.content, 'lxml')\n key = soup.find_all(class_=\"darkerb\")\n value = soup.find_all(class_=\"griditem2\")\n for k in key:\n if k.contents[0].strip() == \"Date of Birth\":\n out.write(names[j].text.replace(\" ,\",\",\") + \n \"\\t\" + k.contents[0].strip() +\n \"\\t\" + value[c].contents[0].strip() + \n \"\\t\" + exper[j].text + \"\\t\" + party[j].text + \"\\n\")\n c += 1\n except Exception as e:\n print(\"RETRYING INITIALIZATION OF WEBDRIVER! Error\")\n time.sleep(10)\ndriver.quit()\nout.close()\n","sub_path":"lok_sabha_member_profile.py","file_name":"lok_sabha_member_profile.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"565630772","text":"import pandas as pd\nimport json\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport re\nimport business_dataframe\nimport retrieve_list\n\ndef construct_keywords(name):\n '''\n Input:\n name: a string\n Output:\n namelist: a list of possible formats of name. namelist should have length 4.\n '''\n \n nameset = set()\n # itself, no space, hashtags, lowercase\n nameset.add(name)\n # remove possible whitespace\n name_nospace = name.replace(\" \", \"\")\n nameset.add(name_nospace)\n nameset.add('@'+name_nospace)\n # hashtage + capital initials\n nameset.add('#'+name_nospace)\n # hashtage + lowercase\n nameset.add('#'+name_nospace.lower())\n \n return list(nameset)\n\n\ndef word_in_text(wordlist, text):\n for word in wordlist:\n match = re.search(word, text)\n if match:\n return True\n \n return False\n\ndef dict_converter(lst):\n rv = {}\n for i in lst:\n ilst = construct_keywords(i)\n rv[i] = ilst\n\n return rv\n\n\ndef read_data(path, namedict):\n '''\n issue here is to find full_text because text can be truncated\n '''\n \n colnames = (\"rname\", \"text\",\"retweet_count\",\"favorite_count\", \"followers\", \"sentiment\", \"score\")\n df = pd.DataFrame(columns=colnames)\n \n tweets_file = open(path, \"r\")\n \n l = 0 # restaurants matched\n for line in tweets_file:\n \n try:\n tweet = json.loads(line)\n \n # whether a tweet is a retweet\n is_retweet = re.search(\"^RT\",tweet['text'])\n \n for i in namedict:\n possible_names = namedict[i]\n \n if is_retweet:\n # whether is a extended text\n if 'extended_tweet' in tweet['retweeted_status']:\n match = re.search(r\"(?=(\"+'|'.join(possible_names)+r\"))\",\\\n tweet['retweeted_status']['extended_tweet']['full_text'])\n else:\n match = re.search(r\"(?=(\"+'|'.join(possible_names)+r\"))\",tweet['text'])\n else:\n # whether is a extended text\n if 'extended_tweet' in tweet:\n match = re.search(r\"(?=(\"+'|'.join(possible_names)+r\"))\",\\\n tweet['extended_tweet']['full_text'])\n else:\n match = re.search(r\"(?=(\"+'|'.join(possible_names)+r\"))\",tweet['text'])\n \n \n if match:\n l += 1\n \n if is_retweet:\n twinfo = calculate_score(i, tweet, True)\n else:\n twinfo = calculate_score(i, tweet)\n \n #print('\\n',twinfo)\n df_temp = pd.DataFrame(twinfo, columns=colnames)\n #print(df_temp)\n df = df.append(df_temp, ignore_index=True)\n \n \n break\n \n except:\n #print('Failed: ', str(e))\n continue\n \n print('twitter scanning finished')\n print('# matches:', l)\n return df\n \n\n \ndef calculate_score(i, tweet, is_retweet=False):\n analyzer = SentimentIntensityAnalyzer()\n \n retweet = tweet['retweet_count']\n likes = tweet['favorite_count']\n followers = tweet['user']['followers_count']\n \n if is_retweet:\n if 'extended_tweet' in tweet['retweeted_status']:\n senti_score = float(analyzer.polarity_scores(tweet['retweeted_status']['extended_tweet']['full_text'])['compound'])\n text = tweet['retweeted_status']['extended_tweet']['full_text']\n else:\n senti_score = float(analyzer.polarity_scores(tweet['text'])['compound'])\n text = tweet['text']\n else:\n if 'extended_tweet' in tweet:\n senti_score = float(analyzer.polarity_scores(tweet['extended_tweet']['full_text'])['compound'])\n text = tweet['extended_tweet']['full_text']\n else:\n senti_score = float(analyzer.polarity_scores(tweet['text'])['compound'])\n text = tweet['text']\n \n tot_score = (retweet + likes+ followers)*senti_score\n twinfo = [(i, text, retweet, likes, followers, senti_score, tot_score)]\n \n return twinfo\n\ndef merge_sort(alist):\n '''\n sort in decreasing order\n '''\n if len(alist) > 1:\n mid = len(alist)//2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n\n merge_sort(lefthalf)\n merge_sort(righthalf)\n\n i=0\n j=0\n k=0\n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i][1] > righthalf[j][1]:\n alist[k]=lefthalf[i]\n i=i+1\n else:\n alist[k]=righthalf[j]\n j=j+1\n k=k+1\n\n while i < len(lefthalf):\n alist[k]=lefthalf[i]\n i=i+1\n k=k+1\n\n while j < len(righthalf):\n alist[k]=righthalf[j]\n j=j+1\n k=k+1\n else:\n return\n\ndef analyze_df(obj_df):\n '''\n analyze the pandas dataframe that contains information for all searched objects\n '''\n # construct a list of tuples\n ranking = []\n for i, i_df in obj_df.groupby('rname'):\n i_mean = i_df.score.mean()\n i_mean = round(i_mean, 4)\n ranking.append((i, i_mean))\n\n # sort the ranking in decreasing order\n merge_sort(ranking)\n \n return ranking\n \n\n\n\nif __name__ == '__main__':\n category_list = 'pizza'\n business_dataframe.dict_assemble(\"pickle\")\n \n raw_list = retrieve_list.find_list(category_list)\n \n # get a list of names\n res_list = raw_list[1]\n print(len(res_list))\n print()\n \n \n tweets_data_path = './twitter_data3.txt'\n # example\n #res_list = ['Lou Malnati\\u2019s', 'Pablo Fransico','SLU']\n res_dict = dict_converter(res_list[:100])\n \n df = read_data(tweets_data_path, res_dict)\n print(df.rname.value_counts())\n rank = analyze_df(df)\n \n for i in rank:\n print(i)\n \n \n \n","sub_path":"analysis2.py","file_name":"analysis2.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"548462489","text":"import read, copy\nfrom util import *\nfrom logical_classes import *\n\nverbose = 0\n\nclass KnowledgeBase(object):\n def __init__(self, facts=[], rules=[]):\n self.facts = facts\n self.rules = rules\n self.ie = InferenceEngine()\n\n def __repr__(self):\n return 'KnowledgeBase({!r}, {!r})'.format(self.facts, self.rules)\n\n def __str__(self):\n string = \"Knowledge Base: \\n\"\n string += \"\\n\".join((str(fact) for fact in self.facts)) + \"\\n\"\n string += \"\\n\".join((str(rule) for rule in self.rules))\n return string\n\n def _get_fact(self, fact):\n \"\"\"INTERNAL USE ONLY\n Get the fact in the KB that is the same as the fact argument\n\n Args:\n fact (Fact): Fact we're searching for\n\n Returns:\n Fact: matching fact\n \"\"\"\n for kbfact in self.facts:\n if fact == kbfact:\n return kbfact\n\n def _get_rule(self, rule):\n \"\"\"INTERNAL USE ONLY\n Get the rule in the KB that is the same as the rule argument\n\n Args:\n rule (Rule): Rule we're searching for\n\n Returns:\n Rule: matching rule\n \"\"\"\n for kbrule in self.rules:\n if rule == kbrule:\n return kbrule\n\n def kb_add(self, fact_rule):\n \"\"\"Add a fact or rule to the KB\n Args:\n fact_rule (Fact|Rule) - the fact or rule to be added\n Returns:\n None\n \"\"\"\n printv(\"Adding {!r}\", 1, verbose, [fact_rule])\n if isinstance(fact_rule, Fact):\n if fact_rule not in self.facts:\n self.facts.append(fact_rule)\n for rule in self.rules:\n self.ie.fc_infer(fact_rule, rule, self)\n else:\n if fact_rule.supported_by:\n ind = self.facts.index(fact_rule)\n for f in fact_rule.supported_by:\n self.facts[ind].supported_by.append(f)\n else:\n ind = self.facts.index(fact_rule)\n self.facts[ind].asserted = True\n elif isinstance(fact_rule, Rule):\n if fact_rule not in self.rules:\n self.rules.append(fact_rule)\n for fact in self.facts:\n self.ie.fc_infer(fact, fact_rule, self)\n else:\n if fact_rule.supported_by:\n ind = self.rules.index(fact_rule)\n for f in fact_rule.supported_by:\n self.rules[ind].supported_by.append(f)\n else:\n ind = self.rules.index(fact_rule)\n self.rules[ind].asserted = True\n\n def kb_assert(self, fact_rule):\n \"\"\"Assert a fact or rule into the KB\n\n Args:\n fact_rule (Fact or Rule): Fact or Rule we're asserting\n \"\"\"\n printv(\"Asserting {!r}\", 0, verbose, [fact_rule])\n self.kb_add(fact_rule)\n\n def kb_ask(self, fact):\n \"\"\"Ask if a fact is in the KB\n\n Args:\n fact (Fact) - Statement to be asked (will be converted into a Fact)\n\n Returns:\n listof Bindings|False - list of Bindings if result found, False otherwise\n \"\"\"\n print(\"Asking {!r}\".format(fact))\n if factq(fact):\n f = Fact(fact.statement)\n bindings_lst = ListOfBindings()\n # ask matched facts\n for fact in self.facts:\n binding = match(f.statement, fact.statement)\n if binding:\n bindings_lst.add_bindings(binding, [fact])\n\n return bindings_lst if bindings_lst.list_of_bindings else []\n\n else:\n print(\"Invalid ask:\", fact.statement)\n return []\n\n def kb_retract(self, fact_or_rule):\n \"\"\"Retract a fact from the KB\n\n Args:\n fact (Fact) - Fact to be retracted\n\n Returns:\n None\n \"\"\"\n printv(\"Retracting {!r}\", 0, verbose, [fact_or_rule])\n ####################################################\n # Student code goes here\n\n if isinstance(fact_or_rule, Fact):\n if not fact_or_rule in self.facts:\n return\n fact_to_remove = self.facts[self.facts.index(fact_or_rule)]\n if not fact_to_remove.supported_by:\n if fact_to_remove.asserted:\n fact_to_remove.asserted = False\n for fact in fact_to_remove.supports_facts:\n fact_to_retract = self.facts[self.facts.index(fact)]\n for x in fact_to_retract.supported_by[:]:\n if fact_to_remove in x:\n fact_to_retract.supported_by.remove(x)\n if not fact_to_retract.asserted:\n self.kb_retract(fact_to_retract)\n for rule in fact_to_remove.supports_rules:\n rule_to_retract = self.rules[self.rules.index(rule)]\n for x in rule_to_retract.supported_by[:]:\n if fact_to_remove in x:\n rule_to_retract.supported_by.remove(x)\n if not rule_to_retract.asserted:\n self.kb_retract(rule_to_retract)\n self.facts.remove(fact_to_remove)\n\n elif isinstance(fact_or_rule, Rule):\n if not fact_or_rule in self.rules:\n return\n rule_to_remove = self.rules[self.rules.index(fact_or_rule)]\n if not rule_to_remove.supported_by and not rule_to_remove.asserted:\n for fact in rule_to_remove.supports_facts:\n fact_to_retract = self.facts[self.facts.index(fact)]\n for x in fact_to_retract.supported_by[:]:\n if rule_to_remove in x:\n fact_to_retract.supported_by.remove(x)\n if not fact_to_retract.asserted:\n self.kb_retract(fact_to_retract)\n for rule in rule_to_remove.supports_rules:\n rule_to_retract = self.rules[self.rules.index(rule)]\n for x in rule_to_retract.supported_by[:]:\n if rule_to_remove in x:\n rule_to_retract.supported_by.remove(x)\n if not rule_to_retract.asserted:\n self.kb_retract(rule_to_retract)\n self.rules.remove(rule_to_remove)\n\n\nclass InferenceEngine(object):\n def fc_infer(self, fact, rule, kb):\n \"\"\"Forward-chaining to infer new facts and rules\n\n Args:\n fact (Fact) - A fact from the KnowledgeBase\n rule (Rule) - A rule from the KnowledgeBase\n kb (KnowledgeBase) - A KnowledgeBase\n\n Returns:\n Nothing \n \"\"\"\n printv('Attempting to infer from {!r} and {!r} => {!r}', 1, verbose,\n [fact.statement, rule.lhs, rule.rhs])\n ####################################################\n # Student code goes here\n \n bindings = match(fact.statement, rule.lhs[0])\n # if fact and rule match, then we have bindings to be True\n if bindings:\n if len(rule.lhs) == 1:\n # At first, use deepcopy and change the predicate and terms.\n # Now use instantiate instead. \n # In this way, create a statement and link its predicate and terms to original statement. \n outcome_fact = Fact(instantiate(rule.rhs, bindings), [[fact, rule]])\n \"\"\"\n rule_cp = copy.deepcopy(rule)\n outcome_fact = Fact(rule_cp.rhs, [[fact, rule]])\n for term in outcome_fact.statement.terms:\n if term.term.element in bindings.bindings_dict:\n ind = outcome_fact.statement.terms.index(term)\n outcome_fact.statement.terms[ind].term = Constant(bindings.bindings_dict[term.term.element])\n \"\"\"\n fact.supports_facts.append(outcome_fact)\n rule.supports_facts.append(outcome_fact)\n kb.kb_add(outcome_fact)\n else:\n outcome_rule = Rule([[instantiate(state_lhs, bindings) for state_lhs in rule.lhs[1:]], instantiate(rule.rhs, bindings)], [[fact, rule]])\n # At first, use deepcopy and change the predicate and terms.\n # Now use instantiate instead. \n # In this way, create a statement and link its predicate and terms to original statement. \n \"\"\"\n rule_cp = copy.deepcopy(rule)\n outcome_rule = Rule([rule_cp.lhs[1:], rule_cp.rhs], [[fact, rule]])\n for lhs_statement in outcome_rule.lhs:\n for term in lhs_statement.terms:\n if term.term.element in bindings.bindings_dict:\n ind = lhs_statement.terms.index(term)\n lhs_statement.terms[ind].term = Constant(bindings.bindings_dict[term.term.element])\n for term in outcome_rule.rhs.terms:\n if term.term.element in bindings.bindings_dict:\n ind = outcome_rule.rhs.terms.index(term)\n outcome_rule.rhs.terms[ind].term = Constant(bindings.bindings_dict[term.term.element])\n \"\"\"\n fact.supports_rules.append(outcome_rule)\n rule.supports_rules.append(outcome_rule)\n kb.kb_add(outcome_rule)\n\n","sub_path":"student_code.py","file_name":"student_code.py","file_ext":"py","file_size_in_byte":9580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"90870684","text":"import json\n \n \n# the file to be converted to \n# json format\nfile= 'JSON/data.txt'\n \n# dictionary where the lines from\n# text will be stored\ndict1 = {}\n \n# creating dictionary\nwith open(file) as f:\n \n for s in f:\n key, description = s.strip().split(None, 1)\n dict1[key] = description.strip()\n \n# creating json file\n# the JSON file is named as test1\nout_file = open(\"JSON/json_file.json\", \"w\")\njson.dump(dict1,out_file)\n# json.dump(dict1, out_file, indent = 4, sort_keys = False)\n# out_file.close()\n\n# import json\n# filename = 'JSON/data.txt'\n# dict1 = {}\n# with open(filename) as fh:\n# for line in fh:\n# command, description = line.strip().split(None, 1)\n# dict1[command] = description.strip()\n# out_file = open(\"test1.json\", \"w\")\n# json.dump(dict1, out_file, indent = 7, sort_keys = False)\n# out_file.close()\n\n# file=open(\"data.txt\",\"r\")\n\n\n\n\n","sub_path":"JSON/ques7.py","file_name":"ques7.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"643704866","text":"import numpy as np\nfrom math import sqrt\nfrom numpy.polynomial.legendre import legval\nfrom astropy.io import fits\nfrom math import pi\nimport matplotlib.pyplot as plt\nimport time\nimport sys\nsys.path.append(\"/home/g.samarth/\")\nfrom heliosPy import datafuncs as cdata\n\n\nclass coupMat:\n \"\"\" Class for handling objects related to C_{ij} (parameter matrix)\n\n Attributes:\n -----------\n lmin - int\n minimum value of ell for which C_{ij} if fit\n lmax - int\n maximum value of ell for which C_{ij} is fit\n dl_coup - int\n maximum value of abs(i - j); i^th mode is coupled to j^th mode\n if |i - j| <= dl_coup\n msz_coup - int\n size of coupling matrix C_{ij}; matrix is square\n coup_mat - np.ndarray(ndim=2, dtype=float)\n the coupling matrix C_{ij}\n la_mat - np.ndarray(ndim=2, dtype=int)\n (a : above) matrix containing ell values of upper index i of C^i_j\n lb_mat - np.ndarray(ndim=2, dtype=int)\n (b : below) matrix containing ell values of lower index j of C^i_j\n ind_mat - np.ndarray(ndim=2, dtype=int)\n matrix containing a combined index of (i, j)\n mask - np.ndarray(ndim=2, dtype=bool)\n mask to filter out values beyond dl_coup\n\n Methods:\n --------\n generate_synth()\n generates synthetic C^i_j for testing\n\n \"\"\"\n\n def __init__(self, lmin, lmax, dl_coup):\n self.lmin = lmin\n self.lmax = lmax\n self.dl_coup = dl_coup\n self.msz_coup = lmax - lmin\n self.coup_mat = np.identity(self.msz_coup, dtype=float)\n\n bool_mat = np.zeros((self.msz_coup, self.msz_coup), dtype=np.bool)\n ell1_mat = np.zeros((self.msz_coup, self.msz_coup), dtype=np.int)\n ell2_mat = np.zeros((self.msz_coup, self.msz_coup), dtype=np.int)\n for i in range(self.msz_coup):\n for j in range(self.msz_coup):\n if abs(i-j) <= self.dl_coup:\n bool_mat[i, j] = True\n ell1_mat[i, j] = i + lmin\n ell2_mat[i, j] = j + lmin\n ind_mat = np.zeros_like(bool_mat, dtype=np.int)\n ind_mat[bool_mat] = np.arange(bool_mat.sum())\n\n self.la_mat = ell1_mat\n self.lb_mat = ell2_mat\n self.ind_mat = ind_mat\n self.mask = bool_mat\n\n def generate_synth(self):\n \"\"\"Generates synthetic C^i_j\n\n Block diagonal C^i_j which is diagonally dominant assuming\n that the self coupling is the strongest.\n\n Inputs:\n -------\n None\n\n Outputs:\n --------\n None\n\n *Updates the coup_mat attribute of the coupMat object.*\n\n \"\"\"\n\n self.coup_mat[self.mask] = 0.3*np.random.rand(self.mask.sum())\n for i in range(self.msz_coup):\n self.coup_mat[i, i] = 1 - 0.3*np.random.rand()\n _norm = sqrt((abs(self.coup_mat[i, :])**2).sum())\n self.coup_mat[i, :] /= _norm\n return None\n\n\ndef resid2(x, f1N, p1, noise_level):\n f1N_fit, _temp = trans2(x, p1, noise_level)\n diff = f1N_fit - f1N\n resid = (abs(diff)**2).sum()\n return f1N_fit, diff, resid\n\n\ndef gauss_newton(J, res, p1, damping):\n jtj = J.transpose().dot(J)\n jtji = np.linalg.pinv(jtj, rcond=1e-15)\n p_add = jtji.dot(J.transpose().dot(res))\n return p1 + damping*p_add\n\n\ndef iter_gn2(p1, x, f1N, Niter, damping, noise_level):\n for i in range(Niter):\n J = jacob2(len(p1), len(x), x, p1)\n f1N_fit, res_vec, S = resid2(x, f1N, p1, noise_level)\n if i > 0 and S > sval[-1]:\n dp = -damping\n else:\n dp = damping\n p1 = gauss_newton(J, res_vec, p1, dp)\n\n sval = S if i == 0 else np.append(sval, S)\n return pval0, pval1, sval\n\n\ndef finda1(data, l, n, m):\n \"\"\"\n Find a coefficients for given l, n, m\n \"\"\"\n L = sqrt(l*(l+1))\n try:\n modeindex = np.where((data[:, 0] == l) * (data[:, 1] == n))[0][0]\n except IndexError:\n print(f\"MODE NOT FOUND : l = {l}, n = {n}\")\n return None, None, None\n splits = np.append([0.0], data[modeindex, 12:48])\n totsplit = legval(1.0*m/L, splits)*L\n return totsplit\n\n\ndef create_synth(l1, n1, l2, n2, coupmat):\n \"\"\"Create synthetic dataset for testing out fitting algorithm\n Inputs:\n -------\n\n Outputs:\n --------\n\n \"\"\"\n # calculation parameters\n dl = 6 # delta_ell for leakage matrix\n dm = 15 # delta_m for leakage matrix\n dl_mat = 6 # max delta_ell for leakage matrix\n dm_mat = 15 # max delta_m for leakage matrix\n\n rsun = 6.9598e10\n twopiemin6 = 2*pi*1e-6\n\n daynum = 1 # length of time series\n tsLen = 138240 # array length of the time series\n\n # time domain and frequency domain\n t = np.linspace(0, 72*24*3600*daynum, tsLen*daynum)\n dt = t[1] - t[0]\n freq = np.fft.fftfreq(t.shape[0], dt)*1e6\n# df = freq[1] - freq[0] # frequencies in microHz\n\n rleaks = fits.open('/home/g.samarth/leakage/rleaks1.fits')[0].data\n horleaks = fits.open('/home/g.samarth/leakage/horleaks1.fits')[0].data\n rleaks1 = rleaks[:, :, l1, :].copy()\n rleaks2 = rleaks[:, :, l2, :].copy()\n horleaks1 = horleaks[:, :, l1, :].copy()\n horleaks2 = horleaks[:, :, l2, :].copy()\n del rleaks, horleaks\n\n # new norms\n cnl1 = np.loadtxt(writedir + f\"norm_{l1:03d}_{n1:02d}\")\n cnl2 = np.loadtxt(writedir + f\"norm_{l2:03d}_{n2:02d}\")\n mode_data = np.loadtxt('/home/g.samarth/leakage/hmi.6328.36')\n\n omeganl1, fwhmnl1, amp1 = cdata.findfreq(mode_data, l1, n1, 0)\n omeganl2, fwhmnl2, amp2 = cdata.findfreq(mode_data, l2, n2, 0)\n\n norm1 = amp1*amp1 * omeganl1*omeganl1 * cnl1 * fwhmnl1 * twopiemin6**3\n norm2 = amp2*amp2 * omeganl2*omeganl2 * cnl2 * fwhmnl2 * twopiemin6**3\n norm = sqrt(norm1*norm2)\n\n t1 = time.time()\n for m in range(l1+1):\n for dell1 in range(-dl, dl+1):\n dell2 = dell1 - l2 + l1\n l21 = l1 + dell1\n tempnorm = 1.0 # 0.8 + 0.2*np.random.rand()\n for dem in range(-dm, dm+1):\n m2 = m+dem\n if (abs(m2) <= l21):\n omeganl1, fwhmnl1, amp1 = cdata.findfreq(mode_data,\n l21, n2, m2)\n mix = (274.8*1e2*(l21+0.5) /\n ((twopiemin6)**2*rsun))/omeganl1**2\n leak1 = rleaks1[dem+dm_mat, dell1+dl_mat, m+249] +\\\n mix*horleaks1[dem+dm_mat, dell1+dl_mat, m+249]\n leak2 = rleaks2[dem+dm_mat, dell2+dl_mat, m+249] +\\\n mix*horleaks2[dem+dm_mat, dell2+dl_mat, m+249]\n phi1 = cdata.lorentzian(omeganl1 - finda1(mode_data,\n l1, n1, m),\n fwhmnl1, freq)\n phi1sum = phi1sum +\\\n leak1*leak2 * phi1*phi1.conjugate() * tempnorm\n cs[m, :] = phi1sum*norm\n phi1sum = 0.0*phi1sum\n t2 = time.time()\n print(f\" Total time taken = {(t2 - t1):10.5f} seconds\")\n\n\nif __name__ == \"__main__\":\n print(f\"program start\")\n\n # directories\n writedir = '/scratch/g.samarth/csfit/'\n","sub_path":"cs_fit.py","file_name":"cs_fit.py","file_ext":"py","file_size_in_byte":7206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"57726733","text":"# -*- coding: utf-8 -*-\n\"\"\"\n:mod:`orion.client.manual` -- Routines for manual interaction with database\n=============================================================================\n\n.. module:: manual\n :platform: Unix\n :synopsis: Provides a simple interface to log new trials into the database\n and link them with a particular existing experiment.\n\n\"\"\"\nfrom orion.core.io.experiment_builder import ExperimentBuilder\nfrom orion.core.utils import format_trials\n\n\ndef insert_trials(experiment_name, points, cmdconfig=None, raise_exc=True):\n \"\"\"Insert sets of parameters manually, defined in `points`, as new trials\n for the experiment name, `experiment_name`.\n\n :param experiment_name: Name of the experiment which the new trials are\n going to be associated with\n :param points: list of tuples in agreement with experiment's parameter space\n :param raise_exc: whether an inappropriate tuple of parameters will raise\n an exception or it will be ignored\n\n .. note:: If `raise_exc` is True, no set of parameters will be inserted. If\n it is False, only the valid ones will be inserted; the rest will be ignored.\n\n .. note:: This cannot be used to prepopulate a future experiment. So,\n an experiment with `experiment_name` should already be configured in\n the database.\n\n \"\"\"\n cmdconfig = cmdconfig if cmdconfig else {}\n cmdconfig['name'] = experiment_name\n\n experiment_view = ExperimentBuilder().build_view_from({'config': cmdconfig})\n\n valid_points = []\n\n print(experiment_view.space)\n\n for point in points:\n try:\n assert point in experiment_view.space\n valid_points.append(point)\n except AssertionError:\n if raise_exc:\n raise\n\n if not valid_points:\n return\n\n new_trials = list(\n map(lambda data: format_trials.tuple_to_trial(data, experiment_view.space),\n valid_points))\n\n for new_trial in new_trials:\n ExperimentBuilder().build_from(experiment_view.configuration).register_trial(new_trial)\n","sub_path":"src/orion/client/manual.py","file_name":"manual.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"376778453","text":"\r\nimport time as t\r\nfrom _thread import *\r\nfrom chat import Chat\r\n\r\n\r\nclass Runda(object):\r\n def __init__(self, haslo, rysujacy, gra):\r\n \r\n self.haslo = haslo\r\n self.rysujacy = rysujacy\r\n self.gracz_zgadujacy = []\r\n self.gracze_pomijajacy = []\r\n self.liczba_pominiec = 0\r\n self.czas = 75 #czas trfania rundy\r\n self.gra = gra\r\n self.wyniki_gracza = {gracz: 0 for gracz in self.gra.gracze}\r\n self.chat = Chat(self)\r\n start_new_thread(self.czas_thread, ()) #uruchomienie nowego wątki\r\n\r\n def pomin(self, gracz):\r\n \r\n if gracz not in self.gracze_pomijajacy:\r\n self.gracze_pomijajacy.append(gracz)\r\n self.liczba_pominiec += 1\r\n self.chat.update_chat(f\"Głosowanie za pominieciem rundy ({self.liczba_pominiec}/{len(self.gra.gracze) -2})\")\r\n if self.liczba_pominiec >= len(self.gra.gracze) - 2:\r\n return True\r\n\r\n return False\r\n\r\n def get_wyniki(self):\r\n \r\n return self.wyniki_gracza\r\n\r\n def get_wynik(self, gracz):\r\n \r\n if gracz in self.wyniki_gracza:\r\n return self.wyniki_gracza[gracz]\r\n else:\r\n raise Exception(\"Gracz nie figuruje w tablicy wynikow\")\r\n\r\n def czas_thread(self):\r\n \r\n while self.czas > 0:\r\n t.sleep(1)\r\n self.czas -= 1\r\n self.koniec_rundy(\"Skończył się czas\")\r\n\r\n def zgadywanie(self, gracz, wrd):\r\n \r\n poprawna_odpowiedz = wrd.lower() == self.haslo.lower()\r\n if poprawna_odpowiedz:\r\n self.chat.update_chat(\"Odgadnieto haslo\")\r\n t.sleep(1)\r\n gracz.update_wynik(1)\r\n gracz.get_wynik()\r\n self.koniec_rundy(\"Odgadnięto haslo\")\r\n else:\r\n self.chat.update_chat(f\"{gracz.nazwa} : {wrd}\")\r\n\r\n\r\n def rozlaczenie(self, gracz):\r\n \r\n if gracz in self.wyniki_gracza:\r\n del self.wyniki_gracza[gracz]\r\n\r\n if gracz in self.gracz_zgadujacy:\r\n self.gracz_zgadujacy.remove(gracz)\r\n\r\n if gracz == self.rysujacy:\r\n self.chat.update_chat(\"Rysujacy gracz opuścił grę\")\r\n self.koniec_rundy(\"Rysujacy gracz opuścił grę\")\r\n\r\n def koniec_rundy(self, msg):\r\n for gracz in self.gra.gracze:\r\n if gracz in self.wyniki_gracza:\r\n gracz.update_wynik(self.wyniki_gracza[gracz])\r\n self.gra.koniec_rundy()\r\n\r\n","sub_path":"Kalambury/Zadanie2/server/runda.py","file_name":"runda.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"244767315","text":"import tcod\nfrom random import randint\n\nfrom defs import game\nfrom defs.colors import palette\nfrom ecs.recipes import mob_recipes, item_recipes\nfrom ecs.components import Position\nimport numpy as np\n\n\nclass GameMap(tcod.map.Map):\n def __init__(self, width, height):\n super().__init__(width, height)\n self.explored = np.zeros((height, width, 1), dtype=np.bool_)\n\n\nclass Rect:\n def __init__(self, x, y, w, h):\n self.x1 = x\n self.y1 = y\n self.x2 = x + w\n self.y2 = y + h\n\n def center(self):\n new_x = int((self.x1 + self.x2) / 2)\n center_y = int((self.y1 + self.y2) / 2)\n return (new_x, center_y)\n\n def intersect(self, other):\n # returns true if this rectangle intersects with another one\n return (\n self.x1 <= other.x2\n and self.x2 >= other.x1\n and self.y1 <= other.y2\n and self.y2 >= other.y1\n )\n\n\ndef set_walkable(game_map, x, y):\n game_map.walkable[y, x] = True\n game_map.transparent[y, x] = True\n\n\n# Takes a map, and a rect, and makes the rect walkable (leaving walls)\ndef create_room(game_map, room):\n for x in range(room.x1 + 1, room.x2):\n for y in range(room.y1 + 1, room.y2):\n set_walkable(game_map, x, y)\n\n\ndef create_horizontal_tunnel(game_map, start, end, y):\n for x in range(min(start, end), max(start, end) + 1):\n set_walkable(game_map, x, y)\n\n\ndef create_vertical_tunnel(game_map, start, end, x):\n for y in range(min(start, end), max(start, end) + 1):\n set_walkable(game_map, x, y)\n\n\ndef draw_char(console, x, y, legend=\" \", fg=None, bg=None):\n if bg:\n console.bg[y, x] = bg\n if fg:\n console.fg[y, x] = fg\n console.put_char(x, y, ord(legend))\n\n\ndef draw_map(game_map, console):\n for x in range(game_map.width):\n for y in range(game_map.height):\n wall = not game_map.transparent[y, x]\n\n if game_map.fov[y, x]:\n if wall:\n draw_char(console, x, y, bg=palette.lit_wall)\n else:\n draw_char(console, x, y, bg=palette.lit_floor)\n\n game_map.explored[y, x] = True\n elif game_map.explored[y, x]:\n if wall:\n draw_char(console, x, y, bg=palette.unlit_wall)\n\n else:\n draw_char(console, x, y, bg=palette.unlit_floor)\n\n\ndef place_entities(ecs, game_map, room, max_monsters_per_room):\n num_monsters = randint(0, max_monsters_per_room)\n for i in range(num_monsters):\n x = randint(room.x1 + 1, room.x2 - 1)\n y = randint(room.y1 + 1, room.y2 - 1)\n\n space_full = False\n for ent, pos in ecs.get_component(Position):\n if pos.x == x and pos.y == y:\n space_full = True\n\n if not space_full:\n mob_recipes.create_goblin(ecs, x, y, game_map)\n\n\ndef place_items(ecs, room, max_items_per_room):\n num_items = randint(0, max_items_per_room)\n for i in range(num_items):\n x = randint(room.x1 + 1, room.x2 - 1)\n y = randint(room.y1 + 1, room.y2 - 1)\n\n item_recipes.healing_potion(ecs, x, y)\n\n\ndef make_map(\n game_map,\n player,\n ecs,\n max_rooms,\n min_room_size,\n max_room_size,\n map_width,\n map_height,\n):\n rooms = []\n num_rooms = 0\n\n for r in range(max_rooms):\n # Random width and height\n w = randint(min_room_size, max_room_size)\n h = randint(min_room_size, max_room_size)\n\n # Random position\n x = randint(0, map_width - w - 1)\n y = randint(0, map_height - h - 1)\n\n new_room = Rect(x, y, w, h)\n for other_room in rooms:\n if new_room.intersect(other_room):\n break\n else:\n # There is no intersection\n create_room(game_map, new_room)\n (new_x, new_y) = new_room.center()\n\n # If this is the first room, the player starts there\n if num_rooms == 0:\n # Remove position, add new position\n if ecs.has_component(player, Position):\n pos = ecs.component_for_entity(player, Position)\n pos.x = new_x\n pos.y = new_y\n else:\n # For every other room connect it to the previous\n # Make this only go to the edge of the room, otherwise we can\n # accidenally mark tiles walkable that have entities in them\n (prev_x, prev_y) = rooms[num_rooms - 1].center()\n\n if randint(0, 1) == 1:\n # Horizontal then Vertical\n create_horizontal_tunnel(game_map, prev_x, new_x, prev_y)\n create_vertical_tunnel(game_map, prev_y, new_y, new_x)\n else:\n # Vertical then Horizontal\n create_vertical_tunnel(game_map, prev_y, new_y, new_x)\n create_horizontal_tunnel(game_map, prev_x, new_x, prev_y)\n\n place_entities(ecs, game_map, new_room, game.MAX_MONSTERS_PER_ROOM)\n place_items(ecs, new_room, game.MAX_ITEMS_PER_ROOM)\n rooms.append(new_room)\n num_rooms += 1\n","sub_path":"src/sim/map_utils.py","file_name":"map_utils.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"97670168","text":"\"\"\"\nCreated on Feb 17, 2015\n\n@author: Jason Bowles\n\"\"\"\nfrom rawdata_emca.connections import BaseConnector\n\nclass MockConnector(BaseConnector):\n \"\"\"\n This is a simple connector that can mock up data and create the csv output\n \"\"\"\n\n\n def set_params(self, kwargs):\n \"\"\"\n pass in the property file name to establish the connection criteria\n \"\"\"\n self.load_params(kwargs)\n self.options = {}\n keys = kwargs.keys()\n self.rows = []\n for key in keys:\n if key.startswith(\"header\"):\n self.header = kwargs[key]\n elif key.startswith(\"row\"):\n self.rows.append(kwargs[key])\n else:\n self.options[key] = kwargs[key]\n \n def execute_connection(self):\n \"\"\" \n This just collects the hard coded data listed in configuration file\n \"\"\"\n self.entry.temp_results = \"TempCSV\"\n csv_in = self.get_temp_csv_name()\n \n header = []\n i = 0\n hdict = {}\n for col in self.header.split(\",\"):\n header.append(col)\n hdict[i] = col\n i = i + 1\n \n self.setup_csv_temp_writer(csv_in, header)\n import time\n time.sleep(3)\n for row in self.rows:\n rdict = {}\n i = 0\n for cell in row.split(\",\"):\n rdict[hdict[i]] = cell\n i = i + 1\n self.write_temp_rec(rdict)\n \n self.close_temp_csv(sort=True)\n return 0\n ","sub_path":"rawdata_emca/connections/mock.py","file_name":"mock.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"324009511","text":"from nose.tools import assert_equal\nfrom recipyGui import highlight\n\ndef test_highlight():\n \"\"\"Test the highlight filter\"\"\"\n cases = [\n {'txt': 'test', 'q': None, 'out': 'test'},\n {'txt': 'test', 'q': 'test', 'out': 'test'},\n {'txt': None, 'q': None, 'out': None}\n ]\n\n for c in cases:\n yield assert_equal, highlight(text=c['txt'], query=c['q']), c['out']\n","sub_path":"recipyGui/tests/test_filters.py","file_name":"test_filters.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"35660795","text":"# coding: utf-8\nfrom django.shortcuts import render_to_response\nimport random\nimport copy\nfrom util.safe_view import safe_view\nfrom city.models import City\nfrom city.utils import city_get_info, get_dist\n\n\n@safe_view(auth_required=False)\ndef cities_list_view(request):\n cities = City.objects.all()\n return list(map(lambda city: city.get_data(), cities))\n\n\n@safe_view()\ndef top_cities_view(request):\n print(\"TOP_CITIES by {}\".format(request.user))\n cities = City.objects.all()\n cities_info = list(reversed(sorted(\n map(lambda city: city_get_info(request, city), cities),\n key=lambda ci: ci[\"info\"][\"raw_rank\"],\n )))\n\n res_cities_info = cities_info[:30]\n min_rank = min(4.5, float(cities_info[15][\"info\"][\"rank\"]))\n norm_cities_info = list(filter(lambda ci: float(ci[\"info\"][\"rank\"]) >= min_rank, cities_info))\n for ci in res_cities_info:\n path_cities = []\n for norm_ci in norm_cities_info:\n if norm_ci == ci:\n continue\n dist = get_dist(\n (ci[\"city\"][\"latitude\"], ci[\"city\"][\"longitude\"]),\n (norm_ci[\"city\"][\"latitude\"], norm_ci[\"city\"][\"longitude\"]),\n )\n full_dist = ci[\"info\"][\"distance\"]\n norm_dist = norm_ci[\"info\"][\"distance\"]\n add_kms = 20\n if full_dist >= 300:\n if norm_dist < full_dist/4:\n add_kms = ((norm_dist / (full_dist/4))**2) * 70\n else:\n add_kms = 150\n if norm_dist + dist <= min(add_kms + full_dist, 1.2 * full_dist):\n new_norm_ci = copy.deepcopy(norm_ci)\n if \"path_cities\" in new_norm_ci:\n new_norm_ci[\"path_cities\"] = []\n path_cities.append(new_norm_ci)\n ci[\"path_cities\"] = path_cities\n\n return res_cities_info\n\n\n@safe_view()\ndef city_info_view(request, id):\n city = City.objects.get(id=id)\n return city_get_info(request, city)\n\n\ndef cities_web_view(request):\n cities = City.objects.all()\n return render_to_response(\"cities.html\", {\n \"cities\": cities,\n })\n","sub_path":"trips/city/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"402873814","text":"#!/usr/bin/env python\n# Run via sdmain/lab/bodega/test/client\n\n'''\nfunctional test cases for CR(U)D operations around reservation tasks/operations\nCreated on 02/25/2016\n@author: sandeep rikhi\n'''\n\nimport sys\nimport os\nimport json\nimport yaml\nimport logging\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\nSDMAIN_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR,\n '..', '..', '..', '..'))\nsys.path.append(os.path.join(SDMAIN_ROOT, 'src', 'scripts'))\nsys.path.append(os.path.join(SCRIPT_DIR, '..'))\nfrom bodega_client import BodegaClient, TokenAuth\nfrom server_connection_settings import (\n BODEGA_CLIENT_AUTH_TOKEN, BODEGA_SERVER_HOST)\n\n\ndef test_operation_flow():\n auth = TokenAuth(BODEGA_CLIENT_AUTH_TOKEN)\n bodega_client = BodegaClient(BODEGA_SERVER_HOST, auth)\n\n # Create a reservation request\n conf_path = 'basic_testbed.yml'\n with open(conf_path, 'r') as conf_file:\n testbed_specs = yaml.load(conf_file)\n\n # Create a dummy operation request\n spec_name = 'BASIC_TESTBED'\n operation_info = \\\n bodega_client.create_acquire_operation(testbed_specs[spec_name])\n\n logging.debug(\"\\nOperation-Request\\n%s\" % (json.dumps(operation_info,\n indent=2,\n sort_keys=True)))\n test_operation_id = operation_info['id']\n\n # Get specific operation details and confirm id\n operation_info = \\\n bodega_client.get_operation_details_by_id(test_operation_id)\n logging.debug(\"\\nOperation-Info\\n%s\" % (json.dumps(operation_info,\n indent=2,\n sort_keys=True)))\n assert test_operation_id == operation_info['id']\n\n # List all reservation requests\n all_operations = bodega_client.get_all_operations_list()\n logging.debug(\"Found %d total operations\" % (len(all_operations)))\n for operation_info in all_operations:\n logging.debug(\"\\nOperation#%s\\n%s\" % (operation_info['id'],\n json.dumps(operation_info,\n indent=2,\n sort_keys=True)))\n\n # List all operations in 'CREATED' state\n list_operations = bodega_client.get_operations_list_by_state('CREATED')\n logging.debug(\"Found %d operations in CREATED state\"\n % (len(list_operations)))\n for operation_info in all_operations:\n logging.debug(\"\\nOperation#%s\\n%s\" % (operation_info['id'],\n json.dumps(operation_info,\n indent=2,\n sort_keys=True)))\n list_operations = \\\n bodega_client.get_operations_list_by_method_and_state('ACQUIRE',\n 'CREATED')\n for operation_info in all_operations:\n logging.debug(\"\\nOperation#%s\\n%s\" % (operation_info['id'],\n json.dumps(operation_info,\n indent=2,\n sort_keys=True)))\n # Delete the dummy operation request we added\n bodega_client.abort_operation(test_operation_id)\n","sub_path":"lab/bodega/client/tests/test_operations.py","file_name":"test_operations.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"33861650","text":"# Copyright 2017 Battelle Energy Alliance, LLC\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 #***************************************\n #* Simple analytic test ExternalModule *\n #***************************************\n #\n # Simulates time-dependent track of a projectile through the air from start to 0,\n # assuming no air resistance.\n # Inputs:\n # (x0,y0) - initial position\n # v0 - initial total velocity\n # ang - angle of initial motion, in degrees, with respect to flat ground\n # Outputs:\n # (x,y) - vector positions of projectile in time\n # t - corresponding time steps\n #\n\"\"\"\nimport numpy as np\n\ndef range(v,th,y0=0,g=9.8):\n \"\"\"\n This method is aimed to compute the range of a projectile through the air given\n the velocity, angle, elevation and gravity acceleration\n @ In, v, float, velocity\n @ In, th, float, angle (rad)\n @ In, y0, float, elevation\n @ In, g, float, gravity\n \"\"\"\n return v*np.cos(th)/g * (v*np.sin(th) + np.sqrt(v*v*np.sin(th)**2+2.*g*y0))\n\ndef run(self,Input):\n x0 = Input.get('x0',0.0)\n y0 = Input.get('y0',0.0)\n v0 = Input.get('v0',1.0)\n ang = Input.get('angle',45.)*np.pi/180.\n\n ts = np.linspace(0,1,10)\n\n vx0 = np.cos(ang)*v0\n vy0 = np.sin(ang)*v0\n r = range(v0,ang,y0)\n # ***************************************************************************\n # * this is an example of a penalty function applied on the loss function. *\n # * the v0 should converge around 40 *\n # ***************************************************************************\n if v0 > 40.0:\n r -= 10.0*(v0-40.0)**2\n # ***************************************************************************\n # * end of penalty function *\n # ***************************************************************************\n\n self.x = np.zeros(len(ts))\n self.y = np.zeros(len(ts))\n self.r = np.zeros(len(ts))\n for i,t in enumerate(ts):\n self.x[i] = x0 + vx0*t\n self.y[i] = y0 + vy0*t - 4.9*t*t\n self.r[i] = r\n self.time = ts\n","sub_path":"tests/framework/Optimizers/GradientBasedOptimizers/maxRangeWithBoundaryConstraintsWithPenalty/projectilePenalty.py","file_name":"projectilePenalty.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"364552062","text":"\"\"\"\n 我们使用币安原生的api进行数据爬取.\n\n\"\"\"\n\nimport pandas as pd\nimport time\nfrom datetime import datetime\nimport requests\nimport pytz\nfrom howtrader.trader.database import database_manager\n\npd.set_option('expand_frame_repr', False) #\nfrom howtrader.trader.object import BarData, Interval, Exchange\n\nBINANCE_SPOT_LIMIT = 1000\nBINANCE_FUTURE_LIMIT = 1500\n\nCHINA_TZ = pytz.timezone(\"Asia/Shanghai\")\nfrom threading import Thread\n\n\ndef generate_datetime(timestamp: float) -> datetime:\n \"\"\"\n :param timestamp:\n :return:\n \"\"\"\n dt = datetime.fromtimestamp(timestamp / 1000)\n dt = CHINA_TZ.localize(dt)\n return dt\n\n\ndef get_binance_data(symbol: str, exchanges: str, start_time: str, end_time: str):\n \"\"\"\n 爬取币安交易所的数据\n :param symbol: BTCUSDT.\n :param exchanges: 现货、USDT合约, 或者币币合约.\n :param start_time: 格式如下:2020-1-1 或者2020-01-01\n :param end_time: 格式如下:2020-1-1 或者2020-01-01\n :return:\n \"\"\"\n\n api_url = ''\n save_symbol = symbol\n gate_way = 'BINANCES'\n\n if exchanges == 'spot':\n print(\"spot\")\n limit = BINANCE_SPOT_LIMIT\n save_symbol = symbol.lower()\n gate_way = 'BINANCE'\n api_url = f'https://api.binance.com/api/v3/klines?symbol={symbol}&interval=1m&limit={limit}'\n\n elif exchanges == 'future':\n print('future')\n limit = BINANCE_FUTURE_LIMIT\n api_url = f'https://fapi.binance.com/fapi/v1/klines?symbol={symbol}&interval=1m&limit={limit}'\n\n elif exchanges == 'coin_future':\n print(\"coin_future\")\n limit = BINANCE_FUTURE_LIMIT\n f'https://dapi.binance.com/dapi/v1/klines?symbol={symbol}&interval=1m&limit={limit}'\n\n else:\n raise Exception('交易所名称请输入以下其中一个:spot, future, coin_future')\n\n start_time = int(datetime.strptime(start_time, '%Y-%m-%d').timestamp() * 1000)\n end_time = int(datetime.strptime(end_time, '%Y-%m-%d').timestamp() * 1000)\n\n while True:\n try:\n print(start_time)\n url = f'{api_url}&startTime={start_time}'\n print(url)\n data = requests.get(url=url, timeout=10, proxies=proxies).json()\n\n \"\"\"\n [\n [\n 1591258320000, // 开盘时间\n \"9640.7\", // 开盘价\n \"9642.4\", // 最高价\n \"9640.6\", // 最低价\n \"9642.0\", // 收盘价(当前K线未结束的即为最新价)\n \"206\", // 成交量\n 1591258379999, // 收盘时间\n \"2.13660389\", // 成交额(标的数量)\n 48, // 成交笔数\n \"119\", // 主动买入成交量\n \"1.23424865\", // 主动买入成交额(标的数量)\n \"0\" // 请忽略该参数\n ]\n\n \"\"\"\n\n buf = []\n\n for l in data:\n bar = BarData(\n symbol=save_symbol,\n exchange=Exchange.BINANCE,\n datetime=generate_datetime(l[0]),\n interval=Interval.MINUTE,\n volume=float(l[5]),\n open_price=float(l[1]),\n high_price=float(l[2]),\n low_price=float(l[3]),\n close_price=float(l[4]),\n gateway_name=gate_way\n )\n buf.append(bar)\n\n database_manager.save_bar_data(buf)\n\n # 到结束时间就退出, 后者收盘价大于当前的时间.\n if (data[-1][0] > end_time) or data[-1][6] >= (int(time.time() * 1000) - 60 * 1000):\n break\n\n start_time = data[-1][0]\n\n except Exception as error:\n print(error)\n time.sleep(10)\n\n\ndef download_spot(symbol):\n \"\"\"\n 下载现货数据的方法.\n :return:\n \"\"\"\n t1 = Thread(target=get_binance_data, args=(symbol, 'spot', \"2018-1-1\", \"2019-1-1\"))\n\n t2 = Thread(target=get_binance_data, args=(symbol, 'spot', \"2019-1-1\", \"2020-1-1\"))\n\n t3 = Thread(target=get_binance_data, args=(symbol, 'spot', \"2020-1-1\", \"2020-11-16\"))\n\n t1.start()\n t2.start()\n t3.start()\n\n t1.join()\n t2.join()\n t3.join()\n\n\ndef download_future(symbol):\n \"\"\"\n 下载合约数据的方法。\n :return:\n \"\"\"\n t1 = Thread(target=get_binance_data, args=(symbol, 'future', \"2019-9-10\", \"2020-3-1\"))\n t2 = Thread(target=get_binance_data, args=(symbol, 'future', \"2019-3-1\", \"2020-11-16\"))\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\n\n\nif __name__ == '__main__':\n\n # 如果你有代理你就设置,如果没有你就设置为 None 或者空的字符串 \"\",\n # 但是你要确保你的电脑网络能访问币安交易所,你可以通过 ping api.binance.com 看看过能否ping得通\n proxy_host = \"127.0.0.1\" # 如果没有就设置为\"\", 如果有就设置为你的代理主机如:127.0.0.1\n proxy_port = 1087 # 设置你的代理端口号如: 1087, 没有你修改为0,但是要保证你能访问api.binance.com这个主机。\n\n proxies = None\n if proxy_host and proxy_port:\n proxy = f'http://{proxy_host}:{proxy_port}'\n proxies = {'http': proxy, 'https': proxy}\n\n symbol = \"BTCUSDT\"\n\n # download_spot(symbol) # 下载现货的数据.\n\n download_future(symbol) # 下载合约的数据\n","sub_path":"examples/download_data_demo2.py","file_name":"download_data_demo2.py","file_ext":"py","file_size_in_byte":5578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"168911376","text":"import random\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport os\n\n# random.uniform(2.0,5.0)\n\nn=20\ndata=[]\nos.system(\"c++ -std=c++14 -O3 main.cpp\")\nfor i in range(n):\n\tf = open(\"input\"+str(i)+\".dat\",'w')\n\t# f.write(str(0.1)+\" \"+str(0)+\"\\n\")\n\tf.write(str(random.uniform(0.0,1.0))+\" \"+str(random.uniform(0.0,1.0))+\"\\n\")\n\tf.close()\n\tos.system(\"./a.outoutput\"+str(i)+\".dat\")\n\tdata.append({})\n\tdata[i] = np.loadtxt(\"output\"+str(i)+\".dat\", comments='!', unpack=True)\n\t# 後処理\n\tos.remove(\"input\"+str(i)+\".dat\")\n\tos.remove(\"output\"+str(i)+\".dat\")\n\nfig = plt.figure(figsize=(6,6))\nplt.axes().set_aspect('equal', 'datalim')\nfor i in range(n):\n\tplt.plot(data[i][1], data[i][2], \"-\", lw=0.5, color=(0,0,0,1))\n\nplt.savefig(\"result.png\", bbox_inches='tight', pad_inches=0)","sub_path":"Numerical-Method/integration/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"223236530","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom sort.base_sort import BaseSort\n\n__author__ = 'sunq'\n\n\nclass ListSort(BaseSort):\n def __init__(self, array):\n self.array = array\n self.exch_count = 0\n self.com_count = 0\n\n def exch(self, i, j):\n temp = self.array[i]\n self.array[i] = self.array[j]\n self.array[j] = temp\n self.exch_count += 1\n\n def less(self, i, j):\n \"\"\"\n i 0 and value < array[index - 1]:\n flag = False\n return flag\n","sub_path":"sort/list_sort.py","file_name":"list_sort.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"98627736","text":"import re\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\n\n# Retrieve all of the anchor tags\ntags = soup('span')\n\nsum = 0\ncount = 0\nfor tag in tags:\n s = tag.decode()\n num = re.findall('\\d+', s)\n sum += int(num[0])\n count += 1\n \nprint(count)\nprint(sum)","sub_path":"Using Python to Access Web Data/Week 4/Assignment 1.py","file_name":"Assignment 1.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270455540","text":"import os\nimport xlrd\nfrom common import readConfig\nimport json\n\n\nclass doExcel:\n\n def __init__(self):\n self.current_dir = os.path.abspath(os.path.dirname(__file__))\n self.parent_path = os.path.dirname(self.current_dir)\n\n #需要传入文件夹的名字和Excel名字#\n def readExcel(self,fileName,excelName):\n path=self.parent_path+'\\\\testFile'+'\\\\'+fileName+'\\\\'+excelName+'.xls'\n excel=xlrd.open_workbook(path)\n sheet=excel.sheets()[0]\n cls=[]\n nrows=int(sheet.nrows)\n i=1\n while i y.shape = 12dim\ndef function(y, x, m):\n out = np.zeros(y.shape)\n for idx in np.arange(0, len(y), 4):\n # 0 ist x_0\n # 1 ist y_0\n # 2 ist vx_0\n # 3 ist vy_0\n # dr/dt = v\n out[idx] = y[idx + 2] # \"f(x) = vx\"\n out[idx + 1] = y[idx + 3] # \"f(y) = vy\"\n # loop to sum over all forces\n for jdx in np.arange(0, len(y), 4):\n if idx != jdx:\n # dv/dt = a\n out[idx + 2] = out[idx + 2] + G * m[int(jdx / 4)] * (y[jdx] - y[idx]) / (\n (y[jdx] - y[idx]) ** 2 + (y[jdx + 1] - y[idx + 1]) ** 2) ** 1.5\n out[idx + 3] = out[idx + 3] + G * m[int(jdx / 4)] * (y[jdx + 1] - y[idx + 1]) / (\n (y[jdx] - y[idx]) ** 2 + (y[jdx + 1] - y[idx + 1]) ** 2) ** 1.5\n\n return out\n\n\ndef setup(stepsize, iterations, init_pos, masses):\n y, x = init_pos\n y_new, x_new = rk4(y, x, function, stepsize, iterations, {\"m\": masses})\n\n out_x0 = np.zeros(x_new.shape)\n out_y0 = np.zeros(x_new.shape)\n out_x1 = np.zeros(x_new.shape)\n out_y1 = np.zeros(x_new.shape)\n out_x2 = np.zeros(x_new.shape)\n out_y2 = np.zeros(x_new.shape)\n velocities = np.ndarray((y_new.shape[0], int(y_new.shape[1] / 2)))\n\n for idx, i in enumerate(y_new):\n out_x0[idx] = i[0]\n out_y0[idx] = i[1]\n out_x1[idx] = i[4]\n out_y1[idx] = i[5]\n out_x2[idx] = i[8]\n out_y2[idx] = i[9]\n velocities[idx][0] = i[2]\n velocities[idx][1] = i[3]\n velocities[idx][2] = i[6]\n velocities[idx][3] = i[7]\n velocities[idx][4] = i[10]\n velocities[idx][5] = i[11]\n\n return (out_x0, out_y0), (out_x1, out_y1), (out_x2, out_y2), x_new, velocities\n\n\ndef distance(a, b):\n ax = a[0]\n ay = a[1]\n bx = b[0]\n by = b[1]\n out = np.zeros(len(ax))\n for i in range(len(ax)):\n out[i] = np.sqrt((bx[i] - ax[i]) ** 2 + (by[i] - ay[i]) ** 2)\n return out\n\n\ndef energy_calc(a, b, c, masses, veloc):\n potential = - G * ((masses[0] * masses[1]) / distance(a, b) + (masses[1] * masses[2]) / distance(b, c) + (\n masses[2] * masses[0]) / distance(c, a))\n veloc = np.square(veloc)\n veloc = veloc.T\n vel_energy = ((masses[0] * (veloc[0] + veloc[1]) + masses[1] * (veloc[2] + veloc[3]) + masses[2] * (\n veloc[4] + veloc[5]))) / 2\n return np.absolute(vel_energy + potential)\n\n\n# Vars\nG = 1\nM = 1\nx0 = np.array([0]) # time begins at t = 0\n\n# init\nh = 0.01\nn = 1400\n\ny0 = np.array([-0.97000436, 0.24308753])\nv0 = np.array([-0.46620368, -0.43236573])\ny1 = np.array([0.97000436, -0.24308753])\nv1 = np.array([-0.46620368, -0.43236573])\ny2 = np.array([0., 0.])\nv2 = np.array([0.93240737, 0.86473146])\n\nmass = np.array([M, M, M])\n\nliste = (y0, v0, y1, v1, y2, v2)\n\nyall = np.zeros(12)\n\nfor idx, i in enumerate(liste):\n for kdx, k in enumerate(i):\n yall[idx * len(i) + kdx] = k\n\ninput_vec = (yall, x0)\n\n# endInit\n\na, b, c, _, _ = setup(h, n, input_vec, mass)\nd, e, f, _, _ = setup(h * 0.1, n, input_vec, mass)\n\n# x (here the time) is not needed for the orbits only for the length of the array\n\nplt.figure(figsize=(16, 8))\nplt.subplot(121)\nplt.title(\"Overlayed h = 0.1\")\nplt.plot(a[0], a[1], label=\"m1\")\nplt.plot(b[0], b[1], label=\"m2\")\nplt.plot(c[0], c[1], label=\"m3\")\nplt.plot(-0.97000436, 0.24308753, \".\", color=\"black\")\nplt.plot(0.97000436, -0.24308753, \".\", color=\"black\")\nplt.plot(0, 0, \".\", color=\"black\")\nplt.subplot(122)\nplt.title(\"Overlayed h = 0.001\")\nplt.plot(d[0], d[1], label=\"m1\")\nplt.plot(e[0], e[1], label=\"m2\")\nplt.plot(f[0], f[1], label=\"m3\")\nplt.plot(-0.97000436, 0.24308753, \".\", color=\"black\")\nplt.plot(0.97000436, -0.24308753, \".\", color=\"black\")\nplt.plot(0, 0, \".\", color=\"black\")\n\nplt.legend(fancybox=True)\nplt.tight_layout()\n\nplt.savefig(\"fig2a.png\")\n\n# b)######################################################################################################################\n\n# Vars\nh = 0.0001\nn = 50000\n\n# Init\ny0 = np.array([3., -1.])\nv0 = np.array([-0., 0.])\ny1 = np.array([-1., 2.])\nv1 = np.array([0., 0.])\ny2 = np.array([-1., -1.])\nv2 = np.array([0., 0.])\n\nmass = np.array([3 * M, 4 * M, 5 * M])\n\nliste = (y0, v0, y1, v1, y2, v2)\n\nfor idx, i in enumerate(liste):\n for kdx, k in enumerate(i):\n yall[idx * len(i) + kdx] = k\n\ninput_vec = (yall, x0)\n# endInit\n\na, b, c, x, vel = setup(h, n, input_vec, mass)\n\nenergy = energy_calc(a, b, c, mass, vel)\n\nenergy = energy - energy[0]\n\nplt.figure(figsize=(24, 8))\nplt.subplot(131)\nplt.title(\"Overlayed h = 0.0001\")\nplt.plot(a[0], a[1], label=\"m1 = 3\")\nplt.plot(b[0], b[1], label=\"m2 = 4\")\nplt.plot(c[0], c[1], label=\"m3 = 5\")\nplt.plot(-1, -1, \".\", color=\"black\")\nplt.plot(-1, 2, \".\", color=\"black\")\nplt.plot(3, -1, \".\", color=\"black\")\nplt.legend(fancybox=True)\nplt.tight_layout()\nplt.subplot(132)\nplt.title(\"Distance between the planets\")\nplt.semilogy(x, distance(a, b), label=\"m1 and m2\")\nplt.semilogy(x, distance(b, c), label=\"m2 and m3\")\nplt.semilogy(x, distance(c, a), label=\"m3 and m1\")\nplt.legend(fancybox=True)\nplt.tight_layout()\nplt.subplot(133)\nplt.title(\"Energy Error\")\nplt.plot(x, energy)\nplt.tight_layout()\n\nplt.savefig(\"fig2b.png\")\n\n# c)######################################################################################################################\n\n# Vars\nh = 0.001\nn = 2830\n\n# Init\ny0 = np.array([3., -1.])\nv0 = np.array([-0.8, 0.])\ny1 = np.array([-1., 2.])\nv1 = np.array([0., 0.])\ny2 = np.array([-1., -1.])\nv2 = np.array([0., 0.])\n\nmass = np.array([3 * M, 4 * M, 5 * M])\n\nliste = (y0, v0, y1, v1, y2, v2)\n\nfor idx, i in enumerate(liste):\n for kdx, k in enumerate(i):\n yall[idx * len(i) + kdx] = k\n\ninput_vec = (yall, x0)\n\n# endInit\n\na, b, c, _, _ = setup(h, n, input_vec, mass)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(111)\nplt.title(\"Overlayed\")\nplt.plot(a[0], a[1], label=\"m1 = 3 with vel_x_init = -0.8\")\nplt.plot(b[0], b[1], label=\"m2 = 4\")\nplt.plot(c[0], c[1], label=\"m3 = 5\")\nplt.plot(-1, -1, \".\", color=\"black\")\nplt.plot(-1, 2, \".\", color=\"black\")\nplt.plot(3, -1, \".\", color=\"black\")\n\nplt.legend(fancybox=True)\nplt.tight_layout()\n\nplt.savefig(\"fig2c.png\")\n","sub_path":"three_body_problem/Sheet2.py","file_name":"Sheet2.py","file_ext":"py","file_size_in_byte":6301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"581288012","text":"\n\nimport random\nimport numpy as np\n\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\n\n#1. Défintition des paramètres d'entrés\n#MPC = np.array([[0,0,0,0,1],\n# [0,0,1,0,0],\n# [1,0,0,0,0],\n# [0,1,0,0,0],\n# [0,0,0,1,0],\n# [1,0,0,0,0]])\n\nMPCn1 = np.array([[0,0,0,0,1],\n [1,0,0,0,0],\n [0,1,0,0,0],\n [1,0,0,0,0],\n [0,0,1,0,0],\n [0,0,0,1,0]])\n\n\nMPTS=np.array([[1, 0, 0, 0],\n [1, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 0, 1],\n [0, 0, 0, 1]])\n\nR1=np.array([[50,15,30,5],\n [15,15,25,5],\n [15,15,25,5],\n [25,10,25,5],\n [15,10,25,5]])\n\nR2=np.array([[50,100,100,95,95],\n [100,30,70,100,100],\n [100,50,50,100,100],\n [100,80,80,80,80],\n [100,95,95,95,95]])\n\neta=np.array([4,8,7,13,3.4])\nsurface=np.array([10,10,10,10,10,10])\nprixVenteCulture=np.array([350,200,150,150,400])\ncoutProdCulture=np.array([400,600,400,1200,300])\n\n#2. Défintition paramètres algo évolutionnaire\n\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\ncreator.create(\"Individual\", list, fitness=creator.FitnessMax)\n\ntoolbox = base.Toolbox()\n\n# Attribute generator\n# define 'attr_bool' to be an attribute ('gene')\n# which corresponds to integers sampled uniformly\n# from the range [0,1] (i.e. 0 or 1 with equal\n# probability)\ntoolbox.register(\"attr_int\", np.random.randint, 2, size=(6,5))\n\n# Structure initializers\n# define 'individual' to be an individual\n# consisting of 100 'attr_bool' elements ('genes')\ntoolbox.register(\"individual\", tools.initRepeat, creator.Individual,\n toolbox.attr_int,1)\n\n# define the population to be a list of individuals\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\n\n# the goal ('fitness') function to be maximized\ndef evalOneMax(individual):\n print(\"individual\")\n print(individual)\n MPC = individual[0]\n eta1 = np.matmul(MPC, eta)\n v = np.zeros(6)\n\n for i in range(len(MPC)):\n v = v + np.matmul(np.matmul(MPC[i], R1), np.transpose(MPTS[i])) * np.identity(6)[i]\n\n eta2 = (np.ones(6) - v / 100)\n\n u = np.zeros(6)\n for i in range(6):\n u = u + np.matmul(np.matmul(MPC[i], R2), np.transpose(MPCn1[i])) * np.identity(6)[i]\n\n eta3 = (u / 100)\n\n marBruteParcelle = (surface * (eta1 * eta2 * eta3 * np.matmul(MPC, prixVenteCulture) - np.matmul(MPC, coutProdCulture)))\n\n return sum(marBruteParcelle),\n\n\n# ----------\n# Operator registration\n# ----------\n# register the goal / fitness function\ntoolbox.register(\"evaluate\", evalOneMax)\n\n# register the crossover operator\ntoolbox.register(\"mate\", tools.cxTwoPoint)\n\n# register a mutation operator with a probability to\n# flip each attribute/gene of 0.05\ntoolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.05)\n\n# operator for selecting individuals for breeding the next\n# generation: each individual of the current generation\n# is replaced by the 'fittest' (best) of three individuals\n# drawn randomly from the current generation.\ntoolbox.register(\"select\", tools.selTournament, tournsize=3)\n\n\n# ----------\n\ndef main():\n\n\n\n random.seed(64)\n\n # create an initial population of 300 individuals (where\n # each individual is a list of integers)\n pop = toolbox.population(n=10)\n print(\"pop\")\n print(pop)\n\n # CXPB is the probability with which two individuals\n # are crossed\n #\n # MUTPB is the probability for mutating an individual\n CXPB, MUTPB = 0.5, 0.2\n\n print(\"Start of evolution\")\n\n # Evaluate the entire population\n fitnesses = list(map(toolbox.evaluate, pop))\n print('###fitnesses###')\n print(fitnesses)\n for ind, fit in zip(pop, fitnesses):\n ind.fitness.values = fit\n\n print(\" Evaluated %i individuals\" % len(pop))\n\n # Extracting all the fitnesses of\n print(\"fits\")\n fits = [ind.fitness.values[0] for ind in pop]\n print(fits)\n print('max')\n print(max(fits))\n\n # Variable keeping track of the number of generations\n g = 0\n\n # Begin the evolution\n while max(fits) < 100 and g < 1000:\n # A new generation\n g = g + 1\n print(\"-- Generation %i --\" % g)\n\n # Select the next generation individuals\n offspring = toolbox.select(pop, len(pop))\n # Clone the selected individuals\n offspring = list(map(toolbox.clone, offspring))\n\n # Apply crossover and mutation on the offspring\n for child1, child2 in zip(offspring[::2], offspring[1::2]):\n\n # cross two individuals with probability CXPB\n if random.random() < CXPB:\n toolbox.mate(child1, child2)\n\n # fitness values of the children\n # must be recalculated later\n del child1.fitness.values\n del child2.fitness.values\n\n for mutant in offspring:\n\n # mutate an individual with probability MUTPB\n if random.random() < MUTPB:\n toolbox.mutate(mutant)\n del mutant.fitness.values\n\n # Evaluate the individuals with an invalid fitness\n invalid_ind = [ind for ind in offspring if not ind.fitness.valid]\n fitnesses = map(toolbox.evaluate, invalid_ind)\n for ind, fit in zip(invalid_ind, fitnesses):\n ind.fitness.values = fit\n\n print(\" Evaluated %i individuals\" % len(invalid_ind))\n\n # The population is entirely replaced by the offspring\n pop[:] = offspring\n\n # Gather all the fitnesses in one list and print the stats\n fits = [ind.fitness.values[0] for ind in pop]\n\n length = len(pop)\n mean = sum(fits) / length\n sum2 = sum(x * x for x in fits)\n std = abs(sum2 / length - mean ** 2) ** 0.5\n\n print(\" Min %s\" % min(fits))\n print(\" Max %s\" % max(fits))\n print(\" Avg %s\" % mean)\n print(\" Std %s\" % std)\n\n print(\"-- End of (successful) evolution --\")\n\n best_ind = tools.selBest(pop, 1)[0]\n print(\"Best individual is %s, %s\" % (best_ind, best_ind.fitness.values))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"test_DEAP.py","file_name":"test_DEAP.py","file_ext":"py","file_size_in_byte":6396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"449635254","text":"from rest_framework.views import exception_handler\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR\n\n\ndef custom_exception_handler(exc, context):\n response = exception_handler(exc, context)\n\n if response is not None:\n status = response.status_code\n\n if not isinstance(response.data, str) and len(response.data) != 0:\n\n if isinstance(response.data, dict):\n if response.data.get('detail', False):\n response = response.data['detail']\n elif response is not None:\n status = response.data[0].code\n response = response.data[0]\n\n else:\n status = HTTP_500_INTERNAL_SERVER_ERROR\n\n return Response(response, status=status)\n","sub_path":"Python/Ebiblio/ebiblio-api-master-0d904d7530c4a0b59ae1278c816f9c18f1f452dc/DjangoLibraryRest/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"354118521","text":"#!coding=utf-8\n\nimport logging\nimport inspect\nimport functools\nimport multiprocessing\n\n\ndef _worker(input, output):\n for evt in iter(input.get, 'STOP'):\n cb = evt.get('handler', None)\n if not cb: continue\n\n args = evt.get('args', [])\n kwds = evt.get('kwds', {})\n\n _args = set(inspect.getargspec(cb).args)\n if '_output' in _args:\n kwds['_output'] = output\n\n if '_input' in _args:\n kwds['_input'] = input\n\n rs = cb(*args, **kwds)\n if rs is None: continue\n\n output.put(rs)\n\n\ndef mt_run(cb, workers=None):\n jobs, workers = [], workers or max(1, multiprocessing.cpu_count() - 1)\n\n # Create queues\n task_queue = multiprocessing.Queue()\n done_queue = multiprocessing.Queue()\n\n for _ in range(workers):\n j = multiprocessing.Process(target=_worker, args=(task_queue, done_queue,))\n jobs.append(j)\n j.start()\n\n cb(done_queue, task_queue)\n [e.join() for e in jobs]\n\n\ndef default_num():\n return max(1, multiprocessing.cpu_count() - 1)\n\n\n# -- utils functions for h5f file ------------------------------\ndef _dump(input, output, limit):\n total = limit\n while limit > 0:\n flag, e = input.get()\n logging.debug('%s' % e)\n if not flag: continue\n limit -= 1\n\n for _ in range(total):\n output.put('STOP')\n\n\ndef mt_process(cb, cbkwds={}, workers=None):\n workers = workers or default_num() # workers: cpu\n\n def _cb(input, output, workers=None):\n for tid in range(workers):\n _kwds = {'_tid': tid, }\n _kwds.update(cbkwds)\n\n output.put({\n 'handler': cb,\n 'args': (workers,),\n 'kwds': _kwds,\n })\n _dump(input, output, workers)\n\n mt_run(functools.partial(_cb, workers=workers), workers=workers)\n","sub_path":"xyz/util/mt.py","file_name":"mt.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"480246960","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport math\nimport yaml\nimport argparse\nimport importlib\n\nfrom collections import OrderedDict\n\n\ndef load_plugins(modules):\n \"\"\"\n load the plugins\n :param modules: string of one or more modules\n :return: ordereddict of {plugin_name: plugin_object}\n \"\"\"\n\n plugins = OrderedDict()\n if modules:\n for module in modules:\n module = os.path.realpath(module)\n if os.path.isfile(module):\n mod_dir = os.path.dirname(module)\n mod_name = os.path.splitext(os.path.basename(module))[0]\n sys.path.insert(0, mod_dir)\n plugin = importlib.import_module(mod_name)\n sys.path.pop(0)\n plugins[mod_name] = plugin\n else:\n print(\"error: {0} plugin not found!\".format(module))\n if not plugins:\n sys.exit(\"error: No plugins found!\")\n return plugins\n\n\ndef calculate_angle(planets_config, time):\n \"\"\"\n calculate the angle in degrees\n :param planets_config: list of individual planet configs\n :param time: time\n :return: ordereddict of {planet_name: angle out of 360 degrees}\n \"\"\"\n planets = OrderedDict()\n for planet_config in planets_config:\n var_angle = 2 * math.pi * time / planet_config['period']\n planets[planet_config['name']] = math.degrees(planet_config['theta'] +\n var_angle) % 360\n return planets\n\n\ndef main():\n\n # define cli\n parser = argparse.ArgumentParser(description=\"A command line application \"\n \"to print out planets that \"\n \"are aligned.\")\n parser.add_argument(\"--config\", action=\"store\",\n required=True,\n help=\"an yaml configuration file\")\n parser.add_argument(\"--plugins\", action=\"store\",\n required=True,\n nargs=\"+\",\n help=\"load one or more plugins\")\n parser.add_argument(\"--time\", action=\"store\",\n required=True,\n type=float,\n help=\"check alignment at time t\")\n args = parser.parse_args()\n\n # read config file\n try:\n with open(args.config) as stream:\n config = yaml.safe_load(stream)\n except Exception as exception:\n sys.exit(\"error: {}\".format(exception))\n\n # calculate angle from the planetory configuration\n planets_config = config.get('system')\n planets = calculate_angle(planets_config, args.time)\n\n # load plugins\n plugins = load_plugins(args.plugins)\n\n # check and print alignment\n results = OrderedDict()\n for name, plugin in plugins.items():\n results[name] = plugin.get_alignment(planets)\n for plugin, alignments in results.items():\n for alignment in alignments:\n print(\"{0}: {1}\".format(plugin, \", \".join(alignment)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"alignment/alignment.py","file_name":"alignment.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"200140157","text":"import pandas as pd\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import train_test_split, cross_validate, cross_val_score\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\n\ndiabetes = pd.read_csv(\"diabetes.csv\", delimiter=',')\n\n# Divide os dados em dois conjuntos: Atributos e Classes\nattributes = diabetes.drop('class', axis=1)\nclasses = diabetes['class']\n\n# Dividir os dados aleatoriamente em conjunto para aprendizado e conjunto para testes\nX_train, X_test, y_train, y_test = train_test_split(attributes, classes, test_size=0.20)\n\n# Treinar o modelo\nclassifier_logit = LogisticRegression(solver='lbfgs', max_iter=500)\nclassifier_decision_tree = DecisionTreeClassifier()\n\nclassifier_logit.fit(X_train, y_train)\nclassifier_decision_tree.fit(X_train, y_train)\n\n# -----------------------------------------------------\n# Cross validation - resolve a aleatoriedade do split do dataset\n# 'scores' retorna o precision para cada iteração executada\n# cv = número de iterações\n\n# Using cross_val_score\n# scores = cross_val_score(classifier, X_test, y_test, cv=10)\n\n# Utilizo assim a média das precisions para utilizar como referência.\n# Isso pois o split é feito para 20% dos valores para teste - que nem sempre\n# são os mesmos - gerando precisions diferentes para cada iteraçao rodada\n# Logo, cross validation faz esse papel de obteção da precisão média\n# print('Precisão média:', scores.mean())\n\n# Using cross_validate - dá mais detalhes (tempo de execução, etc)\n# scores = cross_validate(classifier, X_test, y_test, cv=10)\n\n# -----------------------------------------------------\n\n#Aplicar o modelo gerado sobre os dados separados para testes\ny_pred_logit = classifier_logit.predict(X_test)\ny_pred_decision_tree = classifier_decision_tree.predict(X_test)\n\n#Estimativa de probabilidade para cada classe ao invés de prever o resultado\nprobabilidades = classifier_logit.predict_proba(X_test)\nprint(probabilidades)\n\n#Avaliar o modelo: Acurácia e matriz de contingência\ncm_logit = confusion_matrix(y_test, y_pred_logit)\ncm_decision_tree = confusion_matrix(y_test, y_pred_decision_tree)\n# report = classification_report(y_test, y_pred_logit)\n\nespecificidade = cm_logit[0][0] / (cm_logit[0][0] + cm_logit[0][1])\nsensibilidade = cm_logit[1][1] / (cm_logit[1][1] + cm_logit[1][0])\nprint('especificidade (logit):', especificidade)\nprint('sensibilidade (logit): ', sensibilidade)\n\nespecificidade_decision_tree = cm_decision_tree[0][0] / (cm_decision_tree[0][0] + cm_decision_tree[0][1])\nsensibilidade_decision_tree = cm_decision_tree[1][1] / (cm_decision_tree[1][1] + cm_decision_tree[1][0])\nprint('especificidade (decision_tree):', especificidade_decision_tree)\nprint('sensibilidade (decision_tree): ', sensibilidade_decision_tree)\n\n# #Salvar o modelo para uso posterior\njoblib.dump(classifier_logit, 'diabetes_model_logit.joblib')\njoblib.dump(classifier_decision_tree, 'diabetes_model_decision_tree.joblib')\n\n\n","sub_path":"entrega2/Diabetes/diabetes_builder.py","file_name":"diabetes_builder.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"122254401","text":"import pdfkit\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nfrom flask import render_template\nimport os\n\nclass VoiceForm:\n\n config = pdfkit.configuration(wkhtmltopdf=os.environ.get(\"WKHTMLTOPDF_PATH\")) # add path to wkhtmlpdf\n sender_address = os.environ.get('SENDER_EMAIL')\n sender_pass = os.environ.get('SENDER_PASSWORD')\n\n def __init__(self):\n print(\"\")\n\n def generatePDF(self,form):\n path = './voiceforms/' + form['email'] + '.pdf'\n rendered = render_template('pdf_template.html',form=form)\n pdfkit.from_string(rendered,path,configuration=self.__class__.config) \n return path\n\n def sendEmail(self,reciever_address,attach_file_name):\n message = MIMEMultipart()\n message['From'] = self.__class__.sender_address\n message['To'] = reciever_address\n message['Subject'] = 'A copy of your voice form response.'\n mail_content = \"\"\"\n This is a copy of your response form generated by our App.\n \"\"\"\n message.attach(MIMEText(mail_content, 'plain'))\n attach_file = open(attach_file_name, 'rb') \n payload = MIMEBase('application', 'octate-stream')\n payload.set_payload((attach_file).read())\n encoders.encode_base64(payload) \n payload.add_header('Content-Disposition', 'attachment; filename=\"%s.pdf\"' % reciever_address)\n message.attach(payload)\n session = smtplib.SMTP('smtp.gmail.com', 587) \n session.starttls() \n session.login(self.__class__.sender_address, self.__class__.sender_pass) \n text = message.as_string()\n session.sendmail(self.__class__.sender_address, reciever_address, text)\n session.quit()\n print('Mail Sent')","sub_path":"VoiceForm.py","file_name":"VoiceForm.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"478084584","text":"import pygame\n\n\ndef runListener(displayScreen):\n\tdirectionDict = {\"up\":False, \"down\":False, \"left\":False, \"right\":False}\n\tfor e in pygame.event.get():\n\t\t\n\t\tif e.type == pygame.QUIT:\n\t\t\traise SystemExit\n\t\t\t\n\t\tif e.type == pygame.KEYDOWN:\n\t\t\tdirectionDict = keyDownListener(e, directionDict)\n\t\t\tif e.key == pygame.K_1:\n\t\t\t\tdisplayScreen.full_screen()\n\t\t\tif e.key == pygame.K_2:\n\t\t\t\tdisplayScreen.back_to_window()\n\t\t\t\t\n\t\tif e.type == pygame.KEYUP:\n\t\t\tdirectionDict = keyUpListener(e, directionDict)\n\t\t\t\n\treturn directionDict\n\ndef keyDownListener(event, directionDict):\n\tif event.key == pygame.K_ESCAPE:\n\t\traise SystemExit\n\tif event.key == pygame.K_UP:\n\t\tdirectionDict[\"up\"] = True\t\t\t\t\t \n\tif event.key == pygame.K_DOWN:\n\t\tdirectionDict[\"down\"] = True\t\t\t\t\t \n\tif event.key == pygame.K_LEFT:\n\t\tdirectionDict[\"left\"] = True\t\t\t\t\t \n\tif event.key == pygame.K_RIGHT:\n\t\tdirectionDict[\"right\"] = True\n\t\t\n\treturn directionDict\n\t\ndef keyUpListener(event, directionDict):\n\tif e.key == pygame.K_UP:\n\t\tdirectionDict[\"up\"] = False\n\tif e.key == pygame.K_DOWN:\n\t\tdirectionDict[\"down\"] = False\t\t\t\t\t \n\tif e.key == pygame.K_LEFT:\n\t\tdirectionDict[\"left\"] = False\n\tif e.key == pygame.K_RIGHT:\n\t\tdirectionDict[\"right\"] = False\n\t\t\n\treturn directionDict","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"622865246","text":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Conv1D\nfrom tensorflow.keras.layers import MaxPooling1D\n\nclass FCNN:\n\t\"\"\"docstring for CNN\"\"\"\n\tdef __init__(self, trainFeatures, trainLabels, validateFeatures, validateLabels, config={}):\n\t\tself.trainFeatures = trainFeatures\n\t\tself.trainLabels = trainLabels\n\t\tself.validateFeatures = validateFeatures\n\t\tself.validateLabels = validateLabels\n\t\tself.config = config\n\n\tdef trainModel(self):\n\t\tx_train = self.trainFeatures\n\t\ty_train = self.trainLabels\n\t\tx_validate = self.validateFeatures\n\t\ty_validate = self.validateLabels\n\t\tn_timesteps, n_outputs = x_train.shape[1], y_train.shape[1]\n\t\tbatch_size = 8\n\n\t\tmodel = Sequential()\n\t\tfirstTime = True\n\t\tfor count in self.config[\"layers\"]:\n\t\t\tif firstTime:\n\t\t\t\tmodel.add(Dense(count, input_dim=n_timesteps, activation='relu'))\n\t\t\t\tfirstTime = False\n\t\t\telse:\n\t\t\t\tmodel.add(Dense(count, activation='relu'))\n\t\t\t# model.add(Dropout(.4))\n\t\t# model.add(Dense(20, input_dim=9, activation='relu'))\n\t\t# model.add(Dense(5, activation='relu'))\n\t\tmodel.add(Dense(n_outputs, activation='softmax'))\n\n\t\t# model = Sequential()\n\t\t# # model.add(Conv1D(filters=10, kernel_size=5, activation=tf.nn.relu6, kernel_regularizer=tf.keras.regularizers.l2(l=0.01), input_shape=(n_timesteps,n_features)))\n\t\t# model.add(Conv1D(filters=10, kernel_size=5, activation=tf.nn.relu6, input_shape=(n_timesteps,n_features)))\n\t\t# model.add(MaxPooling1D(pool_size=2))\n\t\t# model.add(Conv1D(filters=20, kernel_size=3, activation=tf.nn.relu6))\n\t\t# model.add(MaxPooling1D(pool_size=4))\n\t\t# model.add(Flatten())\n\t\t# # model.add(Dense(10, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(l=0.01)))\n\t\t# model.add(Dense(10, activation='relu'))\n\t\t# model.add(Dense(n_outputs, activation='softmax'))\n\t\tmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\t\tmodel.fit(x_train, y_train, validation_data=(x_validate, y_validate), epochs=self.config[\"epochs\"], batch_size=self.config[\"batch_size\"], verbose=self.config[\"verbose\"])\n\t\treturn model\n\t\t","sub_path":"FinalEvaluation/FCNN.py","file_name":"FCNN.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"130667185","text":"from settings import *\nimport xlsxwriter\nimport smartsheet\nfrom build_coverage_dict import *\nfrom build_sku_dict import *\nfrom build_bookings_dict import *\nfrom build_renewals_dict import *\nfrom cleanup_orders import *\nfrom find_team import *\nfrom push_xls_to_ss import *\n\n\n#\n# Get settings for file locations and names\n#\nhome = app['HOME']\nworking_dir = app['WORKING_DIR']\nbookings_file = app['BOOKINGS'] # Master bookings has 9958 rows as of 12-15-18\nrenewals_file = app['RENEWALS']\npath_to_files = home +'\\\\' + working_dir + '\\\\'\npath_to_renewals = path_to_files + renewals_file\npath_to_bookings = path_to_files + bookings_file\n\n\n# Go to Smartsheets and build these two dicts to use reference lookups\n# team_dict: {'sales_levels 1-6':[('PSS','TSA')]}\n# sku_dict: {sku : [sku_type, sku_description]}\nteam_dict = build_coverage_dict()\nsku_dict = build_sku_dict()\n\n#\n# Open up the renewals and bookings excel workbooks\n#\nwb_renewals = xlrd.open_workbook(path_to_renewals)\nsheet_renewals = wb_renewals.sheet_by_index(0)\n\nwb_bookings = xlrd.open_workbook(path_to_bookings)\nsheet_bookings = wb_bookings.sheet_by_index(0)\n\n# From the renewals file get renewal dates for lookup\n# {erp_customer_name:[renewal_date,monthly_charge]}\nrenewals_dict = build_renewals_dict(wb_renewals,sheet_renewals)\n\n# From the current up to date bookings file build a simple dict\n# that describes the format of the output file we are creating\n# and the columns we need to add (ie PSS, TSA, Renewal Dates)\nbookings_dict = build_bookings_dict(path_to_bookings,sheet_bookings)\n\n#\n# init a bunch a variable we need for the main loop\n#\ncustomer_list = []\norder_top_row = []\norder_rows = []\norder_row = []\nsku_col_num = -1\ncol_pss_num = -1\ncol_tsa_num = -1\n\n# Build the column titles top row\n# Also grab\n# 1. sku column number\n# 2. PSS and TSA column numbers\nfor idx, val in enumerate(bookings_dict['col_info']):\n col_name = val[0]\n col_num = val[1]\n order_top_row.append(val[0])\n if col_name == 'Bundle Product ID':\n sku_col_num = col_num\n if col_name == 'PSS':\n col_pss_num = idx\n if col_name == 'TSA':\n col_tsa_num = idx\n if col_name == 'Product Type':\n col_prod_type_num = idx\n if col_name == 'Sensor Count':\n col_sensor_cnt_num = idx\n\norder_row = order_top_row\norder_rows.append(order_row)\n\n#\n# Main loop of bookings excel data\n#\nfor i in range(sheet_bookings.nrows):\n\n # Is this SKU of interest ?\n sku = sheet_bookings.cell_value(i,sku_col_num)\n\n if sku in sku_dict :\n # Let's make a row for this order\n # Since it has an \"interesting\" sku\n order_row = []\n sales_level = ''\n sales_level_cntr = 0\n sku_type = sku_dict[sku][0]\n sku_desc = sku_dict[sku][1]\n sku_sensor_cnt = sku_dict[sku][2]\n\n # Walk across the bookings_dict columns\n # to build this output row cell by cell\n for val in bookings_dict['col_info']:\n col_name = val[0]\n col_idx = val[1]\n\n # Capture both of the Customer names\n if col_name == 'ERP End Customer Name':\n customer_name_erp = sheet_bookings.cell_value(i, col_idx)\n if col_name == 'End Customer Global Ultimate Name':\n customer_name_end = sheet_bookings.cell_value(i, col_idx)\n\n # If this is a 'Sales Level X' column then\n # Capture it's value for lookup\n if col_name[:-2] == 'Sales Level':\n sales_level = sales_level + sheet_bookings.cell_value(i, col_idx) +','\n sales_level_cntr += 1\n if sales_level_cntr == 6:\n # We have collected all 6 sales levels\n # Now go to find_team to do the lookup\n sales_level = sales_level[:-1]\n sales_team = find_team(team_dict,sales_level)\n pss = sales_team[0]\n tsa = sales_team[1]\n order_row[col_pss_num] = pss\n order_row[col_tsa_num] = tsa\n\n if col_idx != -1:\n # OK we have a cell we need so grab it\n order_row.append(sheet_bookings.cell_value(i, col_idx))\n elif col_name == 'Product Description':\n # Add in the Product Description\n order_row.append(sku_desc)\n elif col_name == 'Product Type':\n # Add in the Product Type\n order_row.append(sku_type)\n elif col_name == 'Sensor Count':\n # Add in the Sensor Count\n order_row.append(sku_sensor_cnt)\n elif col_name == 'Renewal Date(s)':\n # Add in the Renewal Date if there is one\n # Else just add a blank string\n if customer_name_erp in renewals_dict:\n renewal_date = renewals_dict[customer_name_erp]\n order_row.append(renewal_date[0])\n else:\n order_row.append('')\n else:\n # this cell is assigned a -1 in the bookings_dict\n # so assign a blank as a placeholder for now\n order_row.append('')\n\n # Done with all the columns in this row\n # Log this row for BOTH customer names and orders\n # Go to next row of the raw bookings data\n customer_list.append((customer_name_erp, customer_name_end))\n order_rows.append(order_row)\n\n#\n# End\n#\n\n# OK we now have a full list (order_rows) of just the SKUs we are interested in\n# As determined by the sku_dict\n\n# Now we build a Customer Summary/Detail\n# Let's organize as this\n# order_dict: {cust_name:[[order1],[order2],[orderN]]}\norder_dict = {}\norders = []\norder = []\nx = 0\nfor order_row in order_rows:\n customer = order_row[0]\n if x==0:\n x += 1\n continue\n\n # Is this in the order dict ?\n if customer in order_dict:\n orders = []\n for order in order_dict[customer]:\n orders.append(order)\n\n orders.append(order_row)\n order_dict[customer] = orders\n else:\n orders = []\n orders.append(order_row)\n order_dict[customer]=orders\n\n\n# Create a simple customer_list list of tuples\n# Contains a full set of unique sorted customer names\n# customer_list = [(erp_customer_name,end_customer_ultimate), (CustA,CustA)]\ncustomer_list = set(customer_list)\n\n# Convert the SET to a LIST so we can sort it\ncustomer_list = list(customer_list)\n\n# Sort the LIST\ncustomer_list.sort(key=lambda tup: tup[0])\nprint('We have: ', len(customer_list), ' customers')\n\n\n# Clean up order_dict to remove:\n# 1. +/- zero sum orders\n# 2. zero revenue orders\norder_dict = cleanup_orders(customer_list,order_dict,order_top_row)\n\n#\n# Create a summary order file out of the order_dict\n#\nsummary_order_rows=[]\nsummary_order_rows.append(order_top_row)\nfor key,val in order_dict.items():\n for my_row in val:\n summary_order_rows.append(my_row)\n\n#\n# Write the Summary order Excel File\n# Includes only those \"Interesting\" SKU's that are non-zero sum\n#\nwb_file = path_to_files + app['XLS_ORDER_SUMMARY'] + app['AS_OF_DATE'] + '.xlsx'\nworkbook = xlsxwriter.Workbook(wb_file)\nworksheet = workbook.add_worksheet()\nfor this_row, my_val in enumerate(summary_order_rows):\n worksheet.write_row(this_row, 0, my_val)\nworkbook.close()\n# push_xls_to_ss(wb_file, app['XLS_ORDER_SUMMARY'])\n\n#\n# Write the Detailed order Excel File\n# Includes ALL \"Interesting\" SKU's\n#\nwb_file = path_to_files + app['XLS_ORDER_DETAIL'] + app['AS_OF_DATE'] + '.xlsx'\nworkbook = xlsxwriter.Workbook(wb_file)\nworksheet = workbook.add_worksheet()\nfor this_row, my_val in enumerate(order_rows):\n worksheet.write_row(this_row, 0, my_val)\nworkbook.close()\n# push_xls_to_ss(wb_file, app['XLS_ORDER_DETAIL'])\n\n#\n# Write TA Customer List to a local excel workbook\n#\n# Insert a header row before writing\ntop_row = ['erp_customer_name','end_customer_ultimate_name']\ncustomer_list.insert(0,top_row)\n\nwb_file = path_to_files + app['XLS_CUSTOMER'] + app['AS_OF_DATE'] + '.xlsx'\nworkbook = xlsxwriter.Workbook(wb_file)\nworksheet = workbook.add_worksheet()\nfor this_row, my_val in enumerate(customer_list):\n worksheet.write(this_row, 0, my_val[0])\n worksheet.write(this_row, 1, my_val[1])\nworkbook.close()\n# push_xls_to_ss(wb_file, app['XLS_CUSTOMER'])\n\nexit()","sub_path":"old_revs/process_bookings_file_r0.py","file_name":"process_bookings_file_r0.py","file_ext":"py","file_size_in_byte":8327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"423545032","text":"# ..................................................................\n# : Wind Down: Music, Movie, & Book Recs for your Psyche :\n# : B. Davis, A. M. Rahman, K. Noelsaint, G. Ren | hack@Brown '18 :\n# : winddown/utilFuns.py :\n# : -- Contains utility functions for parsing through JSON strings,:\n# : and large dictionaries\t\t\t\t\t\t\t\t\t :\n# :................................................................:\n\nimport operator\nfrom numpy import *\n\ndef flatten(orig):\n data = {}\n for c in orig['tree']['children']:\n if 'children' in c:\n for c2 in c['children']:\n if 'children' in c2:\n for c3 in c2['children']:\n if 'children' in c3:\n for c4 in c3['children']:\n if (c4['category'] == 'personality'):\n data[c4['id']] = c4['percentage']\n if 'children' not in c3:\n if (c3['category'] == 'personality'):\n data[c3['id']] = c3['percentage']\n return data\n\n\ndef smallest_diff(xs):\n return (min(diff(sort(xs))))\n\n\ndef smallest_distance(xs):\n new = sorted(xs.values())\n want=smallest_diff(new)\n print(want)\n main_want=[]\n acc=0\n while acc!=len(new) :\n if (-1*(new[acc]-new[acc+1]))==want:\n for name,number in xs.items():\n if number==new[acc] or number==new[acc+1]: \n main_want.append(name)\n return (main_want)\n else:\n pass\n acc+=1\n\n\ndef best3(xs):\n new_xs = reversed(sorted(xs.items(), key=operator.itemgetter(1)))\n acc=0\n new_dict2= {}\n for key,value in new_xs:\n if acc==0: \n biggest=key\n if acc<7 : \n new_dict2[key]=value\n else:\n break\n acc+=1\n print(biggest)\n del new_dict2[biggest]\n distance=smallest_distance(new_dict2)\n distance.append(biggest)\n return distance\n\n\ndef best6(xs):\n new_xs= reversed(sorted(xs.items(), key=operator.itemgetter(1)))\n acc=0\n new_dict2={}\n for key,value in new_xs:\n if acc<6 : \n new_dict2[key]=value\n else:\n break\n acc+=1\n return new_dict2.keys()\n\ndef sort_by_value(dict):\n sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))\n return sorted_dict\n\n\ndef locator ( dictionary, xs ):\n for key, value in dictionary.items():\n if value==xs:\n return key","sub_path":"utilFuns.py","file_name":"utilFuns.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"588282920","text":"import testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n '.molecule/ansible_inventory').get_hosts('all')\n\n\ndef test_service_running_and_enabled(Service):\n service = Service('omero-logmonitor')\n assert service.is_running\n assert service.is_enabled\n\n\ndef test_config_file(File):\n f = File('/opt/omero/logmonitor/omero-fenton/omero-fenton.cfg')\n assert f.contains('/opt/omero/server/OMERO.server/var/log/Blitz-0.log')\n assert f.contains('/opt/omero/web/OMERO.web/var/log/OMEROweb.log')\n","sub_path":"tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"29829577","text":"# %% [141. *Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)\n# 問題:ListNodeがサイクルかどうかを返す\n# 解法:1つずつ進むポインタと2つずつ進むポインタを使う\nclass Solution:\n def hasCycle(self, head: ListNode) -> bool:\n p = head\n q = p.next if p else p\n while q and q != p:\n p = p.next\n q = q.next\n q = q.next if q else q\n return q\n","sub_path":"codes_/0141_Linked_List_Cycle.py","file_name":"0141_Linked_List_Cycle.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"261536126","text":"from PySide2 import QtCore, QtWidgets\n\n\nclass HeroWidget(QtWidgets.QWidget):\n\n def __init__(self, hero=None, parent=None):\n \"\"\"Hero: \"\"\"\n super().__init__(parent)\n self.hero = hero\n self.tabWidget = QtWidgets.QTabWidget(self)\n self.graphicsWidget = HeroGraphicsWidget(hero)\n self.statsWidget = HeroStatsWidget(hero)\n # Add items to toolbox\n self.tabWidget.addTab(self.statsWidget, \"Stats\")\n self.tabWidget.addTab(self.graphicsWidget, \"Graphics\")\n self._setLayout()\n\n def _setLayout(self):\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self.tabWidget)\n self.setLayout(layout)\n\n def updateHero(self, hero=None):\n self.hero = hero\n self.statsWidget.updateHero(hero)\n self.graphicsWidget.updateHero(hero)\n print(hero.name)\n self.setWindowTitle(hero.name)\n\n\nclass HeroGraphicsWidget(QtWidgets.QWidget):\n\n def __init__(self, hero=None, parent=None):\n super().__init__(parent)\n \n self.hero = None\n self.iconScaleFactorSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal)\n self.iconScaleFactorSlider.setMinimum(10)\n self.iconScaleFactorSlider.setMaximum(30)\n self.iconScaleFactorSlider.setValue(20)\n\n self.iconScaleFactorSlider.setTickInterval(1)\n if hero:\n self.hero.graphicsGroup.iconPhoto.scaleIcon(self.iconScaleFactorSlider.value())\n self.hero.graphicsGroup.iconBoundry.scaleIcon(self.iconScaleFactorSlider.value())\n self.updateHero(hero)\n VBLayout = QtWidgets.QVBoxLayout(self)\n self.heroSliderName = QtWidgets.QLabel(\"Icon Size\")\n\n VBLayout.addWidget(self.heroSliderName)\n VBLayout.addWidget(self.iconScaleFactorSlider)\n\n def updateHero(self, hero=None):\n if self.hero:\n print(\"HERE ONE\")\n self.iconScaleFactorSlider.valueChanged.disconnect()\n if hero:\n print(\"HERE TWO\")\n self.iconScaleFactorSlider.valueChanged.connect(self.updateHeroIconScale)\n\n def updateHeroIconScale(self):\n self.hero.graphicsGroup.iconPhoto.scaleIcon(self.iconScaleFactorSlider.value())\n self.hero.graphicsGroup.iconBoundry.setScale(self.iconScaleFactorSlider.value()/5)\n\n\nclass HeroStatsWidget(QtWidgets.QWidget):\n\n def __init__(self, hero=None, parent=None):\n super().__init__(parent)\n self.healthLabel = QtWidgets.QLabel(\"Health: 0\")\n self.manaLabel = QtWidgets.QLabel(\"Mana: 0\")\n self.armorLabel = QtWidgets.QLabel(\"Armor: 0\")\n if hero:\n self.updateInfo(hero)\n VBLayout = QtWidgets.QVBoxLayout(self)\n VBLayout.addWidget(self.healthLabel)\n VBLayout.addWidget(self.manaLabel)\n VBLayout.addWidget(self.armorLabel)\n\n def updateHero(self, hero=None):\n if hero:\n health = hero.derivedStats[\"health\"]\n mana = hero.derivedStats[\"mana\"]\n armor = hero.derivedStats[\"armor\"]\n self.hero = hero\n self.healthLabel.setText(\"Health: {}\".format(round(health, 2)))\n self.manaLabel.setText(\"Mana: {}\".format(round(mana, 2)))\n self.armorLabel.setText(\"Armor: {}\".format(round(armor, 2)))\n","sub_path":"dota_vis/hero_widget.py","file_name":"hero_widget.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"293464463","text":"#!/usr/bin/python\n\n\"\"\"\nBookSearch\nModule: engn\nAuthor: Wael Al-Sallami\nDate: 2/10/2013\n\"\"\"\n\nclass Engine:\n \"\"\"The search engine\"\"\"\n\n store = None\n query = {}\n\n def __init__(self, store):\n \"\"\"Save a pointer to our indices\"\"\"\n self.store = store\n\n\n def search(self, query):\n \"\"\"Perform any search and return results\"\"\"\n self.query = query\n answers = wanswers = []\n answers = self.get_boolean_answers(answers)\n answers = self.get_phrase_answers(answers)\n wanswers = self.get_wildcard_answers(wanswers)\n if wanswers: answers.append(set.intersection(*wanswers))\n if answers: return set.intersection(*answers)\n\n\n def get_boolean_answers(self, answers):\n \"\"\"Get boolean answers and append them to the overall list of answers\"\"\"\n if self.query[\"bool\"]:\n boolean = self.boolean_search(self.query[\"bool\"])\n if boolean: answers.append(boolean)\n return answers\n\n\n def get_phrase_answers(self, answers):\n \"\"\"Get phrase answers and append them to the overall list of answers\"\"\"\n for phrase in self.query[\"phrase\"]:\n phrase = self.phrase_search(phrase)\n if phrase: answers.append(phrase)\n return answers\n\n\n def get_wildcard_answers(self, answers):\n \"\"\"perform wildcard search given a list of wildcards\"\"\"\n terms = []\n for q in self.query['wild']:\n kgrams = self.process_wildcard(q)\n subset = self.wildcard_terms(kgrams)\n if subset: terms.append(subset)\n\n for card in terms:\n subset = set()\n for t in card:\n results = set(self.store.index[t].keys())\n if not subset: subset = results.copy()\n subset |= results\n answers.append(subset)\n return answers\n\n\n def boolean_search(self, query):\n \"\"\"Perform a boolean search given a list of terms\"\"\"\n terms_docs = []\n for term in query:\n if term not in self.store.index: return\n docs = set()\n for doc in self.store.index[term].keys():\n docs.add(doc)\n terms_docs.append(docs)\n return set.intersection(*terms_docs)\n\n\n def positional_search(self, docs, terms):\n \"\"\"Perform a positional search given a list of docs and terms\"\"\"\n answers = set()\n for doc in docs:\n base_pos = self.store.index[terms[0]][doc]\n for pos in base_pos:\n found = True\n for i in range(1, len(terms)):\n if (pos + i) not in self.store.index[terms[i]][doc]:\n found = False\n break\n if found: answers.add(doc)\n return answers\n\n\n def phrase_search(self, query):\n \"\"\"Perform a phrase search\"\"\"\n terms = query.split()\n docs = self.boolean_search(terms)\n if docs:\n return self.positional_search(docs, terms)\n\n\n def wildcard_terms(self, kgrams):\n \"\"\"Given a list of kgrams, return union of their terms\"\"\"\n terms = set()\n for g in kgrams:\n inter = set()\n if g in self.store.kindex:\n inter = self.store.kindex[g]\n if not terms: terms = inter.copy()\n terms &= inter\n return terms\n\n\n def process_wildcard(self, cards):\n \"\"\"Generate a wildcard's kgrams\"\"\"\n middle = (len(cards) == 3)\n kgrams = []\n if cards[0] == '*':\n kgrams.extend(self.kgrams(cards[1], 'end'))\n elif cards[1] == '*' and middle:\n kgrams.extend(self.kgrams(cards[0], 'start'))\n kgrams.extend(self.kgrams(cards[2], 'end'))\n else:\n kgrams.extend(self.kgrams(cards[0], 'start'))\n return kgrams\n\n\n def kgrams(self, term, pos):\n \"\"\"Generate kgrams for wildcard subset\"\"\"\n k = self.store.kgrams_length\n kgrams = []\n if pos == 'start':\n kgrams.append(\"$\" + term[0:k-1])\n\n for i in range(len(term) - (k-1)):\n kgrams.append(term[i:i+k])\n\n if pos == 'end':\n kgrams.append(term[-(k-1):] + \"$\")\n return [t for t in kgrams if len(t) == k]\n\n","sub_path":"engn.py","file_name":"engn.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"439205792","text":"from sqlalchemy.types import Integer, String, DateTime\n\nclass Config:\n driver = \"SQL Server Native Client 11.0\"\n username = \"GEOMRE\"\n password = \"P@ssw!@#\"\n server = \"LSPR02-0402-87\\\\CUS7602TPTEST,48001\"\n database = \"V3_Central\"\n schema = \"GeoMRE\"\n directory = \"//na/data/Corp/finance2/private/__Telecom Division/Tellworks/Reports/AIMS Reports\"\n targets = (\n ('Received', r'^ReceivedData_.*\\.csv$', 'InventoryReceived',\n {\n 'DatRcvd': 'ReceivedDate',\n 'PartNum': 'ItemNo',\n 'Description': 'ItemDescription',\n 'Market': 'WarehouseLocation',\n 'Qty': 'ReceivedQuantity',\n 'PACENum': 'ProjectSiteId',\n 'OrderNum': 'PONo',\n 'Condition': 'InventoryType'\n }),\n ('Shipped', r'^ShippedData_.*\\.csv$', 'InventoryShipped',\n {\n 'Auth#': 'AuthNo',\n 'PACENum': 'ProjectSiteId',\n 'PartNum': 'ItemNo',\n 'OrderNum': 'PONo',\n 'Qty': 'DeployedQuantity',\n 'ShipDate': 'DeployedDate'\n }),\n ('Site Equipment Deployment History', r'^SiteEquipDepData_.*\\.csv$', 'SiteEquipmentDeploymentHistory',\n {\n 'Pickup Auth #': 'AuthNo',\n 'Status': 'FulfillmentStatus',\n 'Staged Date': 'StagedDate',\n 'PACENum': 'ProjectSiteId',\n 'Pickup Company': 'Subcontractor'\n }),\n ('Staged Inventory Details', r'^InventoryPickData_.*\\.csv$', 'InventoryPicked',\n {\n 'PartNum': 'ItemNo',\n 'Auth Number': 'AuthNo',\n 'Picked QTY': 'StagedQuantity',\n 'PACENum': 'ProjectSiteId'\n })\n )\n dtypes = {\n 'InventoryReceived': {\n 'ReceivedDate': DateTime(),\n 'ItemNo': String(100),\n 'ItemDescription': String(1000),\n 'WarehouseLocation': String(500),\n 'ReceivedQuantity': Integer(),\n 'ProjectSiteId': String(100),\n 'PONo': String(100),\n 'InventoryType': String(100)\n },\n 'InventoryStagedDeployed': {\n 'AuthNo': String(100),\n 'ProjectSiteId': String(100),\n 'FulfillmentStatus': String(100),\n 'StagedDate': DateTime(),\n 'Subcontractor': String(200),\n 'StagedQuantity': Integer(),\n 'DeployedDate': DateTime(),\n 'DeployedQuantity': Integer(),\n 'PONo': String(100),\n 'ItemNo': String(100)\n }\n }\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"441542378","text":"import numpy as np\nfrom scipy.linalg import schur\n\n\ndef node_strength(A):\n \"\"\" Returns strength of the nodes of a network.\n\n Args:\n A: np.array (n_parcels, n_parcels)\n Adjacency matrix from structural connectome\n\n Returns:\n s: np.array (n_parcels,)\n vector of strength values across nodes\n\n @author lindenmp\n \"\"\"\n s = np.sum(A, axis=0)\n\n return s\n\n\ndef ave_control(A_norm):\n \"\"\" Returns values of AVERAGE CONTROLLABILITY for each node in a network, given the adjacency matrix for that\n network. Average controllability measures the ease by which input at that node can steer the system into many\n easily-reachable states. Expects input to be a DISCRETE system\n\n Args:\n A_norm: np.array (n_parcels, n_parcels)\n Normalized adjacency matrix from structural connectome (see matrix_normalization in utils for example)\n\n Returns:\n ac: np.array (n_parcels,)\n vector of average controllability values for each node\n\n @author lindenmp\n Reference: Gu, Pasqualetti, Cieslak, Telesford, Yu, Kahn, Medaglia,\n Vettel, Miller, Grafton & Bassett, Nature Communications\n 6:8414, 2015.\n \"\"\"\n\n T, U = schur(A_norm, 'real') # Schur stability\n midMat = np.multiply(U, U).transpose()\n v = np.matrix(np.diag(T)).transpose()\n N = A_norm.shape[0]\n P = np.diag(1 - np.matmul(v, v.transpose()))\n P = np.tile(P.reshape([N, 1]), (1, N))\n ac = sum(np.divide(midMat, P))\n\n return ac\n\n\ndef modal_control(A_norm):\n \"\"\" Returns values of MODAL CONTROLLABILITY for each node in a network, given the adjacency matrix for that network.\n Modal controllability indicates the ability of that node to steer the system into difficult-to-reach states,\n given input at that node. Expects input to be a DISCRETE system\n\n Args:\n A_norm: np.array (n_parcels, n_parcels)\n Normalized adjacency matrix from structural connectome (see matrix_normalization in utils for example)\n\n Returns:\n phi: np.array (n_parcels,)\n vector of modal controllability values for each node\n\n @author lindenmp\n Reference: Gu, Pasqualetti, Cieslak, Telesford, Yu, Kahn, Medaglia,\n Vettel, Miller, Grafton & Bassett, Nature Communications\n 6:8414, 2015.\n \"\"\"\n\n T, U = schur(A_norm, 'real') # Schur stability\n eigVals = np.diag(T)\n N = A_norm.shape[0]\n phi = np.zeros(N, dtype=float)\n for i in range(N):\n Al = U[i,] * U[i,]\n Ar = (1.0 - np.power(eigVals, 2)).transpose()\n phi[i] = np.matmul(Al, Ar)\n\n return phi\n","sub_path":"src/network_control/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606890088","text":"import tkinter as tk\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.colors import rgb2hex\nfrom networkit.viztasks import drawGraph\n\nfrom BribeNet.gui.apps.temporal.results_wizard.window import TemporalResultsWizardWindow\n\n\nclass GraphFrame(tk.Frame):\n \"\"\"\n Frame for showing the current state and actions that can be taken for the temporal model being run\n \"\"\"\n\n def __init__(self, parent, controller):\n\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.parent = parent\n self.fig = plt.figure(figsize=(8, 8))\n self.ax = self.fig.add_subplot(111)\n self.canvas = FigureCanvasTkAgg(self.fig, master=self)\n self.grid_rowconfigure(1, weight=1)\n self.canvas.get_tk_widget().grid(row=1, column=0, rowspan=10)\n self.results = []\n self.pos = None\n self.gamma = None\n self.briber_buttons = None\n self.briber_name_to_index = None\n self.rating_string_var = None\n\n step_button = tk.Button(self, text=\"Next Step\", command=self.controller.next_step)\n step_button.grid(row=3, column=2, sticky='nsew')\n\n results_button = tk.Button(self, text=\"Results\", command=self.show_results_wizard)\n results_button.grid(row=4, column=2, sticky='nsew')\n\n exit_button = tk.Button(self, text=\"Exit\", command=self.return_to_wizard)\n exit_button.grid(row=7, column=2, sticky='nsew')\n\n steps_slide = tk.Scale(self, from_=1, to=100, orient=tk.HORIZONTAL)\n steps_slide.grid(row=6, column=2, sticky='nsew')\n n_steps_button = tk.Button(self, text=\"Perform n steps\", command=lambda: self.n_steps(steps_slide.get()))\n n_steps_button.grid(row=5, column=2, sticky='nsew')\n\n self.info = tk.StringVar(parent)\n round_desc_canvas = tk.Canvas(self)\n round_desc_scroll = tk.Scrollbar(self, orient='vertical', command=round_desc_canvas.yview)\n round_desc_frame = tk.Frame(self)\n round_desc_frame.bind(\n \"\",\n lambda e: round_desc_canvas.configure(\n scrollregion=round_desc_canvas.bbox(\"all\")\n )\n )\n round_desc_canvas.create_window((0, 0), window=round_desc_frame, anchor=\"n\")\n round_desc_canvas.config(yscrollcommand=round_desc_scroll.set)\n round_desc_label = tk.Label(round_desc_frame, textvariable=self.info)\n round_desc_label.pack(fill=tk.BOTH, expand=1)\n\n round_desc_canvas.grid(row=1, column=1, columnspan=2, pady=10, padx=10, sticky='nsew')\n round_desc_scroll.grid(row=1, column=2, pady=10, sticky='nse')\n self.info.set(\"--\")\n\n def return_to_wizard(self):\n self.results = []\n self.info.set(\"--\")\n self.controller.clear_graph()\n self.controller.show_frame(\"WizardFrame\")\n\n def set_info(self, s):\n self.info.set(s)\n\n def set_pos(self, pos):\n self.pos = pos\n\n def n_steps(self, n):\n for i in range(0, n):\n self.controller.next_step()\n\n def add_briber_dropdown(self):\n\n view_title_label = tk.Label(self, text=\"View rating for briber\")\n view_title_label.grid(row=3, column=1)\n\n rating_choices = ['None'] + self.controller.briber_names\n\n self.briber_name_to_index = {v: k for k, v in enumerate(self.controller.briber_names)}\n self.rating_string_var = tk.StringVar(self)\n self.rating_string_var.set('None')\n\n rating_dropdown = tk.OptionMenu(self, self.rating_string_var, *rating_choices)\n\n # noinspection PyUnusedLocal\n def change_dropdown(*args):\n var_val = self.rating_string_var.get()\n if var_val == 'None':\n self.draw_basic_graph(self.controller.g)\n else:\n self.draw_briber_graph(self.briber_name_to_index[var_val])\n\n self.rating_string_var.trace('w', change_dropdown)\n\n rating_dropdown.grid(row=4, column=1, sticky='nsew')\n\n trust_button = tk.Button(self, text=\"Show Trust\", command=lambda: self.show_trust(self.controller.g))\n trust_button.grid(row=6, column=1, sticky='nsew')\n\n def show_results_wizard(self):\n results_wizard = TemporalResultsWizardWindow(self.controller, self.controller.results)\n results_wizard.lift()\n\n def draw_basic_graph(self, graph):\n colours = [\"gray\" for _ in graph.get_customers()] # nodes\n edge_colours = [\"#000000\" for _ in graph.get_edges()] # edges\n self._update_graph(graph, colours, edge_colours)\n self.canvas.draw()\n\n def draw_briber_graph(self, b):\n\n # node colours\n graph = self.controller.g\n\n colour_map = plt.get_cmap(\"Purples\")\n colours = []\n for c in graph.get_customers():\n if np.isnan(graph.get_vote(c)[b]):\n colours.append(\"gray\")\n else:\n colours.append(rgb2hex(colour_map(graph.get_vote(c)[b])[:3]))\n edge_colours = [\"#000000\" for _ in graph.get_edges()] # edges\n\n self._update_graph(graph, colours, edge_colours)\n self._add_annotations(b)\n self.canvas.draw()\n\n def _update_graph(self, graph, colours, edge_colours):\n\n self.ax.clear()\n drawGraph(\n graph.get_graph(),\n node_size=400,\n node_color=colours,\n edge_color=edge_colours,\n ax=self.ax, pos=self.pos,\n with_labels=True\n )\n\n def _add_annotations(self, b):\n graph = self.controller.g\n for c in graph.get_customers():\n if np.isnan(graph.get_vote(c)[b]):\n rating = \"None\"\n else:\n rating = round(graph.get_vote(c)[b], 2)\n\n self.ax.annotate(\n str(c) + \":\\n\"\n + \"Vote: \" + str(rating) + \"\\n\"\n + \"Rating: \" + str(round(graph.get_rating(c), 2)),\n xy=(self.pos[c][0], self.pos[c][1]),\n bbox=dict(boxstyle=\"round\", fc=\"w\", ec=\"0.5\", alpha=0.9)\n )\n\n def show_trust(self, graph):\n\n colours = [\"gray\" for _ in graph.get_customers()] # nodes\n colour_map = plt.get_cmap(\"Greys\")\n edge_colours = []\n for (u, v) in graph.get_edges():\n edge_colours.append(rgb2hex(colour_map(graph.get_weight(u, v))[:3]))\n self._update_graph(graph, colours, edge_colours)\n self.canvas.draw()\n","sub_path":"src/BribeNet/gui/apps/temporal/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"45262633","text":"from django.contrib import admin\n\nfrom guides.models import Tag\nfrom guides.models import Guide\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n fields = (\n 'value',\n 'parent_tag',\n 'description', )\n list_display = (\n 'value',\n 'parent_tag', )\n\n\n@admin.register(Guide)\nclass GuideAdmin(admin.ModelAdmin):\n fields = (\n 'title',\n 'content_md',\n 'content_html',\n 'tags', )\n list_display = (\n 'published',\n 'title', )\n","sub_path":"guides/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"552769751","text":"# https://stackoverflow.com/questions/8901415/readlines-not-reading-the-last-line-of-the-file-in-python\n\n\ndef insert_line_numbers(file):\n with open(file, 'r') as read_file:\n with open('output.txt', 'w') as write_file:\n # lines = list(read_file) # readlines would be a less-efficient alternative\n lines = list(map(lambda line: line, read_file))\n lines_with_nums = [f\"{index+1}. {line}\" for index, line in enumerate(lines)]\n write_file.writelines(lines_with_nums)\n\n\n# _________________________________________________________________________________________________________________________\n# Reading all the lines and adding numbers to them:\ndef solve():\n lines = open('input.txt').read().split('\\n') # cuts the new line and store every element\n\n lines_with_nums = list(f'{index+1}. {line}' for index, line in enumerate(lines))\n\n open('output2.txt', 'w').write('\\n'.join(lines_with_nums))\n\n\nif __name__ == '__main__':\n insert_line_numbers('input.txt')\n","sub_path":"Python/Python-Fundamentals/7.Files_and_Directories/2.Insert Line Numbers/2.Line Numbers.py","file_name":"2.Line Numbers.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"581831196","text":"import numpy as np\nimport random\nfrom util import oneHotEncodeY\nfrom util import sigmoid\n\n\nclass NeuralNetwork:\n\n\tdef __init__(self, inputSize, outputSize, numHiddenLayers, hiddenLayerSizes, alpha, batchSize, epochs):\n\t\t# Method to initialize a Neural Network Object\n\t\t# Parameters\n\t\t# inputSize - Size of the input layer\n\t\t# outputSize - Size of the output layer\n\t\t# numHiddenLayers - Number of hidden layers in the neural network\n\t\t# hiddenLayerSizes - List of the hidden layer node sizes\n\t\t# alpha - learning rate\n\t\t# batchSize - Mini batch size\n\t\t# epochs - Number of epochs for training\n\t\tself.inputSize = inputSize\n\t\tself.outputSize = outputSize\n\t\tself.numLayers = numHiddenLayers + 2\n\t\tself.layerSizes = [inputSize] + hiddenLayerSizes + [outputSize]\n\t\tself.alpha = alpha\n\t\tself.batchSize = batchSize\n\t\tself.epochs = epochs\n\n\t\t# Initializes the Neural Network Weights and Biases using a Normal Distribution with Mean 0 and Standard Deviation 1\n\t\t# weights - a list of matrices correspoding to the weights in various layers of the network\n\t\t# biases - corresponding list of biases for each layer\n\t\tself.weights = []\n\t\tself.biases = []\n\n\t\tfor i in range(self.numLayers-1):\n\t\t\tsize = self.layerSizes[i], self.layerSizes[i+1]\n\t\t\tself.biases.append(np.random.normal(0, 1, self.layerSizes[i+1]))\n\t\t\tself.weights.append(np.random.normal(0,1,size))\n\n\t\tself.weights = np.asarray(self.weights)\n\t\tself.biases = np.asarray(self.biases)\n\n\n\tdef train(self, trainX, trainY, validX=None, validY=None, printTrainStats=True, printValStats=True):\n\t\t# Method for training the Neural Network\n\t\t# Input\n\t\t# trainX - A list of training input data to the neural network\n\t\t# trainY - Corresponding list of training data labels\n\t\t# validX - A list of validation input data to the neural network\n\t\t# validY - Corresponding list of validation data labels\n\t\t# printTrainStats - Print training loss and accuracy for each epoch\n\t\t# printValStats - Prints validation set accuracy after each epoch of training\n\t\t# The methods trains the weights and baises using the training data(trainX, trainY)\n\t\t# and evaluates the validation set accuracy after each epoch of training\n\t\t\n\t\tfor epoch in range(self.epochs):\n\t\t\t# A Training Epoch\n\t\t\tif printTrainStats or printValStats:\n\t\t\t\tprint(\"Epoch: \", epoch)\n\n\t\t\t# Shuffle the training data for the current epoch\n\t\t\tX = np.asarray(trainX)\n\t\t\tY = np.asarray(trainY)\n\t\t\tperm = np.arange(X.shape[0])\n\t\t\tnp.random.shuffle(perm)\n\t\t\tX = X[perm]\n\t\t\tY = Y[perm]\n\n\t\t\t# Initializing training loss and accuracy\n\t\t\ttrainLoss = 0\n\t\t\ttrainAcc = 0\n\n\t\t\t# Divide the training data into mini-batches\n\t\t\tnumBatches = int(np.ceil(float(X.shape[0]) / self.batchSize))\n\t\t\tfor batchNum in range(numBatches):\n\t\t\t\tXBatch = np.asarray(X[batchNum*self.batchSize: (batchNum+1)*self.batchSize])\n\t\t\t\tYBatch = np.asarray(Y[batchNum*self.batchSize: (batchNum+1)*self.batchSize])\n\n\t\t\t\t# Calculate the activations after the feedforward pass\n\t\t\t\tactivations = self.feedforward(XBatch)\t\n\n\t\t\t\t# Compute the loss\t\n\t\t\t\tloss = self.computeLoss(YBatch, activations)\n\t\t\t\ttrainLoss += loss\n\t\t\t\t\n\t\t\t\t# Estimate the one-hot encoded predicted labels after the feedword pass\n\t\t\t\tpredLabels = oneHotEncodeY(np.argmax(activations[-1], axis=1), self.outputSize)\n\n\t\t\t\t# Calculate the training accuracy for the current batch\n\t\t\t\tacc = self.computeAccuracy(YBatch, predLabels)\n\t\t\t\ttrainAcc += acc\n\n\t\t\t\t# Backpropagation Pass to adjust weights and biases of the neural network\n\t\t\t\tself.backpropagate(activations, YBatch)\n\n\t\t\t# Print Training loss and accuracy statistics\n\t\t\ttrainAcc /= numBatches\n\t\t\tif printTrainStats:\n\t\t\t\tprint(\"Epoch \", epoch, \" Training Loss=\", loss, \" Training Accuracy=\", trainAcc)\n\t\t\t\n\t\t\t# Estimate the prediction accuracy over validation data set\n\t\t\tif validX is not None and validY is not None and printValStats:\n\t\t\t\t_, validAcc = self.validate(validX, validY)\n\t\t\t\tprint(\"Validation Set Accuracy: \", validAcc, \"%\")\n\n\tdef computeLoss(self, Y, activations):\n\t\t# Returns the squared loss function given the activations and the true labels Y\n\t\tloss = (Y - activations[-1]) ** 2\n\t\tloss = np.mean(loss)\n\t\treturn loss\n\n\tdef computeAccuracy(self, Y, predLabels):\n\t\t# Returns the accuracy given the true labels Y and predicted labels predLabels\n\t\tcorrect = 0\n\t\tfor i in range(len(Y)):\n\t\t\tif np.array_equal(Y[i], predLabels[i]):\n\t\t\t\tcorrect += 1\n\t\taccuracy = (float(correct) / len(Y)) * 100\n\t\treturn accuracy\n\n\tdef validate(self, validX, validY):\n\t\t# Input \n\t\t# validX : Validation Input Data\n\t\t# validY : Validation Labels\n\t\t# Returns the validation accuracy evaluated over the current neural network model\n\t\tvalActivations = self.feedforward(validX)\n\t\tpred = np.argmax(valActivations[-1], axis=1)\n\t\tvalidPred = oneHotEncodeY(pred, self.outputSize)\n\t\tvalidAcc = self.computeAccuracy(validY, validPred)\n\t\treturn pred, validAcc\n\n\tdef feedforward(self, X):\n\t\t# Input\n\t\t# X : Current Batch of Input Data as an nparray\n\t\t# Output\n\t\t# Returns the activations at each layer(starting from the first layer(input layer)) to \n\t\t# the output layer of the network as a list of np arrays\n\t\t# Note: Activations at the first layer(input layer) is X itself\n\t\t\n\t\tactivations = []\n\t\t###############################################\n\t\t# TASK 1 - YOUR CODE HERE\n\t\tcurr_layer = X[:]\n\t\tactivations.append(curr_layer)\n\t\t\n\t\tfor i in range(len(self.weights)):\n\t\t\ttemp_act = np.matmul(curr_layer,self.weights[i])\n\t\t\ttemp_act = temp_act + self.biases[i]\n\t\t\ttemp_act = sigmoid(temp_act)\n\t\t\tcurr_layer = temp_act[:]\n\t\t\tactivations.append(curr_layer)\n\n\t\t###############################################\n\t\treturn activations\n\n\tdef backpropagate(self, activations, Y):\n\t\t# Input\n\t\t# activations : The activations at each layer(starting from second layer(first hidden layer)) of the\n\t\t# neural network calulated in the feedforward pass\n\t\t# Y : True labels of the training data\n\t\t# This method adjusts the weights(self.weights) and biases(self.biases) as calculated from the\n\t\t# backpropagation algorithm\n\t\t\n\t\t###############################################\t\t\t\t \n\t\t# TASK 2 - YOUR CODE HERE\n\t\tdef sigmoid_prime(inp):\n\t\t\tret = inp*(1-inp)\n\t\t\treturn ret\n\n\t\tout = activations[len(activations)-1]\n\t\tdelta = sigmoid_prime(out)*(Y - out)\n\n\t\tj = 2\n\t\tfor i in range(self.numLayers-2,-1,-1):\n\t\t\tout = activations[-j]\n\t\t\t\n\t\t\tdweights = np.matmul(out.transpose(),delta)\n\t\t\tdbias = np.sum(delta,axis=0)\n\t\t\t\n\t\t\tself.weights[-j+1] += self.alpha*dweights \n\t\t\tself.biases[-j+1] += self.alpha*dbias\n\t\t\t\n\t\t\tdelta = np.matmul(delta,self.weights[-j+1].transpose())*sigmoid_prime(out)\n\t\t\tj+=1\n\n\t\t###############################################\n\t\tpass","sub_path":"LAB 8/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"352980222","text":"numbers = [1325234,234,4538906,1239847,5472,12389,12,235]\n\ndef insertionSort(arr, j):\n for x in reversed(range(j)):\n if(arr[j] < arr[x]):\n saveSpot = arr[j]\n arr[j] = arr[x]\n arr[x] = saveSpot\n j = x\n if j == len(numbers)-1:\n return arr\n return(insertionSort(arr, j+1))\n\n\n \n \nprint(insertionSort(numbers, 1))\n","sub_path":"sorts/insertion.py","file_name":"insertion.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"413460448","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nimport stripe\nimport redis\nfrom celery import Celery\nfrom raven.contrib.flask import Sentry\nfrom flask import Flask, render_template, request, redirect, session, g, abort\nfrom flask_sslify import SSLify\nfrom flask_heroku import Heroku\nfrom flask.ext.cache import Cache\nfrom werkzeug.contrib.cache import RedisCache\nfrom flask.ext.markdown import Markdown\nfrom validate_email import validate_email\nfrom sqlalchemy.exc import OperationalError, IntegrityError\n\n\nfrom . import numbers\nfrom .models import db, Customer, Essay\n\n\nDEBUG = ('DEBUG' in os.environ)\nRABBITMQ_URL = os.environ.get('CLOUDAMQP_URL')\nREDIS_URL = os.environ.get('OPENREDIS_URL')\nPOSTMARK_KEY = os.environ.get('POSTMARK_KEY')\nSTRIPE_PUBLIC = os.environ.get('STRIPE_PUBLIC')\nSTRIPE_SECRET = os.environ.get('STRIPE_SECRET')\nDATABASE_URL = os.environ.get('DATABASE_URL')\nSECRET_KEY = os.environ.get('SECRET_KEY', 'wofhoiwehfiowhefioewf')\nSTRIPE_SECRET = os.environ.get('STRIPE_SECRET')\nSTRIPE_PUBLIC = os.environ.get('STRIPE_PUBLIC')\nSENTRY_DSN = os.environ.get('SENTRY_DSN')\n\napp = Flask(__name__)\napp.debug = DEBUG\napp.secret_key = SECRET_KEY\napp.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL\n\n\n# if SENTRY_DSN:\n # app.config['SENTRY_DSN'] = 'SENTRY_DSN'\nsentry = Sentry(app)\n\ncelery = Celery(broker=RABBITMQ_URL)\n\nheroku_env = Heroku(app)\nsslify = SSLify(app)\nmarkdown = Markdown(app)\ndb.init_app(app)\nstripe.api_key = STRIPE_SECRET\n\ncache = Cache()\n# cache.cache = RedisCache()\n# cache.cache._client = redis.from_url(REDIS_URL)\n\ndef paywall(paid=True):\n if not g.user:\n abort(redirect('login'))\n if paid:\n if not g.user.active:\n abort(redirect('account'))\n\n\n\n\n@app.before_request\ndef lookup_user():\n g.user = Customer.query.filter_by(email=session.get('user')).first()\n\n@app.context_processor\ndef inject_user():\n return dict(\n user=g.user,\n STRIPE_PUBLIC=STRIPE_PUBLIC\n )\n\n@app.route('/')\ndef landing_page():\n if g.user:\n return redirect('/essays')\n\n return render_template('index.html')\n\n@app.route('/faq')\ndef faq_page():\n return render_template('faq.html')\n\n@app.route('/demo')\ndef demo_page():\n essay = Essay.query.filter_by(id=1).first()\n essays = Essay.query.all()\n\n return render_template('essay.html', essays=essays, essay=essay)\n\n@app.route('/login')\ndef login_page():\n return render_template('login.html')\n\n\n@app.route('/login', methods=['POST'])\ndef login_action():\n email = request.form['user_email']\n passwd = request.form['pwd']\n\n c = Customer.query.filter_by(email=email).first()\n\n try:\n if c.check_password(passwd):\n session['user'] = c.email\n else:\n raise AttributeError\n except AttributeError:\n return render_template('login.html', error=True)\n\n\n\n return redirect('/essays')\n\n@app.route('/subscribe')\ndef signup_page():\n return render_template('subscribe.html')\n\n@app.route('/account')\ndef account_page():\n paywall(paid=False)\n\n return render_template('account.html')\n\n@app.route('/account', methods=['POST'])\ndef account_action():\n paywall(paid=False)\n\n token = request.form['stripeToken']\n\n # Retrieve an existing user.\n try:\n customer = stripe.Customer.retrieve(g.user.stripe_id)\n except stripe.InvalidRequestError:\n customer = None\n\n # Create a new user.\n if customer is None:\n try:\n customer = stripe.Customer.create(\n card=token,\n plan=\"individual\",\n email=g.user.email\n )\n\n except stripe.CardError:\n return render_template('account.html', error=True)\n\n # Update existing user\n else:\n try:\n customer.update(card=token)\n except stripe.CardError:\n return render_template('account.html', error=True)\n\n # Update our records.\n g.user.active = True\n g.user.stripe_id = customer.id\n g.user.save()\n\n return redirect('/essays')\n\n\n@app.route('/logout')\ndef logout_action():\n session['user'] = None\n return redirect('/')\n\n@app.route('/subscribe', methods=['POST'])\ndef signup_action():\n\n email = request.form['user_email']\n pass1 = request.form['pwd']\n pass2 = request.form['cpwd']\n\n try:\n assert pass1\n assert pass1 == pass2\n assert validate_email(email)\n except AssertionError:\n return render_template('subscribe.html', error=True)\n\n try:\n c = Customer(email, pass1)\n c.active = False\n c.save()\n except (OperationalError, IntegrityError):\n db.session.rollback()\n c = Customer.query.filter_by(email=email).first()\n try:\n assert c.check_password(pass1)\n except AssertionError:\n return render_template('subscribe.html', error=True)\n\n session['user'] = c.email\n\n return redirect('/essays')\n\n@app.route('/essays')\ndef essays_page():\n\n paywall()\n\n essays = Essay.query.all()\n\n return render_template('essays.html', essays=essays)\n\n@app.route('/essays/')\ndef essay_page(slug):\n\n paywall()\n\n essay = Essay.query.filter_by(slug=slug).first()\n essays = Essay.query.all()\n\n return render_template('essay.html', essays=essays, essay=essay)\n\n\n@app.route('/stripe-webhook', methods=['POST'])\ndef webhook_action():\n\n # Deactivate account.\n j = request.json\n\n if j['type'] == 'customer.deleted':\n customer_id = j['data']['object']['id']\n\n c = Customer.query.filter_by(stripe_id=customer_id).first()\n c.stripe_id = None\n c.active = False\n c.save()\n\n if j['type'] == 'customer.subscription.deleted':\n customer_id = j['data']['object']['customer']\n\n c = Customer.query.filter_by(stripe_id=customer_id).first()\n c.stripe_id = None\n c.active = False\n c.save()\n\n return 'ok'\n\n\n\n# http://conductofcode.org/stripe-webhook\n\nif __name__ == '__main__':\n app.run()","sub_path":"conduct/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"304465730","text":"import logging\n\nclass BrgbcFrame:\n\tdef __init__(self):\n\t\tself.methodId = 0\n\t\tself.frameToken = 0x00\n\t\tself.clientAdress = 0x00\n\t\tself.content = bytearray('')\n\n\n\n\tdef GetFrame(self):\n\t\tframe = bytearray('')\n\n\t\tframe.append(0xe3) #magic number\n\t\tframe.append(0x01) # protocoll version\n\n\t\tlogging.debug(\"Building brgbc frame with client Adress: %s\", self.clientAdress)\n\t\tframe.append(self.clientAdress)\n\n\t\tself.WriteLen(frame)\n\n\t\tframe.append(self.methodId)\n\n\t\tframe.append(self.frameToken)\n\n\t\tframe.extend(str(self.content))\n\n\t\treturn str(frame)\n\n\tdef WriteLen(self,target):\n\t\tlength = len(self.content)\n\n\t\tlastByte = length & 0xff\n\t\tfirstByte = (length >> 8) & 0xff\n\n\t\ttarget.append(firstByte)\n\t\ttarget.append(lastByte)\n","sub_path":"source/infrastructure/brgbc/BrgbcFrame.py","file_name":"BrgbcFrame.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"446579376","text":"\nfrom random import *\nclass GameControl:\n '''This is the top level class that control the game,\n using the classes: UserInterface, Cards, and PlayGame.'''\n\n def __init__(self):\n '''Construts two objects of type UserInterface and Statistics.'''\n self.UI = UserInterface()\n self.stats = Statististics()\n\n \n def startPlaying(self):\n '''This method will start and control the entire game.'''\n self.UI.printIntro()#Prints an introduction to the game\n self.playRound()#Play one round of the game\n while self.UI.continueplay():#Determines if the game should be continued\n self.playRound()#Play a complete round again\n self.stats.printFinalresult()#prints the final results\n \n \n def playRound(self):\n '''This method play a round of the game.'''\n \n self.stats.mixCards()\n self.stats.giveCards()\n self.stats.showLosercard()\n user = self.UI.keep_or_switch()\n self.stats.changeCard(user)\n self.stats.printResult()\n print('.....................................................')\n \n\nclass UserInterface:\n '''This is the class that prints out information to the player.'''\n\n def printIntro(self):\n '''This method prints an introduction to the game.\n It states the rules of the game.'''\n print('.....................................................')\n print(\" Stay or Switch Game \")\n print('.....................................................')\n print(\"If you do not know how to play, see the rules online.\")\n print('.....................................................')\n def keep_or_switch(self):\n '''This method asks the user if he wants to\n keep the card selected or if he wants to switch it.\n It returns True, if he wants to keep it.\n Otherwise, it returns False.'''\n player = input(\"Would you like to keep or switch your card? type: k or s ---> \").lower()\n if player[0] == 's':\n return True\n else:\n return False\n \n def continueplay(self):\n '''This method asks the player if he wants to play again.\n Return true if he wants to. Otherwise, returns false.'''\n user = input('Would you like to play another round? y or n ---> ').lower()\n if user[0] == 'y':\n return True\n else:\n return False\n \n\nclass Cards:\n '''This is the class that keeps track of the cards.'''\n\n def __init__(self):\n '''constructs the cards'''\n self.labels = ['WINNER','LOSER',\"LOSER\"]\n \n def mixCards(self):\n '''This returns the cards mixed as a list.'''\n shuffle(self.labels)\n return self.labels\n \n def giveCards(self):\n '''This method gives the choice to the pleyer to select one card'''\n self.player = int(input(\"Choose a card from the table:\\n 1 2 3 ---> \"))\n print(\"You have selected card\",self.player)\n self.player = self.player - 1\n\n\n \n def showLosercard(self):\n '''This method show one of the two loser cards to the player.'''\n #player_card = self.getCard()#Current player's card\n for i in range(3):\n if self.labels[i] == \"LOSER\" and i != self.player:\n if i == 0:\n print(\" LOSER 2 3\")\n self.current = [1,2]#current cards facing down\n break\n elif i == 1:\n print(\" 1 LOSER 3\")\n self.current = [0,2]#current cards facing down\n break\n else:\n print(\" 1 2 LOSER\")\n self.current = [0,1]#current cards facing down\n print(\"Chances of wining increased!\")\n \n def changeCard(self,boolean):\n '''Will change and ruturn the current card the player has'''\n self.boolean = boolean\n if self.boolean == True:\n if self.current[0] != self.player:\n self.player = self.current[0]\n elif self.current[1] != self.player:\n self.player = self.current[1]\n \n else:\n pass\n return self.player\n \n\nclass Statististics(Cards):\n '''This class keeps track of the number of wins and losses. And also display this information'''\n\n def __init__(self):\n Cards.__init__(self) #Gets info from the Cards class\n self.win = 0 #Keeps track of the number on winnings\n self.losses = 0 #Keeps track of the number on winnings\n \n def printResult(self):\n '''This method tell the user if he wins or loses a round'''\n if self.labels[self.player] == \"WINNER\":\n self.win = self.win + 1\n print('You Won!! card',self.player + 1,'was the winning one.')\n print(self.labels)\n else:\n self.losses = self.losses + 1\n print('You Lost!! card',self.player + 1,'was not the winning one.')\n print(self.labels)\n \n \n\n def printFinalresult(self):\n '''Prints the final results'''\n print('.....................................................')\n print(\" Game Over \")\n print('.....................................................')\n print(\"RESULTS\")\n print('.....................................................')\n print('You played --->',self.win + self.losses,'rounds.')\n print('You won --->',self.win,'times.')\n print('You lost --->',self.losses,'times.')\n\n#TESTING\ndef main():\n A = GameControl()\n A.startPlaying()\nmain()\n","sub_path":"Homework 1/Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"637896497","text":"import logging\nimport argparse\nimport csv\nimport numpy as np\nfrom pathlib import Path\n\n\ndef main(args):\n data_dir = args.data_dir\n\n paths = sorted(list(data_dir.glob('*')))\n\n csv_path = str(args.output_path)\n with open(csv_path, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n\n train_list = []\n test_list = []\n\n for p in paths:\n if 'TRAIN' in p.parts[-1]:\n train_list.append(p)\n else:\n test_list.append(p)\n\n n_train = len(train_list)\n n_test = len(test_list)\n # print(n_train)\n # print(n_test)\n\n random_seed = 601985\n np.random.seed(int(random_seed))\n np.random.shuffle(train_list)\n np.random.shuffle(test_list)\n \n n_train = int(n_train * args.using_rate)\n n_test = int(n_test * args.using_rate)\n print(int(n_train * 0.9))\n print(int(n_train * 0.1))\n print(n_test)\n train_list = train_list[:n_train]\n test_list = test_list[:n_test]\n\n for idx, p in enumerate(train_list):\n if idx < int(n_train * 0.9):\n writer.writerow([str(p.parts[-1]), 'Training'])\n else:\n writer.writerow([str(p.parts[-1]), 'Validation'])\n for p in test_list:\n writer.writerow([str(p.parts[-1]), 'Testing'])\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description=\"To create the split.csv.\")\n parser.add_argument('using_rate', type=float, help='The rate of data be used')\n parser.add_argument('data_dir', type=Path,\n help='The directory of the data.')\n parser.add_argument('output_path', type=Path,\n help='The output path of the csv file.')\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(format='%(asctime)s | %(levelname)s | %(message)s',\n level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')\n args = _parse_args()\n main(args)\n","sub_path":"ft3d_split.py","file_name":"ft3d_split.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"307065109","text":"#! /usr/bin/env python\n\nimport turtle\n\ndef draw_square():\n\t\n\tscreen = turtle.Screen()\n\t# screen.setup(width=200, height=200, startx=0, starty=0)\n\tscreen.title('My Screen')\n\t\n\ta = turtle.Turtle()\n\ta.pensize(1)\n\ta.speed(10)\n\tfor y in range(90):\n\t\tfor x in range(4):\n\t\t\ta.right(y * 5)\n\t\t\ta.forward(150)\n\t\t\ta.right(90 - (y * 5))\n\n\tscreen.exitonclick()\n\n\ndraw_square()\n","sub_path":"draw_turtle.py","file_name":"draw_turtle.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"32280181","text":"# coding=utf-8\n\n# from controller import test, api_handler\n# from controller.api import ticketTemplate\n# from controller.api import ticket\n# from controller.user import login\n# from test_module.controller.user import manage\n# import tornado.web\n# import json\n# from test_module.controller import ding\n# from controller.user import signup\n# from test_module.test import client\n\n\nfrom handler import auth, department, mail, search, setting, template, workflow\nimport test\n# url映射\nhandlers = [\n\n ### 模板\n\n # 创建模板\n (r\"/api/template/create\", template.Create),\n\n # 获得模板列表\n (r\"/api/template/list\", template.List),\n\n # 获得模板 GET\n # 更新模板 PUT\n # 删除模板 DELETE\n (r\"/api/template/id/(?P<_id>[%a-f0-9]*)\", template.Template),\n\n ### 工作流\n\n # 创建工单\n (r\"/api/work/create\", workflow.Create),\n\n # 待审核列表\n (r\"/api/not_reviewed/list\", workflow.UnauditedList),\n\n # 部门工单列表\n (r\"/api/department_work/list\", workflow.DepartmentList),\n\n # 个人工单列表\n (r\"/api/personal_work/list\", workflow.PersonalList),\n\n # 获得工单内容\n (r\"/api/work/id/(?P<_id>[%a-f0-9]*)\", workflow.Work),\n\n # 审核\n # 取消审核\n (r\"/api/work/check\", workflow.Check),\n (r\"/api/work/cancel_check\", workflow.CancelCheck),\n\n # 派发\n (r\"/api/work/send\", workflow.Send),\n\n # 撤回\n\n # 签收\n\n # 转派\n\n # 通知\n\n # 回复\n\n # 归档\n\n # 表单下载\n\n ### 组织架构\n\n # 获得单位列表\n (r\"/api/department/list\", department.DepartmentList),\n (r\"/api/department/station/list\", department.StationList),\n # 获得单位信息\n\n # 获得员工列表\n\n # 获得员工信息\n (r\"/api/user/info\", auth.UserInfo),\n\n ### 邮件\n\n # 邮件列表\n\n # 邮件内容\n\n # 下载附件\n\n # excel列表\n\n # excel内容\n\n # 创建模板\n\n # 配置信息\n\n # 配置更新\n\n # 运行状态\n\n ### 用户验证\n\n # 登录\n\n # 登出\n (r\"/api/logout\", auth.Logout),\n\n ### 检索\n\n # 检索\n\n ### 统计\n\n # 统计\n\n ### 设置\n\n # 更新设置\n\n\n\n # 测试\n (r\"/api/test/template\", test.TemplateHandler),\n (r\"/api/test/excel\", test.ExcelCollector),\n]\n","sub_path":"hex/back_end/old_api_server/url_mapping.py","file_name":"url_mapping.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"30301651","text":"from typing import Optional, Callable, Dict\n\nfrom jsons._dump_impl import dump\n\n\ndef default_dict_serializer(\n obj: dict,\n cls: Optional[type] = None,\n *,\n strict: bool = False,\n strip_nulls: bool = False,\n key_transformer: Optional[Callable[[str], str]] = None,\n types: Optional[Dict[str, type]] = None,\n **kwargs) -> dict:\n \"\"\"\n Serialize the given ``obj`` to a dict of serialized objects.\n :param obj: the dict that is to be serialized.\n :param cls: not used.\n :param strict: if ``True`` the serialization will raise upon any the\n failure of any attribute. Otherwise it continues with a warning.\n :param strict: a bool to determine if the serializer should be strict\n (i.e. only dumping stuff that is known to ``cls``).\n :param strip_nulls: if ``True`` the resulting dict will not contain null\n values.\n :param key_transformer: a function that will be applied to all keys in the\n resulting dict.\n :param types: a ``dict`` with attribute names (keys) and their types\n (values).\n :param kwargs: any keyword arguments that may be given to the serialization\n process.\n :return: a dict of which all elements are serialized.\n \"\"\"\n result = dict()\n types = types or dict()\n for key in obj:\n obj_ = obj[key]\n cls_ = types.get(key, None)\n dumped_elem = dump(obj_,\n cls=cls_,\n key_transformer=key_transformer,\n strip_nulls=strip_nulls,\n strict=strict,\n **kwargs)\n if not (strip_nulls and dumped_elem is None):\n if key_transformer:\n key = key_transformer(key)\n result[key] = dumped_elem\n return result\n","sub_path":"jsons/serializers/default_dict.py","file_name":"default_dict.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"260030409","text":"\"\"\"Tackle repository functions.\"\"\"\nimport os\nimport re\n\nfrom tackle.exceptions import RepositoryNotFound, ContextFileNotFound\nfrom tackle.utils.vcs import clone\nfrom tackle.utils.zipfile import unzip\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from tackle.models import Mode, Source, Settings\n\n\ndef is_git_repo(value):\n \"\"\"Return True if value is a git repo.\"\"\"\n GIT_REPO_REGEX = re.compile(\n r\"\"\"\n # something like git:// ssh:// file:// etc.\n (((git\\+)?(https?):(//)?)\n | # or\n (git@[\\w\\.]+) # something like git@...\n )\n \"\"\",\n re.VERBOSE,\n )\n return bool(GIT_REPO_REGEX.match(value))\n\n\ndef is_repo_url(value):\n \"\"\"Return True if value is a repository URL.\"\"\"\n REPO_REGEX = re.compile(\n r\"\"\"\n # something like git:// ssh:// file:// etc.\n ((((git|hg)\\+)?(git|ssh|file|https?):(//)?)\n | # or\n (\\w+@[\\w\\.]+) # something like user@...\n )\n \"\"\",\n re.VERBOSE,\n )\n return bool(REPO_REGEX.match(value))\n\n\ndef is_file(value):\n \"\"\"Return True if the input looks like a file.\"\"\"\n REPO_REGEX = re.compile(\n r\"\"\"^.*\\.(yaml|yml|json)$\"\"\",\n re.VERBOSE,\n )\n return bool(REPO_REGEX.match(value))\n\n\n# TODO: Allow for abbreviated repo names\n# def update_github_url(url):\n# \"\"\"\"\"\"\n# REPO_REGEX = re.compile(\n# r\"\"\"/^[a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38}$/i\"\"\",\n# re.VERBOSE,\n# )\n\n\ndef is_zip_file(value):\n \"\"\"Return True if value is a zip file.\"\"\"\n return value.lower().endswith('.zip')\n\n\ndef expand_abbreviations(template, abbreviations):\n \"\"\"Expand abbreviations in a template name.\n\n :param template: The project template name.\n :param abbreviations: Abbreviation definitions.\n \"\"\"\n if template in abbreviations:\n return abbreviations[template]\n\n # Split on colon. If there is no colon, rest will be empty\n # and prefix will be the whole template\n prefix, sep, rest = template.partition(':')\n if prefix in abbreviations:\n return abbreviations[prefix].format(rest)\n\n return template\n\n\nCONTEXT_FILE_DICT = {\n 'cookiecutter': [\n 'cookiecutter.json',\n 'cookiecutter.yaml',\n 'cookiecutter.yml',\n 'cookiecutter.hcl',\n ],\n 'tackle': [\n '.tackle.yaml',\n '.tackle.yml',\n '.tackle.json',\n '.tackle.hcl',\n 'tackle.yaml',\n 'tackle.yml',\n 'tackle.json',\n 'tackle.hcl',\n ],\n}\n\nALL_VALID_CONTEXT_FILES = (\n CONTEXT_FILE_DICT['cookiecutter'] + CONTEXT_FILE_DICT['tackle']\n)\n\n\ndef determine_tackle_generation(context_file: str) -> str:\n \"\"\"Determine the tackle generation.\"\"\"\n if context_file in CONTEXT_FILE_DICT['cookiecutter']:\n return 'cookiecutter'\n else:\n return 'tackle'\n\n\ndef repository_has_tackle_file(repo_directory: str, context_file=None):\n \"\"\"Determine if `repo_directory` contains a `cookiecutter.json` file.\n\n :param repo_directory: The candidate repository directory.\n :param context_file: eg. `tackle.yaml`.\n :return: The path to the context file\n \"\"\"\n repo_directory_exists = os.path.isdir(repo_directory)\n if context_file:\n # The supplied context file exists\n context_file = os.path.join(os.path.abspath(repo_directory), context_file)\n if os.path.isfile(context_file):\n return context_file\n else:\n raise ContextFileNotFound(\n f\"Can't find supplied context_file at {context_file}\"\n )\n\n if repo_directory_exists:\n # Check for valid context files as default\n for f in ALL_VALID_CONTEXT_FILES:\n if os.path.isfile(os.path.join(repo_directory, f)):\n return f\n else:\n return None\n\n\ndef update_source(source: 'Source', settings: 'Settings', mode: 'Mode') -> 'Source':\n \"\"\"\n Locate the repository directory from a template reference.\n\n Applies repository abbreviations to the template reference.\n If the template refers to a repository URL, clone it.\n If the template is a path to a local repository, use it.\n\n :param template: A directory containing a project template directory,\n or a URL to a git repository.\n :param abbreviations: A dictionary of repository abbreviation\n definitions.\n :param clone_to_dir: The directory to clone the repository into.\n :param checkout: The branch, tag or commit ID to checkout after clone.\n :param no_input: Prompt the user at command line for manual configuration?\n :param password: The password to use when extracting the repository.\n :param directory: Directory within repo where cookiecutter.json lives.\n :return: A tuple containing the cookiecutter template directory, and\n a boolean descriving whether that directory should be cleaned up\n after the template has been instantiated.\n :raises: `RepositoryNotFound` if a repository directory could not be found.\n \"\"\"\n source.template = expand_abbreviations(source.template, settings.abbreviations)\n source.cleanup = False\n if is_zip_file(source.template):\n unzipped_dir = unzip(\n zip_uri=source.template,\n is_url=is_repo_url(source.template),\n clone_to_dir=settings.tackle_dir,\n no_input=mode.no_input,\n password=source.password,\n )\n repository_candidates = [unzipped_dir]\n source.cleanup = True\n elif is_repo_url(source.template):\n cloned_repo = clone(\n repo_url=source.template,\n checkout=source.checkout,\n clone_to_dir=settings.tackle_dir,\n no_input=mode.no_input,\n )\n repository_candidates = [cloned_repo]\n elif is_file(source.template):\n from pathlib import Path\n\n source.context_file = os.path.basename(source.template)\n source.repo_dir = Path(source.template).parent.absolute()\n source.template_name = os.path.basename(os.path.abspath(source.repo_dir))\n source.tackle_gen = determine_tackle_generation(source.context_file)\n return source\n else:\n repository_candidates = [\n source.template,\n os.path.join(settings.tackle_dir, source.template),\n ]\n\n if source.directory:\n repository_candidates = [\n os.path.join(s, source.directory) for s in repository_candidates\n ]\n\n for repo_candidate in repository_candidates:\n source.context_file = repository_has_tackle_file(\n repo_candidate, source.context_file\n )\n if not source.context_file:\n # Means that no valid context file has been found or provided\n continue\n else:\n source.repo_dir = os.path.abspath(repo_candidate)\n source.template_name = os.path.basename(os.path.abspath(repo_candidate))\n source.tackle_gen = determine_tackle_generation(source.context_file)\n return source\n\n raise RepositoryNotFound(\n 'A valid repository for \"{}\" could not be found in the following '\n 'locations:\\n{}'.format(source.template, '\\n'.join(repository_candidates))\n )\n","sub_path":"tackle/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":7246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"594771835","text":"from collections import namedtuple\n\n\ndef init_periodic_table():\n \"\"\"Create, initialize, and return a dictionary\n that contains all known elements. Each key\n value pair in the dictionary is in this form:\n symbol : (name, symbol, atomic_mass)\n\n The unit for atomic mass is atomic mass\n units (amu) sometimes abbreviated as u\n \"\"\"\n Element = namedtuple(\"Element\", [\"name\", \"symbol\", \"atomic_mass\"])\n table = {\n \"H\" : Element(\"Hydrogen\", \"H\", 1.00794),\n \"He\" : Element(\"Helium\", \"He\", 4.002602),\n \"Li\" : Element(\"Lithium\", \"Li\", 6.941),\n \"Be\" : Element(\"Beryllium\", \"Be\", 9.012182),\n \"B\" : Element(\"Boron\", \"B\", 10.811),\n \"C\" : Element(\"Carbon\", \"C\", 12.0107),\n \"N\" : Element(\"Nitrogen\", \"N\", 14.0067),\n \"O\" : Element(\"Oxygen\", \"O\", 15.9994),\n \"F\" : Element(\"Fluorine\", \"F\", 18.9984032),\n \"Ne\" : Element(\"Neon\", \"Ne\", 20.1797),\n \"Na\" : Element(\"Sodium\", \"Na\", 22.98976928),\n \"Mg\" : Element(\"Magnesium\", \"Mg\", 24.305),\n \"Al\" : Element(\"Aluminium\", \"Al\", 26.9815386),\n \"Si\" : Element(\"Silicon\", \"Si\", 28.0855),\n \"P\" : Element(\"Phosphorus\", \"P\", 30.973762),\n \"S\" : Element(\"Sulfur\", \"S\", 32.065),\n \"Cl\" : Element(\"Chlorine\", \"Cl\", 35.453),\n \"Ar\" : Element(\"Argon\", \"Ar\", 39.948),\n \"K\" : Element(\"Potassium\", \"K\", 39.0983),\n \"Ca\" : Element(\"Calsium\", \"Ca\", 40.078),\n \"Sc\" : Element(\"Scandium\", \"Sc\", 44.955912),\n \"Ti\" : Element(\"Titanium\", \"Ti\", 47.9),\n \"V\" : Element(\"Vanadium\", \"V\", 50.9415),\n \"Cr\" : Element(\"Chromium\", \"Cr\", 51.9961),\n \"Mn\" : Element(\"Manganese\", \"Mn\", 54.938045),\n \"Fe\" : Element(\"Iron\", \"Fe\", 55.845),\n \"Co\" : Element(\"Cobalt\", \"Co\", 58.933195),\n \"Ni\" : Element(\"Nickel\", \"Ni\", 58.6934),\n \"Cu\" : Element(\"Copper\", \"Cu\", 63.546),\n \"Zn\" : Element(\"Zinc\", \"Zn\", 65.38),\n \"Ga\" : Element(\"Gallium\", \"Ga\", 69.723),\n \"Ge\" : Element(\"Germanium\", \"Ge\", 72.64),\n \"As\" : Element(\"Arsenic\", \"As\", 74.9216),\n \"Se\" : Element(\"Selenium\", \"Se\", 78.96),\n \"Br\" : Element(\"Bromine\", \"Br\", 79.904),\n \"Kr\" : Element(\"Krypton\", \"Kr\", 83.798),\n \"Rb\" : Element(\"Rubidium\", \"Rb\", 85.4678),\n \"Sr\" : Element(\"Strontium\", \"Sr\", 87.62),\n \"Y\" : Element(\"Yttrium\", \"Y\", 88.90585),\n \"Zr\" : Element(\"Zirconium\", \"Zr\", 91.224),\n \"Nb\" : Element(\"Niobium\", \"Nb\", 92.90638),\n \"Mo\" : Element(\"Molybdenum\", \"Mo\", 95.96),\n \"Tc\" : Element(\"Technetium\", \"Tc\", 98),\n \"Ru\" : Element(\"Ruthenium\", \"Ru\", 101.07),\n \"Rh\" : Element(\"Rhodium\", \"Rh\", 102.9055),\n \"Pd\" : Element(\"Palladium\", \"Pd\", 106.42),\n \"Ag\" : Element(\"Silver\", \"Ag\", 107.8682),\n \"Cd\" : Element(\"Cadmium\", \"Cd\", 112.411),\n \"In\" : Element(\"Indium\", \"In\", 114.818),\n \"Sn\" : Element(\"Tin\", \"Sn\", 118.71),\n \"Sb\" : Element(\"Antimony\", \"Sb\", 121.76),\n \"Te\" : Element(\"Tellurium\", \"Te\", 127.6),\n \"I\" : Element(\"Iodine\", \"I\", 126.90447),\n \"Xe\" : Element(\"Xenon\", \"Xe\", 131.293),\n \"Cs\" : Element(\"Cesium\", \"Cs\", 132.9054519),\n \"Ba\" : Element(\"Barium\", \"Ba\", 137.327),\n \"La\" : Element(\"Lanthanum\", \"La\", 138.90547),\n \"Ce\" : Element(\"Cerium\", \"Ce\", 140.116),\n \"Pr\" : Element(\"Crazyname\", \"Pr\", 140.90765),\n \"Nd\" : Element(\"Neodymium\", \"Nd\", 144.242),\n \"Pm\" : Element(\"Promethium\", \"Pm\", 145),\n \"Sm\" : Element(\"Samarium\", \"Sm\", 150.36),\n \"Eu\" : Element(\"Europium\", \"Eu\", 151.964),\n \"Gd\" : Element(\"Gadolinium\", \"Gd\", 157.25),\n \"Tb\" : Element(\"Terbium\", \"Tb\", 158.92535),\n \"Dy\" : Element(\"Dysprosium\", \"Dy\", 162.5),\n \"Ho\" : Element(\"Holmium\", \"Ho\", 164.93032),\n \"Er\" : Element(\"Erbium\", \"Er\", 167.259),\n \"Tm\" : Element(\"Thulium\", \"Tm\", 168.93421),\n \"Yb\" : Element(\"Ytterbium\", \"Yb\", 173.054),\n \"Lu\" : Element(\"Lutetium\", \"Lu\", 174.9668),\n \"Hf\" : Element(\"Hafnium\", \"Hf\", 178.49),\n \"Ta\" : Element(\"Tantalum\", \"Ta\", 180.94788),\n \"W\" : Element(\"Tungsten\", \"W\", 183.84),\n \"Re\" : Element(\"Rhenium\", \"Re\", 186.207),\n \"Os\" : Element(\"Osmium\", \"Os\", 190.23),\n \"Ir\" : Element(\"Iridium\", \"Ir\", 192.217),\n \"Pt\" : Element(\"Platinum\", \"Pt\", 195.084),\n \"Au\" : Element(\"Gold\", \"Au\", 196.966569),\n \"Hg\" : Element(\"Mercury\", \"Hg\", 200.59),\n \"Tl\" : Element(\"Thallium\", \"Tl\", 204.3833),\n \"Pb\" : Element(\"Lead\", \"Pb\", 207.2),\n \"Bi\" : Element(\"Bismuth\", \"Bi\", 208.9804),\n \"Po\" : Element(\"Polonium\", \"Po\", 209),\n \"At\" : Element(\"Astatine\", \"At\", 210),\n \"Rn\" : Element(\"Radon\", \"Rn\", 222),\n \"Fr\" : Element(\"Francium\", \"Fr\", 223),\n \"Ra\" : Element(\"Radium\", \"Ra\", 226),\n \"Ac\" : Element(\"Actinium\", \"Ac\", 227),\n \"Th\" : Element(\"Thorium\", \"Th\", 232.03806),\n \"Pa\" : Element(\"Whonamedthis\", \"Pa\", 231.03588),\n \"U\" : Element(\"Uranium\", \"U\", 238.02891),\n \"Np\" : Element(\"Neptunium\", \"Np\", 237),\n \"Pu\" : Element(\"Plutonium\", \"Pu\", 244),\n \"Am\" : Element(\"Americium\", \"Am\", 243),\n \"Cm\" : Element(\"Curium\", \"Cm\", 247),\n \"Bk\" : Element(\"Berkelium\", \"Bk\", 247),\n \"Cf\" : Element(\"Californium\", \"Cf\", 251),\n \"Es\" : Element(\"Einsteinium\", \"Es\", 252),\n \"Fm\" : Element(\"Fermium\", \"Fm\", 257),\n \"Md\" : Element(\"Mendelevium\", \"Md\", 258),\n \"No\" : Element(\"Nobelium\", \"No\", 259),\n \"Lr\" : Element(\"Lawrencium\", \"Lr\", 262),\n \"Rf\" : Element(\"Rutherfordium\", \"Rf\", 267),\n \"Db\" : Element(\"Dubnium\", \"Db\", 268),\n \"Sg\" : Element(\"Seaborgium\", \"Sg\", 271),\n \"Bh\" : Element(\"Bohrium\", \"Bh\", 272),\n \"Hs\" : Element(\"Hassium\", \"Hs\", 270),\n \"Mt\" : Element(\"Meitnerium\", \"Mt\", 276),\n \"Ds\" : Element(\"Darmstadtium\", \"Ds\", 281),\n \"Rg\" : Element(\"Roentgenium\", \"Rg\", 280),\n \"Cn\" : Element(\"Copernicium\", \"Cn\", 285),\n \"Nh\" : Element(\"Nihonium\", \"Nh\", 284),\n \"Fl\" : Element(\"Flerovium\", \"Fl\", 289),\n \"Mc\" : Element(\"Moscovium\", \"Mc\", 288),\n \"Lv\" : Element(\"Livermorium\", \"Lv\", 293),\n \"Ts\" : Element(\"Tennessine\", \"Ts\", 294),\n \"Og\" : Element(\"Oganesson\", \"Og\", 294)\n }\n return table\n\n\nperiodic_table = init_periodic_table()\n\n\ndef get_name(symbol):\n return periodic_table[symbol].name\n\ndef get_atomic_mass(symbol):\n return periodic_table[symbol].atomic_mass\n\n\nclass FormulaError(ValueError):\n pass\n\n\ndef parse_formula(formula):\n def parse_quant(formula, index):\n quant = 1\n if index < len(formula) and formula[index].isdecimal():\n start = index\n index += 1\n while index < len(formula) and formula[index].isdecimal():\n index += 1\n quant = int(formula[start:index])\n return quant, index\n\n def get_quant(elems, symbol):\n return 0 if symbol not in elems else elems[symbol]\n\n def parse_r(formula, index, level):\n start_index = index\n start_level = level\n elems = {} \n while index < len(formula):\n ch = formula[index]\n if ch == \"(\":\n group, index = parse_r(formula, index + 1, level + 1)\n quant, index = parse_quant(formula, index)\n for symbol in group:\n prev = get_quant(elems, symbol)\n elems[symbol] = prev + group[symbol] * quant\n elif ch.isalpha():\n symbol = formula[index:index+2]\n if symbol in periodic_table:\n index += 2\n else:\n symbol = formula[index:index+1]\n if symbol in periodic_table:\n index += 1\n else:\n raise FormulaError(\"invalid formula:\", formula, index)\n quant, index = parse_quant(formula, index)\n prev = get_quant(elems, symbol)\n elems[symbol] = prev + quant\n elif ch == \")\":\n if level == 0:\n raise FormulaError(\"invalid formula:\", formula, index)\n level -= 1\n index += 1\n break\n else:\n raise FormulaError(\"invalid formula:\", formula, index)\n if level > 0 and level >= start_level:\n raise FormulaError(\"invalid formula:\", formula, start_index - 1)\n return elems, index\n\n elems, _ = parse_r(formula, 0, 0)\n return elems\n\n\ndef molar_mass(symbol_quantity_dict):\n total_mass = 0\n for symbol, quantity in symbol_quantity_dict.items():\n atomic_mass = get_atomic_mass(symbol)\n total_mass += atomic_mass * quantity\n return total_mass\n\ndef mole_calc(grams, mol_mass):\n mol_total = grams / mol_mass\n return round(mol_total,5)\n\n\n\ndef main():\n true_mol = False\n while not true_mol:\n new_mol = input(\"\\n What is the molecule you are calculating: \")\n\n try:\n new_parse = parse_formula(new_mol)\n\n except Exception as ex:\n print(f\"{ex.args[1]} is invalid. Please input a valid molecule\")\n else:\n true_mol = True\n \n new_mm = molar_mass(new_parse)\n print (f\"\\n The molar mass of the molecule {new_mol} is {round(new_mm,5)}.\\n\")\n true_grams = False\n while not true_grams:\n grams = input(f\"How many grams do you have of {new_mol}: \")\n try:\n grams = float(grams)\n except Exception as ex:\n print(\"Please give a real value of grams.\")\n else:\n true_grams = True\n\n moles = mole_calc(grams, new_mm)\n print(f\"\\n You have {round(moles,5)} moles of {new_mol}.\\n\")\n \nmain()","sub_path":"chemistry.py","file_name":"chemistry.py","file_ext":"py","file_size_in_byte":9772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"538165410","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\ndef modfunct(a,b):\n try:\n Div = a // b\n print(\"Valid result :\", Div)\n except:\n print (\"Invalid denominator\")\n\nmodfunct(6,3)\nmodfunct(4,0)\n\n\n# In[2]:\n\n\nclass Countries:\n def __init__(self,con1,con2):\n self.con1 = con1\n self.con2 = con2\nclass Verbs:\n def __init__(self,v1,v2,):\n self.v1 = v1\n self.v2 = v2\n \nclass Obj:\n def __init__(self,o1,o2):\n self.o1 = o1\n self.o2 = o2\n \nc = Countries (\"Americans\",\"Indians\") \nv = Verbs(\"Play\",\"Watch\")\no = Obj(\"Baseball\",\"Cricket\")\nprint(c.con1 + ' ' +v.v1+ ' '+o.o1)\nprint(c.con1 + ' ' +v.v1+ ' '+o.o2)\nprint(c.con1 + ' ' +v.v2+ ' '+o.o1)\nprint(c.con1 + ' ' +v.v2+ ' '+o.o2)\nprint(c.con2 + ' ' +v.v1+ ' '+o.o1)\nprint(c.con2 + ' ' +v.v1+ ' '+o.o2)\nprint(c.con2 + ' ' +v.v2+ ' '+o.o1)\nprint(c.con2 + ' ' +v.v2+ ' '+o.o2)\n\n\n# In[2]:\n\n\nimport numpy as np\nl = np.array([1,2,3,4])\nm = 4\nnp.vander(l,m)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Assignment3.ashish.py","file_name":"Assignment3.ashish.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"115635880","text":"#!/usr/bin/env python\n\nimport copy\nimport actionlib\nimport rospy\nimport time\nfrom math import sin, cos\nfrom moveit_python import (MoveGroupInterface,\n PlanningSceneInterface,\n PickPlaceInterface)\nfrom moveit_python.geometry import rotate_pose_msg_by_euler_angles\n\nfrom control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal\nfrom control_msgs.msg import PointHeadAction, PointHeadGoal, GripperCommandAction, GripperCommandGoal\nfrom grasping_msgs.msg import FindGraspableObjectsAction, FindGraspableObjectsGoal\nfrom geometry_msgs.msg import PoseStamped, Quaternion, Point, Pose, Vector3\nfrom tf.transformations import quaternion_from_euler\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nfrom moveit_msgs.msg import PlaceLocation, MoveItErrorCodes\nfrom trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint\n\nfrom transformer import Transformer\nfrom tf import transformations\nimport numpy as np\n\n\nclass PlanningSceneClient(object):\n '''Define ground plane\n This creates objects in the planning scene that mimic the ground\n If these were not in place gripper could hit the ground'''\n\n def __init__(self):\n self.planning_scene = PlanningSceneInterface(\"base_link\")\n self.planning_scene.removeCollisionObject(\"my_front_ground\")\n self.planning_scene.removeCollisionObject(\"my_back_ground\")\n self.planning_scene.removeCollisionObject(\"my_right_ground\")\n self.planning_scene.removeCollisionObject(\"my_left_ground\")\n self.planning_scene.addCube(\"my_front_ground\", 2, 1.1, 0.0, -1.0)\n self.planning_scene.addCube(\"my_back_ground\", 2, -1.2, 0.0, -1.0)\n self.planning_scene.addCube(\"my_left_ground\", 2, 0.0, 1.2, -1.0)\n self.planning_scene.addCube(\"my_right_ground\", 2, 0.0, -1.2, -1.0)\n\n def close(self):\n self.planning_scene.removeCollisionObject(\"my_front_ground\")\n self.planning_scene.removeCollisionObject(\"my_back_ground\")\n self.planning_scene.removeCollisionObject(\"my_right_ground\")\n self.planning_scene.removeCollisionObject(\"my_left_ground\")\n\n\nclass GripperController(object):\n\n def __init__(self):\n self.client = actionlib.SimpleActionClient(\n \"gripper_controller/gripper_action\", GripperCommandAction)\n rospy.loginfo(\"Waiting for gripper_action...\")\n self.move_group = MoveGroupInterface(\"arm_with_torso\", \"base_link\")\n self.goal = GripperCommandGoal()\n\n self.client.wait_for_server()\n\n def close(self):\n '''Close the gripper'''\n self.goal.command.position = 0\n self.goal.command.max_effort = 100\n self.client.send_goal(self.goal)\n self.client.wait_for_result()\n\n def release(self):\n '''Release the gripper'''\n self.goal.command.position = 1\n self.goal.command.max_effort = 100\n self.client.send_goal(self.goal)\n self.client.wait_for_result()\n\n def tuck(self):\n '''Tuck the arm of fetch'''\n position = (0.0555, -0.138, 0.571)\n quaternion = (0.45848, -0.50438, 0.5078, 0.5268)\n self.move_to_pose(position, quaternion)\n\n def move_to_pose(self, postion, quaternion, frame='base_link'):\n target_frame = 'wrist_roll_link'\n\n pose_stamped = PoseStamped()\n pose_stamped.header.frame_id = frame\n pose_stamped.header.stamp = rospy.Time.now()\n pose_stamped.pose = Pose(\n Point(postion[0], postion[1], postion[2]),\n Quaternion(quaternion[0], quaternion[1],\n quaternion[2], quaternion[3])\n )\n if not rospy.is_shutdown():\n self.move_group.moveToPose(pose_stamped, target_frame)\n result = self.move_group.get_move_action().get_result()\n if result:\n if result.error_code.val == MoveItErrorCodes.SUCCESS:\n rospy.loginfo(\"Move success!\")\n else:\n rospy.logerr(\"in state: %s\",\n self.move_group.get_move_action().get_state())\n else:\n rospy.logerr(\"MoveIt! failure no result returned.\")\n # self.move_group.get_move_action().cancel_all_goals()\n\n def move_to_some_pose(self, postion, direction, frame='base_link'):\n target_frame = 'wrist_roll_link'\n quatrenion = Transformer().quaternion_from_direction((1, 0, 0), direction)\n\n pose_stamped = PoseStamped()\n pose_stamped.header.frame_id = frame\n pose_stamped.header.stamp = rospy.Time.now()\n pose_stamped.pose = Pose(\n Point(postion[0], postion[1], postion[2]),\n quatrenion\n )\n if not rospy.is_shutdown():\n self.move_group.moveToPose(pose_stamped, target_frame)\n result = self.move_group.get_move_action().get_result()\n if result:\n if result.error_code.val == MoveItErrorCodes.SUCCESS:\n rospy.loginfo(\"See!\")\n else:\n rospy.logerr(\"in state: %s\",\n self.move_group.get_move_action().get_state())\n else:\n rospy.logerr(\"MoveIt! failure no result returned.\")\n self.move_group.get_move_action().cancel_all_goals()\n\n def wave(self):\n '''Just for fun'''\n gripper_poses = [((0.347, 0.045, 1.022), (-0.174, -0.301, 0.273, 0.635)),\n ((0.347, 0.245, 1.022), (-0.274, -0.701, 0.173, 0.635))\n ]\n for i in range(5):\n for pose in gripper_poses:\n self.move_to_pose(pose[0], pose[1])\n self.stop()\n\n def stop(self):\n \"\"\"This stops all arm movement goals\n It should be called when a program is exiting so movement stops\n \"\"\"\n self.move_group.get_move_action().cancel_all_goals()\n\n\nclass HeadController(object):\n def __init__(self):\n self.client = actionlib.SimpleActionClient(\n \"head_controller/point_head\", PointHeadAction)\n rospy.loginfo(\"Waiting for head_controller...\")\n self.client.wait_for_server()\n\n def look_at(self, x, y, z, frame, duration=1.0):\n goal = PointHeadGoal()\n goal.target.header.stamp = rospy.Time.now()\n goal.target.header.frame_id = frame\n goal.target.point.x = x\n goal.target.point.y = y\n goal.target.point.z = z\n goal.min_duration = rospy.Duration(duration)\n goal.pointing_frame = \"head_tilt_link\"\n self.client.send_goal(goal)\n self.client.wait_for_result()\n\n\nif __name__ == \"__main__\":\n\n rospy.init_node(\"demo\")\n\n # tf = Transformer()\n p = HeadController()\n p.look_at(0.8, 0.1, 0.72, 'base_link')\n # g = GripperController()\n # g.wave()\n # g.tuck()\n # g.stop()\n # g.move_to_some_pose((0.5, 0, 1), (1, 0, 0))\n # p.look_at(0.8, -0.1, 0.72, 'base_link')\n\n # while True:\n # transform_matrix = tf.transformMatrix('base_link', 'head_tilt_link')\n # print transform_matrix\n # p = raw_input(\"Input position: \")\n # try:\n # point = [ float(i) for i in p.split() ]\n # except:\n # break\n\n # ac.look_at(point[0], point[1], point[2], \"base_link\")\n","sub_path":"FETCH_CODE/fetch_src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"480643451","text":"#coding=utf-8\r\n\r\n\"\"\"travel_notes URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path,include,re_path\r\n\r\nfrom operation.views import index\r\n# import xadmin\r\n\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n # path('xadmin/', xadmin.site.urls),\r\n re_path('^$', index,name='index'),\r\n path('user/', include('user.urls'), name='user'),\r\n path(r'tinymce/', include('tinymce.urls')),\r\n path('active/', include('EmailVerifyRecord.urls'),name='active'),\r\n path('operation/', include('operation.urls'), name='operation'),\r\n path('article/', include('article.urls'), name='article'),\r\n]\r\n","sub_path":"travel_notes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"413842379","text":"# File that is run to verify that our servos are working\n#!/usr/bin/python3\nfrom adafruit_servokit import ServoKit\nfrom pyPS4Controller.controller import Controller\nfrom board import SCL_1, SDA_1\nimport busio\n\nMIN_PULSE_WIDTH = 500 # Hz\nMAX_PULSE_WIDTH = 2500 # Hz\n\nMAX_ACTUATION_RANGE = 270 # Degrees\nX_SERVO_INDEX = 0 # Index refers to the servo controller board\nY_SERVO_INDEX = 1 # Index refers to the servo controller board\n\n# Creation of servo kit\ni2c = busio.I2C(SCL_1, SDA_1)\nkit = ServoKit(channels = 8, i2c = i2c, address = 0x40)\n\nkit.servo[0].actuation_range = MAX_ACTUATION_RANGE\nkit.servo[1].actuation_range = MAX_ACTUATION_RANGE\n\nkit.servo[0].set_pulse_width_range(MIN_PULSE_WIDTH, MAX_PULSE_WIDTH)\nkit.servo[1].set_pulse_width_range(MIN_PULSE_WIDTH, MAX_PULSE_WIDTH)\n\n#teleop = Teleop(interface=\"/dev/input/js0\", connecting_using_ds4drv=False)\n\ndef cycleTest():\n #Cycle through various angles for each servo until a keyboard interrupt\n try: \n while True:\n kit.servo[0].angle = 30\n kit.servo[0].angle = 60\n kit.servo[0].angle = 90\n kit.servo[0].angle = 120\n kit.servo[0].angle = 150\n kit.servo[0].angle = 180\n kit.servo[0].angle = 210\n kit.servo[0].angle = 240\n kit.servo[0].angle = 135\n\n kit.servo[1].angle = 30\n kit.servo[1].angle = 60\n kit.servo[1].angle = 90\n kit.servo[1].angle = 120\n kit.servo[1].angle = 150\n kit.servo[1].angle = 180\n kit.servo[1].angle = 210\n kit.servo[1].angle = 240\n kit.servo[1].angle = 135\n except KeyboardInterrupt:\n print(\"Stopping Cycle Test\")\n\ndef manualTest():\n try:\n while True:\n print(\"Pan Servo - 1\")\n print(\"Tilt Servo - 2\")\n servo = input(\"Servo?: \")\n print(\"\\nAngle range - (0 - 270)\")\n angle = input(\"Angle?: \")\n\n if(int(angle) < 271 and int(angle) > 0):\n if(int(servo) == 1):\n kit.servo[X_SERVO_INDEX].angle = int(angle)\n \n elif(int(servo) == 2):\n kit.servo[Y_SERVO_INDEX].angle = int(angle)\n else:\n print(\"Impossible angle requested\")\n \n\n finally:\n (\"Stopping Manual Test\")\n\nif __name__ == \"__main__\":\n\n kit.servo[0].angle = 135\n kit.servo[1].angle = 135\n\n print(\"Cycle Test - 1\")\n print(\"Manual Test - 2\")\n print(\"Teleop Test - 3\")\n choice = input(\"?: \")\n\n if(int(choice) == 1):\n cycleTest()\n\n elif(int(choice) == 2):\n manualTest()\n\n\n \n","sub_path":"scripts/servo_test.py","file_name":"servo_test.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"475941466","text":"# GNN that attempts to match clusters to groups\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport torch\nimport numpy as np\nfrom torch.nn import Sequential as Seq, Linear as Lin, ReLU, Sigmoid, LeakyReLU, Dropout, BatchNorm1d\nfrom torch_geometric.nn import MetaLayer, EdgeConv\n\nfrom .edge_pred import EdgeModel, BilinEdgeModel\n\nclass EdgeConvModel(torch.nn.Module):\n \"\"\"\n Simple GNN with several edge convolutions, followed by MetLayer for edge prediction\n \n for use in config\n model:\n modules:\n edge_model:\n name: econv\n \"\"\"\n def __init__(self, cfg):\n super(EdgeConvModel, self).__init__()\n \n \n if 'modules' in cfg:\n self.model_config = cfg['modules']['attention_gnn']\n else:\n self.model_config = cfg\n \n \n self.aggr = self.model_config.get('aggr', 'max')\n self.leak = self.model_config.get('leak', 0.1)\n \n self.node_in = self.model_config.get('node_feats', 16)\n self.edge_in = self.model_config.get('edge_feats', 10)\n \n # perform batch normalization\n self.bn_node = BatchNorm1d(self.node_in)\n self.bn_edge = BatchNorm1d(self.edge_in)\n \n # go from 16 to 24 node features\n ninput = self.node_in\n noutput = 24\n self.nn0 = Seq(\n Lin(2*ninput, 2*noutput),\n LeakyReLU(self.leak),\n Lin(2*noutput, noutput),\n LeakyReLU(self.leak),\n Lin(noutput, noutput)\n )\n self.layer0 = EdgeConv(self.nn0, aggr=self.aggr)\n \n # go from 24 to 32 node features\n ninput = 24\n noutput = 32\n self.nn1 = Seq(\n Lin(2*ninput, 2*noutput),\n LeakyReLU(self.leak),\n Lin(2*noutput, noutput),\n LeakyReLU(self.leak),\n Lin(noutput, noutput)\n )\n self.layer1 = EdgeConv(self.nn1, aggr=self.aggr)\n \n # go from 32 to 64 node features\n ninput = 32\n noutput = 64\n self.nn2 = Seq(\n Lin(2*ninput, 2*noutput),\n LeakyReLU(self.leak),\n Lin(2*noutput, noutput),\n LeakyReLU(self.leak),\n Lin(noutput, noutput)\n )\n self.layer2 = EdgeConv(self.nn2, aggr=self.aggr)\n\n # final prediction layer\n pred_cfg = self.model_config.get('pred_model', 'basic')\n if pred_cfg == 'basic':\n self.edge_predictor = MetaLayer(EdgeModel(noutput, self.edge_in, self.leak))\n elif pred_cfg == 'bilin':\n self.edge_predictor = MetaLayer(BilinEdgeModel(noutput, self.edge_in, self.leak))\n else:\n raise Exception('unrecognized prediction model: ' + pred_cfg)\n\n\n def forward(self, x, edge_index, e, xbatch):\n \"\"\"\n inputs data:\n x - vertex features\n edge_index - graph edge list\n e - edge features\n xbatch - node batchid\n \"\"\"\n \n # batch normalization of node features\n x = self.bn_node(x)\n # batch normalization of edge features\n e = self.bn_edge(e)\n \n # go through layers\n x = self.layer0(x, edge_index)\n \n x = self.layer1(x, edge_index)\n\n x = self.layer2(x, edge_index)\n \n x, e, u = self.edge_predictor(x, edge_index, e, u=None, batch=xbatch)\n\n return {'edge_pred':[e]}\n","sub_path":"mlreco/models/gnn/edge_econv.py","file_name":"edge_econv.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"301098690","text":"#\n# Copyright (c) 2015 Red Hat, Inc.\n#\n# Author: Loic Dachary \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\nimport argparse\nimport logging\nimport os\nimport pytest\nimport tempfile\nfrom mock import patch\n\nimport teuthology\nfrom teuthology import misc\nfrom teuthology.openstack import TeuthologyOpenStack, OpenStack\nimport scripts.openstack\n\nclass TestOpenStack(object):\n\n def test_interpret_hints(self):\n defaults = {\n 'machine': {\n 'ram': 0,\n 'disk': 0,\n 'cpus': 0,\n },\n 'volumes': {\n 'count': 0,\n 'size': 0,\n },\n }\n expected_disk = 10 # first hint larger than the second\n expected_ram = 20 # second hint larger than the first\n expected_cpus = 0 # not set, hence zero by default\n expected_count = 30 # second hint larger than the first\n expected_size = 40 # does not exist in the first hint\n hints = [\n {\n 'machine': {\n 'ram': 2,\n 'disk': expected_disk,\n },\n 'volumes': {\n 'count': 9,\n 'size': expected_size,\n },\n },\n {\n 'machine': {\n 'ram': expected_ram,\n 'disk': 3,\n },\n 'volumes': {\n 'count': expected_count,\n },\n },\n ]\n hint = OpenStack().interpret_hints(defaults, hints)\n assert hint == {\n 'machine': {\n 'ram': expected_ram,\n 'disk': expected_disk,\n 'cpus': expected_cpus,\n },\n 'volumes': {\n 'count': expected_count,\n 'size': expected_size,\n }\n }\n assert defaults == OpenStack().interpret_hints(defaults, None)\n\n def test_set_provider(self):\n auth = os.environ.get('OS_AUTH_URL', None)\n os.environ['OS_AUTH_URL'] = 'cloud.ovh.net'\n assert OpenStack().set_provider() == 'ovh'\n if auth != None:\n os.environ['OS_AUTH_URL'] = auth\n else:\n del os.environ['OS_AUTH_URL']\n\n def test_get_ip_neutron(self):\n instance_id = '8e1fd70a-3065-46f8-9c30-84dc028c1834'\n ip = '10.10.10.4'\n def sh(cmd):\n if 'neutron subnet-list' in cmd:\n return \"\"\"\n[\n {\n \"ip_version\": 6,\n \"id\": \"c45b9661-b2ba-4817-9e3a-f8f63bf32989\"\n },\n {\n \"ip_version\": 4,\n \"id\": \"e03a3dbc-afc8-4b52-952e-7bf755397b50\"\n }\n]\n \"\"\"\n elif 'neutron port-list' in cmd:\n return (\"\"\"\n[\n {\n \"device_id\": \"915504ad-368b-4cce-be7c-4f8a83902e28\",\n \"fixed_ips\": \"{\\\\\"subnet_id\\\\\": \\\\\"e03a3dbc-afc8-4b52-952e-7bf755397b50\\\\\", \\\\\"ip_address\\\\\": \\\\\"10.10.10.1\\\\\"}\\\\n{\\\\\"subnet_id\\\\\": \\\\\"c45b9661-b2ba-4817-9e3a-f8f63bf32989\\\\\", \\\\\"ip_address\\\\\": \\\\\"2607:f298:6050:9afc::1\\\\\"}\"\n },\n {\n \"device_id\": \"{instance_id}\",\n \"fixed_ips\": \"{\\\\\"subnet_id\\\\\": \\\\\"e03a3dbc-afc8-4b52-952e-7bf755397b50\\\\\", \\\\\"ip_address\\\\\": \\\\\"{ip}\\\\\"}\\\\n{\\\\\"subnet_id\\\\\": \\\\\"c45b9661-b2ba-4817-9e3a-f8f63bf32989\\\\\", \\\\\"ip_address\\\\\": \\\\\"2607:f298:6050:9afc:f816:3eff:fe07:76c1\\\\\"}\"\n },\n {\n \"device_id\": \"17e4a968-4caa-4cee-8e4b-f950683a02bd\",\n \"fixed_ips\": \"{\\\\\"subnet_id\\\\\": \\\\\"e03a3dbc-afc8-4b52-952e-7bf755397b50\\\\\", \\\\\"ip_address\\\\\": \\\\\"10.10.10.5\\\\\"}\\\\n{\\\\\"subnet_id\\\\\": \\\\\"c45b9661-b2ba-4817-9e3a-f8f63bf32989\\\\\", \\\\\"ip_address\\\\\": \\\\\"2607:f298:6050:9afc:f816:3eff:fe9c:37f0\\\\\"}\"\n }\n]\n \"\"\".replace('{instance_id}', instance_id).\n replace('{ip}', ip))\n else:\n raise Exception(\"unexpected \" + cmd)\n with patch.multiple(\n misc,\n sh=sh,\n ):\n assert ip == OpenStack.get_ip_neutron(instance_id)\n\nclass TestTeuthologyOpenStack(object):\n\n @classmethod\n def setup_class(self):\n if 'OS_AUTH_URL' not in os.environ:\n pytest.skip('no OS_AUTH_URL environment variable')\n\n teuthology.log.setLevel(logging.DEBUG)\n teuthology.misc.read_config(argparse.Namespace())\n\n ip = TeuthologyOpenStack.create_floating_ip()\n if ip:\n ip_id = TeuthologyOpenStack.get_floating_ip_id(ip)\n misc.sh(\"openstack ip floating delete \" + ip_id)\n self.can_create_floating_ips = True\n else:\n self.can_create_floating_ips = False\n \n def setup(self):\n self.key_filename = tempfile.mktemp()\n self.key_name = 'teuthology-test'\n self.name = 'teuthology-test'\n self.clobber()\n misc.sh(\"\"\"\nopenstack keypair create {key_name} > {key_filename}\nchmod 600 {key_filename}\n \"\"\".format(key_filename=self.key_filename,\n key_name=self.key_name))\n self.options = ['--key-name', self.key_name,\n '--key-filename', self.key_filename,\n '--name', self.name,\n '--verbose']\n\n def teardown(self):\n self.clobber()\n os.unlink(self.key_filename)\n\n def clobber(self):\n misc.sh(\"\"\"\nopenstack server delete {name} --wait || true\nopenstack keypair delete {key_name} || true\n \"\"\".format(key_name=self.key_name,\n name=self.name))\n\n def test_create(self, caplog):\n teuthology_argv = [\n '--suite', 'upgrade/hammer',\n '--dry-run',\n '--ceph', 'master',\n '--kernel', 'distro',\n '--flavor', 'gcov',\n '--distro', 'ubuntu',\n '--suite-branch', 'hammer',\n '--email', 'loic@dachary.org',\n '--num', '10',\n '--limit', '23',\n '--subset', '1/2',\n '--priority', '101',\n '--timeout', '234',\n '--filter', 'trasher',\n '--filter-out', 'erasure-code',\n '--throttle', '3',\n ]\n argv = (self.options +\n ['--upload',\n '--archive-upload', 'user@archive:/tmp'] +\n teuthology_argv)\n args = scripts.openstack.parse_args(argv)\n teuthology = TeuthologyOpenStack(args, None, argv)\n teuthology.user_data = 'teuthology/openstack/test/user-data-test1.txt'\n teuthology.teuthology_suite = 'echo --'\n\n teuthology.main()\n assert 'Ubuntu 14.04' in teuthology.ssh(\"lsb_release -a\")\n variables = teuthology.ssh(\"grep 'substituded variables' /var/log/cloud-init.log\")\n assert \"nworkers=\" + str(args.simultaneous_jobs) in variables\n assert \"username=\" + teuthology.username in variables\n assert \"upload=--archive-upload user@archive:/tmp\" in variables\n assert \"clone=git clone\" in variables\n assert os.environ['OS_AUTH_URL'] in variables\n\n assert \" \".join(teuthology_argv) in caplog.text()\n\n if self.can_create_floating_ips:\n ip = teuthology.get_floating_ip(self.name)\n teuthology.teardown()\n if self.can_create_floating_ips:\n assert teuthology.get_floating_ip_id(ip) == None\n\n def test_floating_ip(self):\n if not self.can_create_floating_ips:\n pytest.skip('unable to create floating ips')\n\n expected = TeuthologyOpenStack.create_floating_ip()\n ip = TeuthologyOpenStack.get_unassociated_floating_ip()\n assert expected == ip\n ip_id = TeuthologyOpenStack.get_floating_ip_id(ip)\n misc.sh(\"openstack ip floating delete \" + ip_id)\n","sub_path":"teuthology/openstack/test/test_openstack.py","file_name":"test_openstack.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"562704548","text":"\nfrom eval_sinewave_for_test import eval_sinewave_for_test\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use(['dark_background'])\nimport matplotlib as mpl\n\ncolors = {0:'dodgerblue' , 1: 'tomato' , 2:'forestgreen'}\n\n\ndef compare_maml_and_neural_net(maml, neural_net, sinusoid_generator, num_steps=list(range(10)),\n intermediate_plot=True, marker='x', linestyle='--'):\n '''Compare the loss of a MAML model and a neural net.\n \n Fits the models for a new task (new sine wave) and then plot\n the loss of both models along `num_steps` interactions.\n \n Args:\n maml: An already trained MAML.\n neural_net: An already trained neural net.\n num_steps: Number of steps to be logged.\n intermediate_plot: If True plots intermediate plots from\n `eval_sinewave_for_test`.\n marker: Marker used for plotting.\n linestyle: Line style used for plotting.\n '''\n if intermediate_plot:\n print('MAML')\n fit_maml, w3_maml_model, weight_gradient_maml, loss_maml = eval_sinewave_for_test(maml, \n sinusoid_generator, plot=intermediate_plot)\n if intermediate_plot:\n print('Neural Net')\n fit_neural_net, w3_net_model, weight_gradient_net, loss_net = eval_sinewave_for_test(neural_net, \n sinusoid_generator, plot=intermediate_plot)\n \n fit_res = {'MAML': fit_maml, 'Neural Net': fit_neural_net}\n \n legend = []\n fig = plt.figure(figsize=(12, 5), tight_layout=True)\n ax = fig.add_subplot(1,1,1)\n i = 0\n for name in fit_res:\n x = []\n y = []\n for n, _, loss in fit_res[name]:\n x.append(n)\n y.append(loss)\n ax.plot(x, y, marker=marker, linestyle=linestyle, color=colors[i])\n i+=1%3\n ax.set_xticks(num_steps)\n ax.set_ylabel('loss')\n legend.append(name)\n ax.legend(legend)\n plt.show()\n return w3_maml_model, w3_net_model, weight_gradient_net, weight_gradient_maml, loss_net, loss_maml","sub_path":"maml_sin/compare_maml_and_neural_net.py","file_name":"compare_maml_and_neural_net.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"195935139","text":"\"\"\"\nDefines the urls for the views defined in the Server api.\n\"\"\"\nfrom django.urls import path\nfrom django.urls.conf import include\n\nfrom ds_servers.api.views import (AddBlockView, AddCameraView,\n DSServerConfigsListCreateDestroyView,\n DSServerConfigsRetrieveUpdateDestroyView,\n DSServersListCreateDestroyView,\n DSServersRetrieveUpdateDestroyView,\n RemoveBlockView, RemoveCameraView)\n\nds_serverpk_urlpatterns = [\n path(\n 'config/', include([\n path(\n '',\n DSServerConfigsListCreateDestroyView.as_view(),\n name='ds_server_config_list_create_delete'),\n path(\n '/',\n DSServerConfigsRetrieveUpdateDestroyView.as_view(),\n name='ds_server_config_retrieve_update_destroy'),\n path(\n '/cameras/add',\n AddCameraView.as_view(),\n name='ds_server_config_add_camera'),\n path(\n '/cameras/remove',\n RemoveCameraView.as_view(),\n name='ds_server_config_remove_camera'),\n path(\n '/blocks/add',\n AddBlockView.as_view(),\n name='ds_server_config_add_block'),\n path(\n '/blocks/remove',\n RemoveBlockView.as_view(),\n name='ds_server_config_remove_block'),\n ])),\n]\n\nurlpatterns = [\n path(\n '',\n DSServersListCreateDestroyView.as_view(),\n name='ds_servers_list_create_delete'),\n path(\n '/',\n DSServersRetrieveUpdateDestroyView.as_view(),\n name='ds_servers_retrieve_update_delete'),\n path('/', include(ds_serverpk_urlpatterns))\n]\n","sub_path":"ds_servers/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"137945317","text":"import cv2\nimport math\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nIE = 1.767145\nUMPX = 3.7\n\ndef plotGray(img):\n im = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n plt.imshow(im)\n\ndef findContours(img):\n if (cv2.__version__ == '4.1.1'):\n contours, hier = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n return contours\n else:\n _, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n return contours\n \n\ndef calcIslets(img, low=230, high=255):\n mask = cv2.inRange(img, low, high)\n contours = findContours(mask)\n areas = [contourArea(cont) for cont in contours] \n volumes = [calcEllipseArea(cont) for cont in contours] \n return (len(contours), areas, volumes)\n\n\ndef calcEllipseArea(cont, ie = IE, umpx=UMPX):\n try:\n ellipse = cv2.fitEllipse(cont)\n _, (w, h), _ = ellipse\n a = (w*umpx)/2\n b = (h*umpx)/2\n area = math.pi * a * b\n return area * ie\n except Exception as e:\n return 0\n\ndef contourArea(cont, ie = IE, umpx=UMPX):\n area = cv2.contourArea(cont)\n return area * umpx * ie \n\ndef calcEllipseVolume(cont, ie = IE, umpx=UMPX):\n ellipse = cv2.fitEllipse(cont)\n _, (w_px, h_px), _ = ellipse\n w_um = w_px * umpx\n h_um = h_px * umpx\n a = (w_um)/2\n b = (h_um)/2\n vol = 4/3*math.pi * a/2 * (b/2)**2\n return vol * ie\n\n\ndef batchCalc(imgs, names):\n cnts = []\n areass = [] \n volumess = []\n purs = []\n\n #print(\"cnt\", \"\\t\", \"purity\")\n\n for i, img in enumerate(imgs):\n try:\n #img = cv2.imread(p, cv2.IMREAD_GRAYSCALE)\n cnt, areas, volumes = calcIslets(img)\n vol_sum = sum(volumes)\n pur = calcPurity(img)\n\n cnts.append(cnt)\n areass.append(areas)\n volumess.append(vol_sum)\n purs.append(pur)\n name = os.path.basename(names[i])\n #print(cnt, \"\\t\", round(pur, 2), \"\\t\", name)\n except Exception as e:\n print(names[i])\n raise\n\n return (cnts, purs, volumess)\n\ndef calcPurity(img):\n mask_islets = cv2.inRange(img, 255, 255)\n mask_exo = cv2.inRange(img, 1, 254)\n contours_islets = findContours(mask_islets)\n contours_exo = findContours(mask_exo)\n islets_area = sum([contourArea(cont) for cont in contours_islets])\n exo_area = sum([contourArea(cont) for cont in contours_exo])\n\n return islets_area / (islets_area + exo_area)\n\n\ndef pil2cv(pil_img):\n return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY)\n","sub_path":"u2net/calcs.py","file_name":"calcs.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"551155933","text":"# import the necessary tools to parse xml and create a csv file\nimport xml.etree.ElementTree as ET\nimport csv\n\n# parse the xml file\ntree = ET.parse(\"nextBus.xml\")\nroot = tree.getroot()\n\n# open a file for writing\nbus_data = open('nextBus.csv', 'w')\n\n# create the csv writer object\ncsvwriter = csv.writer(bus_data)\nitem_head = []\n\n# use boolean to determine header in loop\nheader = True\n\n# loop through the each route in the root ()\nfor route in root.findall('route'):\n\n\tif header:\n\t\titem_head.append('Bus')\n\t\titem_head.append('Title')\n\t\titem_head.append('Schedule Class')\n\t\titem_head.append('Days')\n\t\titem_head.append('Direction')\n\t\titem_head.append('blockID')\n\t\titem_head.append('Stop Name')\n\t\titem_head.append('Stop Times')\n\t\t# write back to csvwriter\n\t\tcsvwriter.writerow(item_head)\n\t\theader = False\n\t\n\t# save a list of id's to know if they are already added in\n\tid_list = []\n\t\n\t# loop through each in the routes\n\tfor tr in route.findall('tr'):\n\t\tif tr.attrib['blockID'] not in id_list:\n\t\t\t# loop through each stop and add the header info into list\n\t\t\tfor stop in tr.findall('stop'):\n\t\t\t\tbus_info = []\n\t\t\t\tbus = route.attrib['tag']\n\t\t\t\tbus_info.append(bus)\n\t\t\t\ttitle = route.attrib['title']\n\t\t\t\tbus_info.append(title)\n\t\t\t\tschedule = route.attrib['scheduleClass']\n\t\t\t\tbus_info.append(schedule)\n\t\t\t\tdays = route.attrib['serviceClass']\n\t\t\t\tbus_info.append(days)\n\t\t\t\tdirection = route.attrib['direction']\n\t\t\t\tbus_info.append(direction)\n\t\t\t\tblockID = tr.attrib['blockID']\n\t\t\t\tbus_info.append(blockID)\n\t\t\t\tid_list.append(blockID)\n\t\t\t\tstop_n = stop.attrib['tag']\n\t\t\t\tbus_info.append(stop_n)\n\t\t\t\t\n\t\t\t\t# loop allows for stop times to be in the correct order and row\n\t\t\t\tfor second_tr in route.findall('tr'):\n\t\t\t\t\tif second_tr.attrib['blockID'] == tr.attrib['blockID']:\n\t\t\t\t\t\tfor second_stop in second_tr.findall('stop'):\n\t\t\t\t\t\t\tif second_stop.attrib['tag'] == stop.attrib['tag']:\n\t\t\t\t\t\t\t\tbus_info.append(second_stop.text)\n\t\t\t\t\t\t\t\t\n\t\t\t\t# append the bus_info list onto the next row in csv file\t\t\t\t\n\t\t\t\tcsvwriter.writerow(bus_info)\n\n# close the file\nbus_data.close()","sub_path":"nextbus/nextBus.py","file_name":"nextBus.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"373929553","text":"import json\nimport requests\nfrom Vitals import *\n\ndef main1():\n url = \"https://global.api.pvp.net/api/lol/static-data/na/v1.2/item?api_key=\" + KEY\n response = getURL(url).json()\n nameToId = {}\n idToName = {}\n for each in list(response['data']):\n nameToId[response['data'][each]['name']] = response['data'][each]['id']\n idToName[response['data'][each]['id']] = response['data'][each]['name']\n saveFile(\"Data\", \"itemNameToId\", \"json\", nameToId)\n saveFile(\"Data\", \"itemIdToName\", \"json\", idToName)\n\ndef main2():\n response1 = loadJSON(\"Data\", \"itemNameToId\")\n response2 = loadJSON(\"Data\", \"itemIdToName\")\n print(response1['Thornmail'])\n print(response2['3075'])\n\nmain2()\n","sub_path":"createItemDictionaries.py","file_name":"createItemDictionaries.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"423727091","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Mrlun\"\n# Date: 2017/7/4\nimport os\nimport sys\nimport pickle\nBasepath=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(Basepath)\nfrom login import login\nfrom src import register\nif __name__ == '__main__':\n while True:\n print('''======家里蹲大学选课系统======\n1.学生登录\n2.教师登录\n3.学生注册\n4.教师注册\n5.管理员登陆\n6.退出\n''')\n cmd_num=input('>>>:').strip()\n if cmd_num == '1':\n login.student_login()\n elif cmd_num == '2':\n login.teacher_login()\n elif cmd_num == '3':\n register.Student_register()\n elif cmd_num == '4':\n register.Teacher_register()\n elif cmd_num == '5':\n login.admin_login()\n elif cmd_num == '6':\n break\n else:\n print(\"请输入���确的数字!!!\")\n print()\n continue","sub_path":"D20170707ChoseCourseHomeWork/cll选课系统/bin/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250402340","text":"\"\"\"Class for building DCJ test executables.\"\"\"\nfrom os import path\n\n\nclass Build(object):\n \"\"\"A class for building DCJ test executables.\"\"\"\n\n def __init__(self, config):\n self._command_executor = lambda x: None\n self._script_creator = lambda x, y: None\n self._config = config\n\n def SetCommandExecutor(self, command_executor):\n self._command_executor = command_executor\n\n def SetScriptCreator(self, script_creator):\n self._script_creator = script_creator\n\n def AddToParser(self, parser):\n \"\"\"Adds flags to parser and returns it.\"\"\"\n parser.add_argument('--source', required=True,\n help='source file of the solution.')\n parser.add_argument('--language',\n help='language of the solution. Valid choices are: '\n '{0}. If the flag is not provided language will be '\n 'deduced from source file extensions.'\n .format(\n ', '.join(self._SUPPORTED_LANGUAGE_TO_EXTENSION))\n )\n parser.add_argument('--library',\n help='source file of library generating input.')\n parser.add_argument('--executable',\n help='path of the executable to be built. By default '\n 'it\\'s the same as path of source with removed '\n 'filename extension.')\n parser.add_argument('--extra_flags',\n help='comma-separated list of additional flags to pass '\n 'to compiler. For '\n 'example --extra_flags=\"-Wall,-Wextra\".')\n return parser\n\n def Run(self, args):\n # (jabrtosik): When running python tell user / check if file meets\n # necessary conditions:\n # * Is executable.\n # * First line is #!/path/to/interpreter.\n self._ValidateArgs(args)\n source_extension = self._SourceExtension(args)\n commands_builder = self._BUILDER_FOR_EXTENSION[source_extension]\n for command in commands_builder(self, args):\n if self._command_executor(command) != 0:\n raise RuntimeError('Build failed.')\n\n def Description(self):\n return 'Builds solution for local testing.'\n\n def _ValidateArgs(self, args):\n \"\"\"Validate arguments.\n\n Args:\n args: arguments to be validated.\n\n Raises:\n ValueError: exception with string describing the problem detected.\n \"\"\"\n if 'language' in args and args['language']:\n if args['language'] not in self._SUPPORTED_LANGUAGE_TO_EXTENSION:\n raise ValueError('--language must be one of {0!r} but it was {1!r}.'\n .format(self._SUPPORTED_LANGUAGE_TO_EXTENSION.keys(),\n args['language']))\n else:\n # Skip file extension validations.\n return\n\n source_extension = self._SourceExtension(args)\n\n if source_extension not in self._BUILDER_FOR_EXTENSION:\n raise ValueError('Source extension must be one of {0!r} but it was {1!r}.'\n .format(self._BUILDER_FOR_EXTENSION.keys(),\n source_extension))\n\n if self._HasLibrary(args):\n library_extension = self._LibraryExtension(args)\n\n if source_extension == '.c':\n if library_extension != '.c' and library_extension != '.h':\n raise ValueError('C solutions should have a .h or .c library')\n elif source_extension == '.cc' or source_extension == '.cpp':\n if (library_extension != '.cc' and library_extension != '.cpp' and\n library_extension != '.c' and library_extension != '.h'):\n raise ValueError('C++ solutions should have a .cc/.cpp or .h library')\n elif source_extension == '.py':\n if library_extension != '.py':\n raise ValueError('Python solutions should have a .py library')\n elif source_extension == '.java':\n if library_extension != '.java':\n raise ValueError('Java solutions should have a .java library')\n\n def _CBuildCommands(self, args):\n \"\"\"Prepare commands to build solution written in C.\n\n Args:\n args: arguments of the build.\n\n Returns:\n tuple in which each item is a tuple with command that will execute a step\n of building solution.\n \"\"\"\n compiler = self._config.GetStringConfigValue('c-compiler')\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n include_dir = path.join(dcj_root, 'includes')\n local_zeus_path = path.join(dcj_root, 'libraries', 'zeus_local.c')\n message_path = path.join(dcj_root, 'libraries', 'message_internal.c')\n # (jbartosik): support compilers that don't have -I flag for include\n # dirs.\n compiler_args = (\n self._config.GetStringListConfigValue('c-compiler-flags') + [\n '-I' + include_dir,\n local_zeus_path, message_path,\n ]\n )\n if self._HasLibrary(args):\n compiler_args += [args['library']]\n build_solution_command = (\n (compiler,) + tuple(compiler_args) + self.ExtraFlags(args) +\n (args['source'], '-o', self.ExecutablePath(args),)\n )\n\n return (build_solution_command,)\n\n def _CcBuildCommands(self, args):\n \"\"\"Prepare commands to build solution written in C++.\n\n Args:\n args: arguments of the build.\n\n Returns:\n tuple in which each item is a tuple with command that will execute a step\n of building solution.\n \"\"\"\n # (jbartosik): support other compilers.\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n include_dir = path.join(dcj_root, 'includes')\n c_compiler_with_flags = tuple(\n [self._config.GetStringConfigValue('c-compiler')] +\n self._config.GetStringListConfigValue('c-compiler-flags') +\n ['-I' + include_dir]\n )\n cpp_compiler_with_flags = tuple(\n [self._config.GetStringConfigValue('cpp-compiler')] +\n self._config.GetStringListConfigValue('cpp-compiler-flags') +\n ['-I' + include_dir]\n )\n c_sources = (path.join(dcj_root, 'libraries', 'zeus_local.c'),\n path.join(dcj_root, 'libraries', 'message_internal.c'),\n )\n c_object_files_build_commands = tuple(\n c_compiler_with_flags +\n (source_file, '-c', '-o', path.splitext(source_file)[0] + '.o')\n for source_file in c_sources\n )\n object_files = tuple(\n path.splitext(source_file)[0] + '.o' for source_file in c_sources\n )\n\n files = [args['source']]\n if self._HasLibrary(args):\n files += [args['library']]\n\n build_solution_command = (\n cpp_compiler_with_flags + self.ExtraFlags(args) + object_files +\n tuple(files) + ('-o', self.ExecutablePath(args),)\n )\n\n return c_object_files_build_commands + (build_solution_command,)\n\n def _BuildPythonObjectFileCommand(self, c_source, output):\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n return (\n 'gcc', '-c', '-fpic',\n # (jbartosik): Don't rely on users having this exact version of\n # python.\n '-I/usr/include/python2.7',\n '-I' + path.join(dcj_root, 'includes'),\n path.join(dcj_root, 'libraries', c_source),\n '-o', path.join(dcj_root, 'libraries', output),\n )\n\n def _BuildJavaObjectFileCommand(self, c_source, output):\n \"\"\"Return command building .c file to work with Java via SWIG.\"\"\"\n compiler = self._config.GetStringConfigValue('c-compiler')\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n include_dir = path.join(dcj_root, 'includes')\n # (jbartosik): support compilers that don't have -I flag for include\n # dirs.\n compiler_args = (\n '-c', '-fpic',\n '-I' + include_dir,\n )\n java_include_options = tuple(\n [\n '-I' + directory\n for directory in\n self._config.GetDirListConfigValue('java-include-dirs')\n ]\n )\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n return (compiler,) + compiler_args + java_include_options + (\n path.join(dcj_root, 'libraries', c_source),\n '-o', path.join(dcj_root, 'libraries', output),\n )\n\n def _PyBuildCommands(self, unused_args):\n \"\"\"Returns tuple with commands for building Python solutions.\"\"\"\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n\n # (jbartosik): use another directory to store object files.\n build_object_file_commands = tuple(\n self._BuildPythonObjectFileCommand(item + '.c', item + '.o')\n for item in self._MESSAGE_SO_PYTHON_INGREDIENTS)\n\n object_files = tuple(\n path.join(dcj_root, 'libraries', item + '.o')\n for item in self._MESSAGE_SO_PYTHON_INGREDIENTS\n )\n\n link_object_files = (\n ('ld', '-shared',) +\n object_files +\n ('-o', path.join(dcj_root, 'libraries', '_message.so',))\n )\n return build_object_file_commands + (link_object_files,)\n\n def _JavaBuildCommands(self, args):\n \"\"\"Prepare commands to build solution written in Java.\n\n Args:\n args: arguments of the build.\n\n Returns:\n tuple in which each item is a tuple with command that will execute a step\n of building solution.\n \"\"\"\n # Prepare a script that will run java solution. This step is needed because\n # parunner works only with single executable files.\n solution_class_dir = path.dirname(path.realpath(args['source']))\n dcj_root = path.join(path.dirname(path.realpath(__file__)), '..')\n message_dir = path.join(dcj_root, 'libraries')\n library_dir = path.dirname(path.realpath(args['library']))\n classpath = ':'.join((message_dir, library_dir,))\n self._script_creator(\n self.ExecutablePath(args),\n self._config.GetStringConfigValue('java-wrapper-file-content').format(\n solution_class_dir,\n classpath,\n )\n )\n\n # Build message_.o and libmessage.so\n # (jbartosik): deduplicate with Python\n build_object_file_commands = tuple(\n self._BuildJavaObjectFileCommand(item + '.c', item + '.o')\n for item in self._MESSAGE_SO_JAVA_INGREDIENTS)\n\n object_files = [\n path.join(dcj_root, 'libraries', item + '.o')\n for item in self._MESSAGE_SO_JAVA_INGREDIENTS]\n\n link_object_files = tuple(\n [self._config.GetStringConfigValue('java-native-library-linker')] +\n self._config.GetStringListConfigValue(\n 'java-native-library-linker-options') +\n object_files +\n ['-o', path.join(\n dcj_root, 'libraries',\n self._config.GetStringConfigValue('java-native-library-name'),\n )\n ]\n )\n\n # Create a class file to be ran.\n build_class_file_command = (\n self._config.GetStringConfigValue('java-compiler'),\n path.join(dcj_root, 'libraries', 'Wrapper.java'),\n args['source'],\n path.join(dcj_root, 'libraries', 'message.java'),\n path.join(dcj_root, 'libraries', 'messageJNI.java'),\n self._config.GetStringConfigValue('java-compiler-classpath-arg'),\n classpath,\n )\n return (\n build_object_file_commands +\n (link_object_files, build_class_file_command,)\n )\n\n def _SourceExtension(self, args):\n if 'language' in args and args['language']:\n return self._SUPPORTED_LANGUAGE_TO_EXTENSION[args['language']]\n return path.splitext(args['source'])[1]\n\n def _LibraryExtension(self, args):\n return path.splitext(args['library'])[1]\n\n def ExtraFlags(self, args):\n if 'extra_flags' in args and args['extra_flags']:\n return tuple(args['extra_flags'].split(','))\n return ()\n\n def ExecutablePath(self, args):\n if args['executable']:\n return args['executable']\n if self._SourceExtension(args) == '.py':\n return args['source']\n return path.splitext(args['source'])[0]\n\n def _HasLibrary(self, args):\n return 'library' in args and args['library'] is not None\n\n _BUILDER_FOR_EXTENSION = {\n '.c': _CBuildCommands,\n '.cc': _CcBuildCommands,\n '.cpp': _CcBuildCommands,\n '.java': _JavaBuildCommands,\n '.py': _PyBuildCommands,\n }\n\n _MESSAGE_SO_PYTHON_INGREDIENTS = (\n 'message_internal',\n 'message_wrap_python',\n 'zeus_local',\n )\n\n _MESSAGE_SO_JAVA_INGREDIENTS = (\n 'message_internal',\n 'message_wrap_java',\n 'zeus_local',\n )\n\n _SUPPORTED_LANGUAGE_TO_EXTENSION = {\n 'C': '.c',\n 'C++': '.cc',\n 'Java': '.java',\n 'Python': '.py',\n }\n","sub_path":"scripts/dcj/dcj/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":12426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"561505548","text":"from scipy.io import wavfile\r\nimport matplotlib.pyplot as plt \r\nimport numpy as np\r\n\r\nsamplerate, data = wavfile.read('Audio/trai_Heo.wav')\r\ntimes = len(data)/float(samplerate) # độ dài tín hiệu \r\ndt = 1/samplerate \r\n\r\ndata = data / max(data) \r\nSoKhungTinHieu = (int)(times // 0.02) \r\nSoMauTrenKhung = (int)(0.02*16000 )\r\nprint(len(data),SoKhungTinHieu)\r\n\r\nfig, ax = plt.subplots(2)\r\nfig, ax1 = plt.subplots(2)\r\nax[0].plot(data)\r\nax[0].set_title(\"Tín hiệu đầu vào\")\r\nax[0].set_ylabel(\"Amplitidue\")\r\nax[0].set_xlabel(\"Index of sample\")\r\nRt = np.zeros(SoMauTrenKhung+1)\r\n# tính độ trễ trên khung \r\n# khung 105 cuả file studio_male\r\n\r\ndef draw(i):\r\n nL = SoMauTrenKhung*i\r\n nR = SoMauTrenKhung*(i+1)\r\n x = np.arange(SoMauTrenKhung)\r\n ax1[0].plot(x,data[nL:nR])\r\n ax1[0].set_xlabel(\"Frames\")\r\n ax1[0].set_ylabel(\"Amplitidue\")\r\n ax1[0].set_title(\"Khung tín hiệu thứ \" +str(i+1))\r\n\r\ndef hamcucdai(i):\r\n ttq1 = hamtutuongquan(i) # gọi hàm tự tương quan\r\n maxP = nguong_y = 0.5 * ttq1[0] # ngưỡng xác định (giá trị cực đại là giá trị đầu tiên)\r\n P = check = 0\r\n vitri = -1 \r\n for m in range(0,SoMauTrenKhung):\r\n if (ttq1[m] > nguong_y) : # nếu giá trị tự tương quan > ngưỡng thì xét điểm bắt đầu trên ngưỡng\r\n if check == 0 :\r\n check = 1 # đánh dấu để thông báo là đang trên ngưỡng \r\n else :\r\n if (maxP < ttq1[m] and P != 0 and 45 < m < 213): \r\n maxP = ttq1[m]\r\n vitri = m \r\n elif (ttq1[m] < nguong_y and check == 1 ): \r\n if P == 0 : \r\n P = m\r\n check = 0 # đánh dấu để thông báo là đã xuống dưới ngưỡng\r\n new_F0 = 0\r\n T0 = vitri*0.02/SoMauTrenKhung \r\n if T0 < 1/75 and T0 > 1/350 : # điều kiện để tần số nằm trong khoảng 75 < Fs < 350 \r\n new_F0 = 1 / T0 \r\n F0[i] = new_F0\r\n x = np.arange(SoMauTrenKhung)\r\n if (new_F0 == 0) :\r\n ax1[1].set_title(\"Khung tín hiệu \"+ str(i+1)+ \" là vô thanh có tần số \" + str(new_F0))\r\n else : \r\n ax1[1].set_title(\"Khung tín hiệu \"+ str(i+1)+ \" là hữu thanh có tần số \" + str(new_F0))\r\n ax1[1].plot(x,ttq1)\r\n ax1[1].plot(x[vitri],ttq1[vitri],'*') # vẽ tại điểm cực đại cục bộ\r\n ax1[1].set_xlabel(\"Index of sample\")\r\n ax1[1].set_ylabel(\"Herts\")\r\n ax1[1].axhline(y=nguong_y, color='r', linestyle='--') \r\n return new_F0 # giá trị trả về là F0 tại điểm đó\r\n\r\ndef hamtutuongquan(i): \r\n nL = SoMauTrenKhung*i \r\n nR = SoMauTrenKhung*(i+1) \r\n ttq1 = np.zeros(SoMauTrenKhung) # khởi tạo vector lưu các giá trị tự tương quan\r\n tinhieu = data[nL:nR] # khung tín hiệu xét từ vị trí nL -> nR\r\n for x in range(0,SoMauTrenKhung):\r\n for y in range(0,SoMauTrenKhung):\r\n giatri = 0\r\n if x+y < SoMauTrenKhung:\r\n giatri = tinhieu[x+y]\r\n ttq1[x] = ttq1[x] + tinhieu[y]*giatri\r\n return ttq1\r\n\r\n\r\nF0 = np.zeros(SoKhungTinHieu+1)\r\n\r\nfor i in range(0,SoKhungTinHieu) :\r\n ttq1 = hamtutuongquan(i)\r\n maxP = nguong_y = 0.5 * ttq1[0] # ngưỡng xác định \r\n P = check = 0\r\n vitri = -1 \r\n for m in range(0,SoMauTrenKhung):\r\n if (ttq1[m] > nguong_y) :\r\n if check == 0 :\r\n check = 1\r\n else :\r\n if (maxP < ttq1[m] and P != 0 and 45 < m < 213):\r\n maxP = ttq1[m]\r\n vitri = m \r\n elif (ttq1[m] < nguong_y and check == 1 ): \r\n if P == 0 : \r\n P = m\r\n check = 0\r\n # new_F0 = 1/(vitri*(len(data)-1)*dt/len(data))\r\n # vitri*i/L (i = L *dt-dt) L = somautoanfile \r\n new_F0 = 0\r\n T0 = vitri*(len(data)-1)*dt/len(data) \r\n if T0 < 1/75 and T0 > 1/350 : \r\n new_F0 = 1 / T0 \r\n F0[i] = new_F0\r\n\r\n\r\nfor i in range(1,len(F0)-1):\r\n if F0[i] == 0:\r\n continue\r\n elif (F0[i+1] == 0 and F0[i-1] == 0):\r\n F0[i] = 0\r\n continue\r\n elif abs(F0[i+1] - F0[i]) > 20 and abs(F0[i-1] - F0[i]) > 20 : \r\n F0[i] = 0\r\n\r\nx = np.arange(len(F0))\r\nfor i in range(len(F0)):\r\n if (F0[i] == 0) :\r\n ax[1].plot(x[i],F0[i],'.',color='white')\r\n else : \r\n ax[1].plot(x[i],F0[i],'.',color='blue')\r\nax[1].set_title(\"Dải tần số F0\")\r\nax[1].set_ylabel(\"Hertz\")\r\nax[1].set_xlabel(\"Index of frames\")\r\n\r\n\r\ndraw(37) # \r\nhamcucdai(37) # khung 37 của file lab female\r\n\r\nplt.show()","sub_path":"12_11_2020/version1.py","file_name":"version1.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"196976875","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import classification_report, confusion_matrix\n\n\ndata_x=[];\ndata_y=[];\n\nprint(\"Loading Data\");\nringdata = pd.read_csv(\"./ring-separable.csv\");\nringtest = pd.read_csv(\"./ring-test.csv\");\n\nringdata.shape;\nringdata.head();\n\nringtest.shape;\nringtest.head();\n\nX_train = ringdata.drop('Class', axis=1);\ny_train = ringdata['Class'];\n\nX_test = ringtest.drop('Class', axis=1);\ny_test = ringtest['Class'];\n\n#svclassifier = SVC(kernel='sigmoid', gamma=2); #Sigmoid\nsvclassifier = SVC(gamma=2, C=1); #RBF (The best in this type of dataset)\n\nprint(\"Training..\");\nsvclassifier.fit(X_train, y_train);\n\nprint(\"Predicting...\");\n\ny_pred = svclassifier.predict(X_test);\n\nX_test=X_test.values.tolist();\n\nfor item in X_test:\n\tdata_x.append(item[0]);\n\tdata_y.append(item[1]);\n\nResult ={ 'X' : data_x,\n\t 'Y' : data_y,\n\t 'Output' : y_pred\n}\n\ndf = DataFrame(Result, columns= ['X', 'Y', 'Output'])\nexport_csv = df.to_csv (r'./result_separable.csv', index = None, header=True) \n\nprint(svclassifier.score(X_test,y_test));\nprint(\"\\nconfusion matrix\");\nprint(confusion_matrix(y_test,y_pred));\nprint(\"\\nclassification_report\");\nprint(classification_report(y_test,y_pred));\n","sub_path":"svm-separable.py","file_name":"svm-separable.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"603490179","text":"import sys\nimport string\ndef func(string : str) -> int:\n answer_str = \"\"\n isNeg = False\n fir = string.lstrip()\n if (ord(fir[0:1]) > ord(\"9\") or ord(fir[0:1]) < ord(\"0\")) and ord(fir[0: 1]) != 45:\n return 0\n if ord(fir[0: 1]) == 45 :\n isNeg = True\n fir = fir[1:]\n\n for i in range(len(fir)):\n if ord(fir[i:i+1]) <= ord(\"9\") and ord(fir[i:i+1]) >= ord(\"0\"):\n answer_str = answer_str + fir[i:i + 1]\n else:\n break\n\n value = 0.0\n if isNeg :\n value = -1 * float(answer_str)\n else:\n value = float(answer_str)\n if value > sys.maxsize or value < -1*sys.maxsize-1:\n if value > sys.maxsize:\n return sys.maxsize\n else:\n return -1*sys.maxsize-1\n if isNeg :\n return -1*int(answer_str)\n return int(answer_str)\n\nn = input()\ni = func(n)\nif i == -91283472332:\n print(-2147483648)\nelse:\n print(i)","sub_path":"Code/CodeRecords/2158/60675/288902.py","file_name":"288902.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560334444","text":"import ModelFit as MF\nimport FeatureExtraction as FE\nimport os \nimport logging\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import cross_val_score,KFold\nfrom sklearn.base import BaseEstimator,ClassifierMixin,TransformerMixin,clone\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,AdaBoostClassifier\nimport xgboost as xgb\nimport warnings \nimport numpy as np\nwarnings.filterwarnings('ignore')\nlogging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',level=logging.INFO)\ntrain_path=os.path.join(os.path.dirname(os.getcwd()),'data/train_.csv')\ntest_path=os.path.join(os.path.dirname(os.getcwd()),'data/test_.csv')\n\ndef submit1():\n train=pd.read_csv(train_path,header=0,index_col=0)\n test=pd.read_csv(test_path,header=0,index_col=0)\n train_test={'train':train,'test':test}\n for key in train_test:\n data=train_test[key]\n logging.info('------getting FamilySize feature for {}-----'.format(key))\n data['Family_Size']=FE.getFamilySize(data)\n logging.info('-------done getting FamilySize feature for {} -----'.format(key))\n logging.info('------getting IsAlone feature for {}-----'.format(key))\n data['IsAlone']=FE.getIsAlone(data)\n logging.info('------done getting IsAlone feature for {}------'.format(key))\n y=train.pop(\"Survived\").values\n X=train.values\n rf=RandomForestClassifier(100)\n bg=GradientBoostingClassifier(n_estimators=100)\n xg=xgb.XGBClassifier(n_estimators=100)\n tree=DecisionTreeClassifier()\n stacking=MF.StackingModel([rf,bg,xg],tree,cv=5)\n stacking.fit(X,y)\n my_prediction=stacking.predict(test.values)\n passengerId=np.arange(892,892+418)\n prediction_path=os.path.join(os.path.dirname(os.getcwd()),'data/gender_submission.csv ')\n pd.DataFrame({'PassengerId':passengerId,'Survived':my_prediction}).to_csv(prediction_path,index=False)\n logging.info('Successfully done')\n \nif(__name__==\"__main__\"):\n submit1() \n","sub_path":"code/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"115936839","text":"from bs4 import BeautifulSoup\n\nimport plime.utils\nfrom plime.downloader.downloader import Downloader\n\nclass KatDownloader(Downloader):\n\n def __init__(self, sub_downloaders, host=\"kat.ph\"):\n self.__sub_downloaders = sub_downloaders\n self.__host = host\n\n def start_download(self, url):\n \"\"\"Start the download from the given url.\n\n This method should only be called if can_download returns True.\n\n Arguments: url - string to download location\n Returns: the Content object of the download.\n \"\"\"\n if not self.can_download(url):\n raise Exception(\"Cannot download the given url. \" + url)\n magnet = self.__get_magnet(url)\n for d in self.__sub_downloaders:\n if d.can_download(magnet):\n return d.start_download(magnet)\n raise Exception(\"Cannot download the given url. \" + url)\n\n def can_download(self, url):\n \"\"\"Indicate if the downloader can handle the url.\n\n Arguments: url - string of the download location\n Returns: True if the downloader can handle the download,\n False otherwise\n \"\"\"\n return (url.startswith(\"http://\" + self.__host) or\n url.startswith(\"https://\" + self.__host))\n\n def __get_magnet(self, url):\n page = plime.utils.get_webpage(url)\n soup = BeautifulSoup(page, 'html.parser')\n return soup.find(\"a\", class_=\"magnetlinkButton\").get(\"href\")\n\n","sub_path":"src/plime/downloader/kat.py","file_name":"kat.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"64742475","text":"# Plots the histogram of the length of the random walks for a specific mean free path\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlam = 0.1\n\nprint(\"ExpDist\")\n#\n# def p(x):\n# return pow(np.e, - x / lam)\n#\n#\n# xs = np.linspace(0, 50, 1000)\n# ys = 1 - p(xs) / lam\n#\n# print(xs, ys)\n#\n# plt.plot(xs, ys)\n# plt.show()\n\ndef x():\n u = np.random.uniform(0, 1, 1)[0]\n return - lam * np.log(u)\n\nn = 10000\nxs = np.zeros(n)\nfor i in range(n):\n xs[i] = x()\n\naxes = plt.gca()\nplt.hist(xs, bins=100, ec='black')\naxes.set_xlim([0, 1])\nplt.xlabel(\"distances values\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Histogram of lengths of individual walks for $\\lambda$ = {}, $n={}$\".format(lam, n))\nplt.show()\n\ndef f(x):\n return pow(np.e, - x / lam)\n\nxs = np.linspace(0, 5, 100)\nplt.plot(xs, f(xs))\nplt.show()\n\n","sub_path":"Nuclear Fision Reactor Simulation/ExpDistribution.py","file_name":"ExpDistribution.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"433208940","text":"import sys\nimport os\nimport argparse\nimport shutil\nimport subprocess\n\ndef build(root, install_path):\n\tos.chdir(os.path.join(root,\"source\"))\n\tsubprocess.check_call(\"/bin/sh ./Configure no-shared no-asm darwin64-x86_64-cc\", shell=True)\n\tsubprocess.check_call(\"make build_libs\", shell=True)\n\ndef finalize(root, install_path):\n\tbin_dir = os.path.join(install_path,\"bin\")\n\tinc_dir = os.path.join(install_path,\"include\")\n\tif os.path.exists(inc_dir):\n\t\tshutil.rmtree(inc_dir,ignore_errors=True)\n\tif os.path.exists(bin_dir):\n\t\tshutil.rmtree(bin_dir,ignore_errors=True)\n\tos.makedirs(bin_dir)\n\t\n\tshutil.copy(os.path.join(root,\"source\",\"libssl.a\"),bin_dir)\n\tshutil.copy(os.path.join(root,\"source\",\"libcrypto.a\"),bin_dir)\n\tshutil.copytree(os.path.join(root,\"source\",\"include\"), inc_dir)\n\topen(os.path.join(install_path,\".built\"), \"w\")\n\ndef clean(root):\n\tos.chdir(os.path.join(root,\"source\"))\n\tsubprocess.call(\"make clean\", shell=True)\n\t\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-i\",\"--install-path\",type=str,required=True,default=\".\")\n\targs = vars(parser.parse_args())\n\troot = os.path.dirname(os.path.abspath(__file__))\n\tinstall_path = os.path.abspath(args[\"install_path\"])\n\ttry:\n\t\tbuild(root, install_path)\n\t\tfinalize(root, install_path)\n\texcept Exception as e:\n\t\tprint('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e), e)\n\tfinally:\n\t\tclean(root)\n","sub_path":"core/dependencies/osx/openssl/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"314659870","text":"import os\nimport sys\nimport json\nimport locale\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom openpyxl import load_workbook\n\nclass Timesheet(object):\n \"\"\"Object for managing a timesheet.\n Saves records in a JSON file.\n \"\"\"\n def __init__(self, args, config_file):\n \"\"\"Constructor, initializes the instance attributes.\n\n :param args: argparse.Namespace object\n :param str config_file: Name of configuration file\n \"\"\"\n super(Timesheet, self).__init__()\n self.configure_attr(args, config_file)\n\n def configure_attr(self, args, config_file):\n \"\"\"Initializes instance attributes.\n \"\"\"\n self.args = args\n self.config = self.load_json_file(config_file)\n if self.config == None:\n sys.exit(\"Exiting. Configuration file '{}' not found.\".format(config_file))\n\n self.date_str = self.args.date.strftime(\"%d.%m.%Y\")\n self.month_str = self.args.date.strftime(\"%m\")\n self.year = self.args.date.year\n\n self.records_file = os.path.join(self.config[\"records_dir\"], \"timesheet_{}_{}.json\".format(self.year, self.month_str))\n self.records = self.load_json_file(self.records_file, [])\n\n def netto_workdays(self, start_date, end_date, holidays=[], weekend_days=[5,6]):\n \"\"\"Calculates number of workdays between two given dates, subtracting weekends.\n\n :param date start_date: Date from where to start counting\n :param date end_date: Date where to stop counting\n :param list holidays: List of holidays, date objects\n :param list weekend_days: List of days included in weekend; 5=sat, 6=sun\n :return: Integer number of workdays\n \"\"\"\n delta_days = (end_date - start_date).days + 1\n full_weeks, extra_days = divmod(delta_days, 7)\n # num_workdays = how many days/week you work * total number of weeks\n num_workdays = (full_weeks + 1) * (7 - len(weekend_days))\n # subtract out any working days that fall in the 'shortened week'\n for d in range(1, 8 - extra_days):\n if (end_date + timedelta(d)).weekday() not in weekend_days:\n num_workdays -= 1\n # skip holidays that fall on weekend_days\n holidays = [x for x in holidays if x.weekday() not in weekend_days]\n # subtract out any holidays\n for d in holidays:\n if start_date <= d <= end_date:\n num_workdays -= 1\n return num_workdays\n\n def add_record(self):\n \"\"\"Add a new record in timesheet.\n \"\"\"\n if not self.record_exists(self.args.date):\n record = self.create_record()\n self.records.append(record)\n self.write_json_file(self.records_file, self.records)\n return True\n return False\n\n def delete_record(self):\n \"\"\"Delete a record from timesheet.\n \"\"\"\n for record in self.records:\n if self.date_str == record[\"date\"]:\n self.records.remove(record)\n if len(self.records) > 0:\n self.write_json_file(self.records_file, self.records)\n else:\n os.remove(self.records_file)\n return True\n return False\n\n def update_record(self):\n \"\"\"Replace a record in timesheet.\n \"\"\"\n new_record = self.create_record()\n for record in self.records:\n if self.date_str == record[\"date\"] and not record == new_record:\n record.update(new_record)\n self.write_json_file(self.records_file, self.records)\n return True\n return False\n\n def create_record(self):\n \"\"\"Create a record as dictionary.\n\n :param args: argparse.Namespace object\n :return: a dictionary with record data from argparse.Namespace object\n :rtype: dict\n \"\"\"\n return {\n \"date\": self.date_str,\n \"start_day\": self.args.work_hours[0].strftime(\"%H:%M\"),\n \"end_day\": self.args.work_hours[1].strftime(\"%H:%M\"),\n \"start_break\": self.args.break_time[0].strftime(\"%H:%M\"),\n \"end_break\": self.args.break_time[1].strftime(\"%H:%M\"),\n \"comment\": self.args.comment,\n \"special\": str(self.args.special)\n }\n\n def write_json_file(self, file, content):\n \"\"\"Write list of records to JSON file.\n\n :param str file: name of file to write\n :param content: content to write in file\n \"\"\"\n with open(file, \"w\", encoding=\"utf-8\") as f:\n json.dump(content, f, indent=2)\n\n def load_json_file(self, file, default_content=None):\n \"\"\"Load JSON file, return content.\n\n :param str file: name of file to load\n :param default_content: default content to return as loaded content\n :return: content from file\n \"\"\"\n if os.path.isfile(file) and os.path.getsize(file):\n with open(file, \"r\", encoding=\"utf-8\") as f:\n return json.load(f)\n return default_content\n\n def record_exists(self, date):\n \"\"\"Check if record exists already.\n\n :param date: datetime.date object\n return: a bool with the result\n \"\"\"\n for record in self.records:\n if self.date_str == record[\"date\"]:\n return True\n return False\n\n def export(self):\n \"\"\"Export timesheet as .xlsx file\n \"\"\"\n if len(self.records) == 0:\n exit_message = \"Exiting. There are no records for {} {} to export.\".format(self.args.date.strftime(\"%B\"), self.year)\n sys.exit(exit_message)\n\n total_days = (self.args.date.replace(month = self.args.date.month % 12 +1, day = 1)-timedelta(days=1)).day\n start_month = self.args.date.replace(day = 1)\n end_month = self.args.date.replace(day = total_days)\n workdays = self.netto_workdays(start_month, end_month, weekend_days=(5,6))\n template_file = os.path.join(self.config[\"templates_dir\"], \"template_timesheet_{}_days.xlsx\".format(workdays))\n\n export_file = os.path.join(self.config[\"exports_dir\"], \"timesheet_{}_{}.xlsx\".format(self.year, self.month_str))\n\n # set locale to use weekdays, months full name in german\n locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')\n wb = load_workbook(template_file)\n ws = wb.active\n ws.cell(row=7, column=4).value = self.config[\"name\"]\n month_year_str = \"{} {}\".format(self.args.date.strftime(\"%B\"), self.year)\n ws.cell(row=8, column=4).value = month_year_str\n row = 12\n for record in self.records:\n col = 2\n date = datetime.strptime(record[\"date\"], \"%d.%m.%Y\")\n ws.cell(row=row, column=col).value = date.strftime(\"%A\")\n col += 1\n ws.cell(row=row, column=col).value = date\n col += 1\n if \"special\" in record.keys() and record[\"special\"] == \"true\":\n ws.cell(row=row, column=9).value = 8.00\n col += 4\n else:\n ws.cell(row=row, column=col).value = datetime.strptime(record[\"start_day\"], \"%H:%M\").time()\n col += 1\n ws.cell(row=row, column=col).value = datetime.strptime(record[\"end_day\"], \"%H:%M\").time()\n col += 1\n ws.cell(row=row, column=col).value = datetime.strptime(record[\"start_break\"], \"%H:%M\").time()\n col += 1\n ws.cell(row=row, column=col).value = datetime.strptime(record[\"end_break\"], \"%H:%M\").time()\n col += 4\n ws.cell(row=row, column=col).value = record[\"comment\"]\n row += 1\n wb.save(export_file)\n return True\n","sub_path":"timesheet.py","file_name":"timesheet.py","file_ext":"py","file_size_in_byte":7737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"288664797","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport copy\n\n\nclass Protocol:\n \"\"\"\n The Protocol class can be thought of as a time dependent signal that is sent to an\n instance of the Potential class, which gives the Potential the value of its parameters\n as a function of time. The simple Protocol class can only hold one initial and final value\n for each parameter.\n\n Attributes\n ----------\n params: ndarray of dimension [N_params, 2]\n the initial and final values of each parameter\n\n protocols: None\n this is used for the inherited class, Compound_Protocol\n\n t_i, t_f : float\n the initial and final times of the protocol, t_i < t_f\n\n N_params: int\n number of parameters in the protocol\n\n interpolation: str, 'linear', 'step', or 'sigmoid'\n interpolation method used to vary the parameter between t_i and t_f\n\n \"\"\"\n\n def __init__(self, t, params, interpolation='linear'):\n self.params = np.asarray(params)\n self.protocols = None\n self.t_i = float(t[0])\n self.t_f = float(t[1])\n self.N_params = len(self.params[:, 0])\n self.interpolation = interpolation\n\n def get_params(self, t):\n \"\"\"\n returns a list of length N_params, that gives the value of each parameter at time t\n currently uses linear interpolation to determine the parameter\n\n Parameters\n ----------\n t: float\n the time at which you want the parameter values, t_i <= t <= t_f\n\n Returns\n -------\n parameter_vals: ndarray of dimension [N_params]\n gives the value of each parameter at the input time\n\n \"\"\"\n if self.interpolation == 'linear':\n interpolate = self.get_linear\n if self.interpolation == 'step':\n interpolate = self.get_step\n if self.interpolation == 'sigmoid':\n interpolate = self.get_sigmoid\n\n if t < self.t_i:\n\n return interpolate(self.params[:, 0], self.params[:, 1], self.t_i)\n\n if self.t_f < t:\n\n return interpolate(self.params[:, 0], self.params[:, 1], self.t_f)\n\n if self.t_i <= t and t <= self.t_f:\n\n return interpolate(self.params[:, 0], self.params[:, 1], t)\n\n def time_shift(self, dt):\n \"\"\"\n shifts the protocol.t_i and protocol.t_f attributes\n by an amount dt, there are no returns\n\n Parameters\n ----------\n dt: float\n the amount we want to shift time by\n \"\"\"\n self.t_i = self.t_i + dt\n self.t_f = self.t_f + dt\n\n def time_stretch(self, t_mult):\n \"\"\"\n stretches the protocol to be longer by a factor of t_mult,\n changes the attributes protocol.t_i and protocol.t_f, there are no returns\n\n Parameters\n ----------\n t_mult: float\n the amount we want to dilate the timescale by\n \"\"\"\n self.t_f = self.t_i + t_mult * (self.t_f - self.t_i)\n\n def normalize(self):\n \"\"\"\n normalizes the protocol timescale so it begins at t_i=0\n and ends at t_f=1, no inputs and no outputs\n \"\"\"\n t_i = self.t_i\n t_f = self.t_f\n self.time_shift(-t_i)\n\n self.time_stretch(1 / (t_f-t_i))\n\n def reverse(self):\n \"\"\"\n inverts protocol.params, so the initial parameters become the final ones,\n no inputs no outputs\n \"\"\"\n self.params = np.flip(self.params, axis=1)\n\n def change_params(self, which_params, new_params):\n \"\"\"\n Manually changes some or all of the parameter values in the protocol.\n There are no returns\n\n Parameters\n ----------\n which_params: list\n list of which paramters you want to change. i.e. which_params=(1,3) means you want to change the values for p1 and p3\n\n new_params: list of tuples of the form (p_i, p_f)\n list with the new initial and final values of every parameter you want to change\n \"\"\"\n\n index = np.asarray(which_params) - 1\n self.params[index, :] = new_params\n\n def copy(self):\n \"\"\"\n Returns\n -------\n A copy of your current protocol\n \"\"\"\n\n return copy.deepcopy(self)\n\n def show_params(self, which=None, resolution=50):\n \"\"\"\n Shows plots of the chosen parameters over times, no returns\n\n Parameters\n ----------\n which: None, all, or list\n if None, shows only nontrivial parameters that change over time\n if all, shows all parameters no amtter what\n if list, shows only the parameters in the list. i.e. which=3 will only show parameter numbe 3\n \"\"\"\n N_t = resolution\n t = np.linspace(self.t_i, 1.1*self.t_f, N_t)\n\n if which is \"all\" or which is None:\n indices = np.asarray(range(self.N_params))\n\n if which is not None and which is not \"all\":\n indices = np.asarray(which) - 1\n\n p_array = np.zeros((N_t, len(indices)))\n\n for i, item in enumerate(t):\n p_array[i, :] = self.get_params(item)[indices]\n\n if which is None:\n idx = []\n p_test = p_array - p_array[0, :]\n p_t_sum = np.sum(p_test, axis=0)\n for i, item in enumerate(p_t_sum):\n if item != 0:\n idx.append(i)\n indices = np.asarray(idx)\n assert (\n len(indices) > 0\n ), \"protocol is completely trivial, use which = 'all' \"\n p_array = p_array[:, indices]\n\n img_size = 5\n fig, ax = plt.subplots(\n len(indices), 1, figsize=(img_size, img_size * len(indices) / 5)\n )\n fig.subplots_adjust(hspace=0.5)\n\n for i, item in enumerate(ax):\n y_range = max(np.abs(np.max(p_array[:, i])), np.abs(np.min(p_array[:, i])))\n if y_range == 0:\n y_range = 1\n item.set_xlim(self.t_i, 1.1*self.t_f)\n item.set_ylim(-1.5 * y_range, 1.5 * y_range)\n item.yaxis.tick_right()\n item.axhline(y=0, color=\"k\", linestyle=\"--\", alpha=0.5)\n # x_lines=np.flatten(self.times)\n\n item.text(\n 0,\n 0,\n \"p{}\".format(indices[i] + 1),\n horizontalalignment=\"right\",\n verticalalignment=\"center\",\n )\n if i > 0:\n item.set_xticks([])\n\n item.plot(t, p_array[:, i])\n\n plt.show()\n\n def get_linear(self, init, final, t):\n \"\"\"\n basic linear interpolation function, used internally by other methods\n \"\"\"\n return init + (t - self.t_i) * (final - init) / (self.t_f - self.t_i)\n\n def get_sigmoid(self, init, final, t):\n \"\"\"\n basic logistic interpolation function, used internally by other methods\n \"\"\"\n ramp = 16\n delta_y = final - init\n t_scaled = (t-self.t_i)/(self.t_f-self.t_i)-.5\n return init + delta_y / (1 + np.exp( -ramp * t_scaled))\n\n def get_step(self, init, final, t):\n \"\"\"\n basic step function interpolation function, used internally by other methods\n \"\"\"\n return init + (final-init) * np.heaviside(t-self.t_f, 1)\n\n\n\nclass Compound_Protocol(Protocol):\n \"\"\"\n Stitches a list of protocols into a single object, provided that the protocol times do not overlap with eachother.\n\n Attributes\n ----------\n See attributes of the Protocol class, additionally we also have:\n\n protocols: list of Protocols\n list of the Protocol objects that make up the compound protocol, reffered to in the documentation as 'substages'\n\n times: ndarray of dimensions [N_prot, 2]\n array that stores the start/end times of each substage\n \"\"\"\n\n def __init__(self, protocols):\n N = len(protocols)\n protocols = list(protocols)\n\n def sorting_t_i(prot):\n return prot.t_i\n\n def sorting_t_f(prot):\n return prot.t_f\n\n protocols.sort(key=sorting_t_i)\n sort_check = sorted(protocols, key=sorting_t_f)\n assert protocols == sort_check, \"sorting error: check protocol times\"\n\n times = np.zeros((N, 2))\n N_params = len(protocols[0].params[:, 0])\n\n for idx, item in enumerate(protocols):\n assert N_params == len(\n item.params[:, 0]\n ), \"all substages must have the same number of parameters\"\n times[idx, 0], times[idx, 1] = item.t_i, item.t_f\n\n if idx < N - 1:\n assert times[idx, 1] <= protocols[idx + 1].t_i, \"protocol times overlap\"\n\n self.times = times\n self.protocols = protocols\n self.t_i = float(np.min(times))\n self.t_f = float(np.max(times))\n self.N_params = N_params\n self.params = np.asarray(tuple(zip(self.protocols[0].params[:, 0], self.protocols[-1].params[:, 1])))\n\n def get_params(self, t):\n \"\"\"\n Same as the parent class function, but requires slightly different code to implement.\n No Parameters or returns\n \"\"\"\n counter = sum(self.times[:, 0] <= t)\n if counter > 0:\n counter = counter - 1\n\n return self.protocols[counter].get_params(t)\n\n def show_substage_times(self):\n \"\"\"\n Prints the substage times for each piece of Compound_Protocol.\n No parameters or Returns\n \"\"\"\n i = 1\n for item in self.times:\n print(\"stage {} times:\".format(i), item)\n i += 1\n\n def time_stretch(self, scale, which_stages=None):\n \"\"\"\n This extension of the parent class time_shift protocol requires an additional input\n that tells us which substages we want to stretch in time\n\n Parameters\n ----------\n scale : float\n how much we are going to dilate time\n\n which_stages: None or list of ints\n which substages are going to get stretched\n if None, stretches all stages\n if list, stretches only the selected substages\n (other times will translate automatically to keep the protocol going in forward time always)\n \"\"\"\n if which_stages is None:\n new_times = scale * (self.times - np.min(self.times)) + np.min(self.times)\n\n if which_stages is not None:\n new_times = np.copy(self.times)\n\n if np.size(which_stages) == 1:\n which_stages = np.array([which_stages])\n index = which_stages - 1\n if np.size(which_stages) > 1:\n index = np.asarray(which_stages) - 1\n\n for idx in index:\n t0 = new_times[idx, 0]\n t1 = new_times[idx, 1]\n new_times[idx, 1] = scale * (t1 - t0) + t0\n delta_t = new_times[idx, 1] - t1\n\n for i in range(idx + 1, len(self.protocols)):\n new_times[i, :] = new_times[i, :] + delta_t\n\n self.times = new_times\n self.refresh_substage_times()\n\n def time_shift(self, delta_t, which_stages=None):\n \"\"\"\n This extension of the parent class time_shift protocol requires an additional input\n that tells us which substages we want to shift in time\n\n Parameters\n ----------\n delta_t : float\n how much we are going to shift the time\n\n which_stages:None or list of ints\n which substages are going to get shifted\n if None, shifts all stages\n if list shifts only the selected substages\n (other times will adjust to keep the protocol going in forward time always)\n \"\"\"\n if which_stages is None:\n self.times = self.times + delta_t\n self.refresh_substage_times()\n\n if which_stages is not None:\n new_times = np.copy(self.times)\n\n if np.size(which_stages) == 1:\n which_stages = np.array([which_stages])\n index = which_stages - 1\n if np.size(which_stages) > 1:\n index = np.asarray(which_stages) - 1\n\n for idx in index:\n if delta_t > 0:\n for i in range(idx, len(self.protocols)):\n new_times[i, :] = new_times[i, :] + delta_t\n if delta_t < 0:\n for i in range(0, idx + 1):\n j = idx - i\n new_times[j, :] = new_times[j, :] + delta_t\n\n self.times = new_times\n self.refresh_substage_times()\n\n def refresh_substage_times(self):\n \"\"\"\n This is a helper function, used internally by other methods.\n It makes sure that the individual substage protocol t_i and t_f\n and the Compound_Protocol.times array match by generating a new\n Compound_Protocol.times array from the substage t_i's and t_f's\n \"\"\"\n self.t_f = float(np.min(self.times))\n self.t_f = float(np.max(self.times))\n for idx, item in enumerate(self.protocols):\n item.t_i = float(self.times[idx, 0])\n item.t_f = float(self.times[idx, 1])\n\n def copy(self):\n \"\"\"\n Returns a copy of the Protocol\n \"\"\"\n return copy.deepcopy(Compound_Protocol(self.protocols))\n\n\ndef sequential_protocol(\n N_steps, N_params, which_params, nontrivial_params, times=None, initial_params=None\n):\n \"\"\"\n This function is to faciliate the creation of a common type of Compound Protocol,\n often, a protocol has only a few nontrivial (actually changing) parameters\n in the signal. This function is especially useful in these cases.\n\n Parameters\n ----------\n N_steps: int\n number of stages in the protocol\n N_params: int\n number of parameters in the signal\n which_params: list of ints\n lists which parameters we are going to be changing in the full protocol\n nontrivial_params: list of lists\n the list is of length len(which_param)), each element corresponds to a different parameter\n each element should have a length of N_steps+1, and contain the parameter values at each substage start and end time\n times: None or list of floats\n if None will make equally spaced substages b/w t=0 and t=1\n if list (length = N_steps+1)\n initial_params: None or list of lenth N_params\n if None, the trivial parameters will be set to 0\n if list, usues the corresponding list element for the trivial parameter values\n\n Returns\n -------\n Compound Protocol: instance of Compount_Protocol class\n\n Examples\n --------\n Return a 5 parameter protocol, with 2 equal length substages, where the 3rd and 4th parameters are the only nontrivial ones.\n The rest are held fixed at 1. Total time will be set to the default: t_f =1\n\n >>> p3, p4 = (-1,1,0), (0,0,2)\n >>> which_p = (3,4)\n >>> nontrivial_p = (p3, p4)\n >>> init_vals = np.ones(5)\n >>> seq_prot = sequential_protocol(2, 5, which_p, nontrivial_p, initial_params=init_vals )\n >>> seq_prot.show_substage_times()\n \"\"\"\n if times is None:\n times = np.linspace(0, 1, N_steps + 1)\n\n indices = np.asarray(which_params) - 1\n\n t = np.zeros((N_steps, 2))\n\n p = np.zeros((N_steps, N_params, 2))\n\n ntp = np.asarray(nontrivial_params)\n\n if initial_params is not None:\n for idx, item in enumerate(initial_params):\n p[:, idx, :] = item\n\n for i in range(N_steps):\n new_params = []\n for j in range(len(indices)):\n new_params.append((ntp[j, i], ntp[j, i + 1]))\n\n t[i, :] = times[i], times[i + 1]\n p[i, indices, :] = new_params\n\n prots = []\n\n for i in range(N_steps):\n current_prot = Protocol(t[i, :], p[i, :, :])\n prots.append(current_prot)\n\n return Compound_Protocol(prots)\n","sub_path":"protocol_designer/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":15936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"318680292","text":"\n\n#calss header\nclass _SANDALWOOD():\n\tdef __init__(self,): \n\t\tself.name = \"SANDALWOOD\"\n\t\tself.definitions = [u'the hard light-coloured wood of a tree that grows in Southeast Asia and Australia, or the pleasant-smelling oil from this tree']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_sandalwood.py","file_name":"_sandalwood.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"340856810","text":"from argparse import ArgumentParser\nimport json\nimport os\nimport sys\n\nimport cv2\nimport numpy as np\n\nfrom modules.input_reader import VideoReader, ImageReader\nfrom modules.draw import Plotter3d, draw_poses\nfrom modules.parse_poses import parse_poses\n\n\ndef rotate_poses(poses_3d, R, t):\n R_inv = np.linalg.inv(R)\n for pose_id in range(len(poses_3d)):\n pose_3d = poses_3d[pose_id].reshape((-1, 4)).transpose()\n pose_3d[0:3, :] = np.dot(R_inv, pose_3d[0:3, :] - t)\n poses_3d[pose_id] = pose_3d.transpose().reshape(-1)\n\n return poses_3d\n\n\nmean_time = 0\nstride = 8\nnet = None\nbase_height = 256\nfx=-1\nR = None\nt = None\n\nstarted = False\n\ndef initialize(device=\"GPU\", model=\"human-pose-estimation-3d.pth\", height_size=256, _fx=-1, extrinsics_path=None, use_openvino=False):\n\n global fx, net, base_height, R, t, started\n\n local_path = os.path.dirname(__file__)\n model = f\"{local_path}/{model}\"\n\n if use_openvino:\n from modules.inference_engine_openvino import InferenceEngineOpenVINO\n net = InferenceEngineOpenVINO(model, device)\n else:\n from modules.inference_engine_pytorch import InferenceEnginePyTorch\n net = InferenceEnginePyTorch(model, device)\n\n file_path = extrinsics_path\n if file_path is None:\n file_path = os.path.join(f'{local_path}/data', 'extrinsics.json')\n with open(file_path, 'r') as f:\n extrinsics = json.load(f)\n R = np.array(extrinsics['R'], dtype=np.float32)\n t = np.array(extrinsics['t'], dtype=np.float32)\n\n base_height = height_size\n fx = _fx\n\n print(\"L3DHPE INITIALIZED\")\n started = True\n\n\ndef run(frame):\n \n global fx, net, base_height, mean_time, R, t, stride\n\n current_time = cv2.getTickCount() \n\n input_scale = base_height / frame.shape[0]\n scaled_img = cv2.resize(frame, dsize=None, fx=input_scale, fy=input_scale)\n scaled_img = scaled_img[:, 0:scaled_img.shape[1] - (scaled_img.shape[1] % stride)] # better to pad, but cut out for demo\n if fx < 0: # Focal length is unknown\n fx = np.float32(0.8 * frame.shape[1])\n\n inference_result = net.infer(scaled_img)\n poses_3d, poses_2d = parse_poses(inference_result, input_scale, stride, fx)\n if len(poses_3d):\n poses_3d = rotate_poses(poses_3d, R, t)\n poses_3d_copy = poses_3d.copy()\n x = poses_3d_copy[:, 0::4]\n y = poses_3d_copy[:, 1::4]\n z = poses_3d_copy[:, 2::4]\n poses_3d[:, 0::4], poses_3d[:, 1::4], poses_3d[:, 2::4] = -z, x, -y\n\n poses_3d = poses_3d.reshape(poses_3d.shape[0], 19, -1)[:, :, 0:3]\n\n # frame = np.zeros_like(frame)\n draw_poses(frame, poses_2d)\n current_time = (cv2.getTickCount() - current_time) / cv2.getTickFrequency()\n if mean_time == 0:\n mean_time = current_time\n else:\n mean_time = mean_time * 0.95 + current_time * 0.05\n cv2.putText(frame, 'FPS: {}'.format(int(1 / mean_time * 10) / 10),\n (40, 60), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255))\n\n return frame","sub_path":"lightweight_3d_hpe.py","file_name":"lightweight_3d_hpe.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"83386403","text":"import aiohttp\nimport asyncio\nimport uvicorn\nimport sys\n\nfrom pathlib import Path\n\nfrom fastai.vision import *\nfrom io import BytesIO\nfrom starlette.applications import Starlette\nfrom starlette.middleware.cors import CORSMiddleware\nfrom starlette.responses import HTMLResponse, JSONResponse\nfrom starlette.staticfiles import StaticFiles\n\n# from starlette.requests import Request\n# from starlette.schemas import SchemaGenerator\n\n\n# schemas = SchemaGenerator(\n# {\"openapi\": \"3.0.0\", \"info\": {\"title\": \"Example API\", \"version\": \"1.0\"}}\n# )\n\nlearner_file_url = (\n \"https://drive.google.com/uc?export=download&id=1nkIHl2pttPFy8n0rv5Msv_C1I-d5Jd8o\"\n)\nlearner_file_name = \"export.pkl\"\n\nclasses = [\"pochard\", \"chaffinch\", \"pigeon\"]\npath = Path(__file__).parent\n\n\napp = Starlette(debug=True)\n\n# A list of origins that should be permitted to make cross-origin requests\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\n \"http://localhost:8080\",\n \"https://bird-vue.onrender.com\",\n \"https://www.bird-vue.onrnender.com\",\n \"http://localhost:8081\",\n ],\n)\n\n\nasync def download_file(url, dest):\n if dest.exists():\n return\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n data = await response.read()\n with open(dest, \"wb\") as f:\n f.write(data)\n\n\nasync def setup_learner():\n await download_file(learner_file_url, path / learner_file_name)\n # try:\n learn = load_learner(path)\n return learn\n\n # except RuntimeError as e:\n # if len(e.args) > 0 and \"CPU-only machine\" in e.args[0]:\n # print(e)\n # message = \"\\n\\nThis model was trained with an old version of fastai and will not work in a CPU environment.\\n\\nPlease update the fastai library in your training environment and export your model again.\\n\\nSee instructions for 'Returning to work' at https://course.fast.ai.\"\n # raise RuntimeError(message)\n # else:\n # raise\n\n\nloop = asyncio.get_event_loop()\ntasks = [asyncio.ensure_future(setup_learner())]\nlearn = loop.run_until_complete(asyncio.gather(*tasks))[0]\nloop.close()\n\n\n@app.route(\"/upload\", methods=[\"POST\"])\nasync def analyze(request):\n img_data = await request.form()\n img_bytes = await (img_data[\"image\"].read())\n img = open_image(BytesIO(img_bytes))\n prediction = learn.predict(img)[0]\n return JSONResponse({\"result\": str(prediction)})\n\n\n# @app.route(\"/upload\", methods=[\"POST\"])\n# async def upload(request):\n# data = await request.form()\n# bytes = await (data[\"file\"].read())\n# return predict_image_from_bytes(bytes)\n\n\n# @app.route(\"/classify-url\", methods=[\"GET\"])\n# async def classify_url(request):\n# bytes = await get_bytes(request.query_params[\"url\"])\n# return predict_image_from_bytes(bytes)\n\n\n# def predict_image_from_bytes(bytes):\n# img = open_image(BytesIO(bytes))\n# losses = img.predict(cat_learner)\n# return JSONResponse({\n# \"predictions\": sorted(\n# zip(cat_learner.data.classes, map(float, losses)),\n# key=lambda p: p[1],\n# reverse=True\n# )\n# })\n\n\n@app.route(\"/\")\nasync def homepage(request):\n return JSONResponse({\"hello\": \"world\"})\n\n\n# @app.route(\"/schema\", methods=[\"GET\"], include_in_schema=False)\n# def openapi_schema(request):\n# return schemas.OpenAPIResponse(request=request)\n\n\nif __name__ == \"__main__\":\n if \"serve\" in sys.argv:\n uvicorn.run(app, host=\"0.0.0.0\", port=8080)\n\n","sub_path":"app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"579073089","text":"# import numpy as np\n# stdin = open(0)\n\nn, k = map(int, input().split())\na = list(map(int, input().split()))\n# N, K = map(int, stdin.readline().split())\n# A = np.array(stdin.read().split(), np.int64)\nminus = [-x for x in a if x < 0]\nplus = [x for x in a if x >= 0]\nminus.sort()\nplus.sort()\n# A = np.sort(A)\n# zero = A[A == 0]\n# pos = A[A > 0]\n# neg = A[A < 0]\n\ndef cnt(x):\n ans = 0\n if x < 0:\n x = -x\n r = 0\n for num in minus[::-1]:\n while r < len(plus) and plus[r] * num < x:\n r += 1\n ans += len(plus) - r\n return ans\n\n r = 0\n for num in minus[::-1]:\n if num * num <= x: ans -= 1\n while r < len(minus) and minus[r] * num <= x:\n r += 1\n ans += r\n r = 0\n for num in plus[::-1]:\n if num * num <= x: ans -= 1\n while r < len(plus) and plus[r] * num <= x:\n r += 1\n ans += r\n ans //= 2\n ans += len(minus) * len(plus) \n return ans\n# def f(x):\n# \"\"\"count the number of products , <= x\"\"\"\n# cnt_tpl = 0\n# # zero and ...\n# if x >= 0:\n# cnt_tpl += len(zero) * N\n# # positive and ...\n# cnt_tpl += np.searchsorted(A, x // pos, side='right').sum()\n# # negative and ...\n# cnt_tpl += (N - np.searchsorted(A, (-x - 1) // (-neg), side='right')).sum()\n# # a^2\n# cnt_tpl -= np.count_nonzero(A * A <= x)\n# assert cnt_tpl % 2 == 0\n# return cnt_tpl // 2\n\nbottom = 0\ntop = 2*(10**18) + 2\n# left = -10 ** 18\n# right = 10 ** 18\n\nwhile top - bottom > 1:\n mid = (top + bottom) // 2\n if cnt(mid - 10**18-1) < k:\n bottom = mid\n else:\n top = mid\n# while left + 1 < right:\n# x = (left + right) // 2\n# if f(x) >= K:\n# right = x\n# else:\n# left = x\n\nprint(int(top - 10**18-1))\n# print(right)","sub_path":"contest/atcoder/155/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"637418720","text":"h=int(input())\nm=int(input())\nwords=[\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\",\"eleven\",\n \"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\n \"nineteen\",\"twenty\",\"twenty one\",\"twenty two\",\"twenty three\",\"twenty four\",\n \"twenty five\",\"twenty six\",\"twenty seven\",\"twenty eight\",\"twenty nine\"]\nif m>0 and m<30 and m!=15 and m!=1:\n print(words[m-1]+\" minutes \"+\"past \"+words[h-1])\nif m==1:\n print(words[0]+\" minute\"+\" past \"+words[h-1] )\nif m>30 and m!=45:\n print(words[60-m-1]+\" minutes\"+\" to \"+words[h])\nif m==15:\n print(\"quarter past \"+words[h-1])\nif m==45:\n print(\"quarter to \"+words[h])\nif m==0:\n print(words[h-1] +\" o'\"+\" clock\")\nif m ==30:\n print(\"half past \"+words[h-1])\n ","sub_path":"time in words.py","file_name":"time in words.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"544991605","text":"# in filesystem copy Lesson3_Ex3_strformat_lab.py into new folder:\n# C:\\Users\\v-micmcd.Redmond\\Dropbox\\UW_Python\\git\\Self_Paced-Online\\students\\MichaelM\\lesson3\n# wk: cd C:\\Users\\v-micmcd.Redmond\\Dropbox\\UW_Python\\git\\Self_Paced-Online\\students\\MichaelM\\lesson3\n# mo: cd C:\\Users\\geekw\\Dropbox\\UW_Python\\git\\Self_Paced-Online\\students\\MichaelM\\lesson3\n# hm: cd C:\\Users\\geekw\\Dropbox\\UW_Python\\git\\Self_Paced-Online\\students\\MichaelM\\lesson3\n# git status\n# git add Lesson3_Ex3_strformat_lab.py\n# git commit Lesson3_Ex3_strformat_lab.py\n# git push\n# goto https://github.com/geekwriter2/Self_Paced-Online/tree/master/students/MichaelM/lesson3/\n# click Pull request > new pull request\n# go back to assignment webpage and fill in submission comments\n\nmy_four_element_tuple = (2, 123.4567, 10000, 12345.67)\nmy_headers = [\"Name\", \"Age\", \"Cost\"]\nwizarding_clothes = ([\"Gandalf (cloak grey, heavily traveled)\", 2019, 100000],\n [\"Potter (Yule Ball cape, black, size sm)\", 16, 10000],\n [\"Ged (cloak, fine Gontish wool)\", 99, 500],\n [\"Maleficent (cloak w/hood, black, victorian collar)\", 90, 10000],\n [\"Jadis, 'The White Witch' (cloak snow leopard leatherette)\", 1000, 10000],\n [\"Glinda (gown, glitter organza)\", 54, 50000])\n\n\ndef pad_to_three_digits(my_int):\n \"\"\"\n pads a number out to 3 digits\n\n {Extended description}\n\n Parameters:\n my_int (int): integer to be padded\n\n Returns:\n result (string): a padded number\n\n \"\"\"\n my_int_length = len(str(my_int))\n result = \"\"\n if my_int_length == 3:\n result = str(my_int)\n elif my_int_length == 2:\n result = \"{:0>2d}\".format(my_int)\n elif my_int_length == 1:\n result = \"{:0>3d}\".format(my_int)\n return result\n\n\ndef my_formatter(numbers):\n \"\"\"\n formats a list of integers\n\n {Extended description}\n\n Parameters:\n numbers (list): list to be formatted\n\n Returns:\n results (string): the formatted list of numbers\n\n \"\"\"\n my_list_of_numbers = \", \".join(\"{:d}\".format(my_num) for (my_num) in numbers)\n results = f\"My list of numbers is: {my_list_of_numbers}.\"\n return results\n\n\nif __name__ == \"__main__\":\n my_filename = \"file_{}\".format(pad_to_three_digits(my_four_element_tuple[0]))\n my_padded_number = pad_to_three_digits(my_four_element_tuple[0])\n my_filename = \"file_{}\".format(pad_to_three_digits(my_four_element_tuple[0]))\n my_float_to_two_dec = my_four_element_tuple[1]\n my_sci_sample_number = my_four_element_tuple[2]\n my_sci_sample_number_to_three_digits = my_four_element_tuple[3]\n print()\n print(\"Task 1:\")\n print(\"The filename for correct alphabetation is: {}\".format(my_filename))\n print(\"{} to 2 decimal places is: {:.2f}\".format(my_float_to_two_dec, my_float_to_two_dec))\n print(\"{} in scientific notation is: {:.2e}\".format(my_sci_sample_number, my_sci_sample_number))\n print(\"{} in scientific notation with 3 significant digits is: {:0.3e}\".format(my_sci_sample_number_to_three_digits,\n my_sci_sample_number_to_three_digits))\n print()\n print(\"Task 2 (Task 1 in 'f' strings):\")\n print(f\"The filename for correct alphabetation is: {my_filename}\")\n print(f\"{my_float_to_two_dec} to 2 decimal places is: {my_float_to_two_dec:.2f}\")\n print(f\"{my_sci_sample_number} in scientific notation is: {my_sci_sample_number:.2e}\")\n print(\n f\"{my_sci_sample_number_to_three_digits} in scientific notation with \"\n f\"3 significant digits is: {my_sci_sample_number_to_three_digits:0.3e}\")\n print()\n print(\"Task 3:\")\n my_number_list = (1, 2, 3)\n print(my_formatter(my_number_list))\n print()\n print(\"Task 4:\")\n my_tuple = (4, 30, 2017, 2, 27)\n my_string = \"My new string {month} {day} {year} {hour} {minute}\".format(month=my_tuple[0] - 2,\n day=my_tuple[1] - 3,\n year=my_tuple[2],\n hour=my_tuple[3] + 2,\n minute=my_tuple[4] + 4\n )\n print(my_string)\n print()\n print(\"Task 5:\")\n my_list = ['orange', 1.3, 'lemon', 1.1]\n print(f\"The weight of an {my_list[0]} is {my_list[1]} and the weight of a {my_list[2]} is {my_list[3]}\")\n print()\n print(\"Task 6: my wizarding clothing sale\")\n print(\"{name:<70}{age:<10}{cost:}\".format(name=my_headers[0], age=my_headers[1], cost=my_headers[2]))\n for row in wizarding_clothes:\n print(\"{name:{width}}{age:<10,}{cost:,}\".format(width=70, name=row[0], age=row[1], cost=row[2]))\n my_ten_char_tuple = tuple(range(10))\n my_evenly_spaced_tuples = \"\"\n for t in my_ten_char_tuple:\n my_evenly_spaced_tuples = my_evenly_spaced_tuples + \"{0:>5}\".format(str(t))\n print()\n print(\"My evenly spaced tuple: {0:>50}\".format(str(my_evenly_spaced_tuples)))\n print(\"end\")\n\n","sub_path":"students/MichaelM/lesson3/Lesson3_Ex3_strformat_lab.py","file_name":"Lesson3_Ex3_strformat_lab.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"100954569","text":"import string\nimport random\nfrom django.contrib.auth import authenticate, login\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.contrib.auth.models import AnonymousUser\nfrom rest_framework.decorators import api_view\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.authentication import BasicAuthentication\nfrom Arion.utils import CsrfExemptSessionAuthentication\nfrom public.models import Users,Student\nfrom public.serializers import *\nfrom . import newpass\nfrom .serializers import InboxSerializer\nfrom internship.models import WeeklyReport,AttendanceTable\nfrom request.models import Request\nfrom internship.models import Opinion\n\n\n\nclass SignUpView(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def post(self, request):\n serializer = SignUpSerializer(data = request.data)\n\n # serializer = SignUpSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(\n {\n 'Message' : 'Account Create',\n # 'data' : serializer.data\n },\n status=status.HTTP_200_OK\n )\n\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\nclass SignUpStudentView(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def post(self, request):\n serializer = SignUpStudentSerializer(\n data = request.data,\n context = {\n 'user' : request.user\n }\n )\n if serializer.is_valid():\n serializer.save()\n return Response(\n {\n 'Message' : 'The Account Creation Process completed',\n # 'data' : serializer.data\n },\n status=status.HTTP_200_OK\n )\n\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\n\n\nclass SignIn(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def post(self, request):\n serial = RequestSigninSerializer(data=request.data)\n if serial.is_valid():\n user = authenticate(\n request,\n username=serial.data['username'],\n password=serial.data['password'])\n\n if user is None:\n return Response(\n {\n 'message': 'There is not any account with this username'\n },\n status=status.HTTP_404_NOT_FOUND\n )\n\n login(request, user)\n return Response(\n {\n 'message': 'Your account info is correct',\n },\n status=status.HTTP_200_OK\n )\n else:\n return Response(\n serial.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\nclass EditProfile(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n\n def get(self, request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n else:\n information = Student.objects.get(user = request.user)\n serializer = StudentInformationSerializer(instance=information)\n # serializer = StudentInformationSerializer(instance=information,many=True)\n return Response(\n {\n 'data' : serializer.data\n },\n status=status.HTTP_200_OK\n )\n\n\n def put(self,request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n else:\n information = Student.objects.get(user = request.user)\n serializer = EditProfileSerializer(instance=information,data=request.data)\n if serializer.is_valid():\n serializer.save()\n\n return Response(\n {\n 'message': 'your account have been Edited successfuly',\n 'data': serializer.data\n },\n status=status.HTTP_200_OK\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\nclass RequestForgetEmail(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def post(self,request):\n\n serializer = ForgetEmailSerializer(data=request.data) #request.POST['email']\n if serializer.is_valid():\n try:\n user = Users.objects.get(username=serializer.data['username'])\n except ObjectDoesNotExist:\n return Response(\n {\n 'message': 'There is not any account with this username'\n },\n status=status.HTTP_404_NOT_FOUND\n )\n\n newpassword = newpass.get_code(10)\n send_mail('New Password', 'This is Your New Password : {}'.format(newpassword),'utfarabi@gmail.com', user.username.split())\n user.set_password(newpassword)\n user.save()\n\n return Response(\n {\n 'message':'A New Email Sended successfuly!!!'\n },\n status=status.HTTP_200_OK\n )\n\n else:\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\n\nclass LogOutView(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def post(self, request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n\n else:\n request.session.flush()\n request.user = AnonymousUser()\n return Response(\n {\n 'message': 'Your account info is correct',\n },\n status=status.HTTP_200_OK\n )\n\n\n\n\nclass Inbox(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n def get(self, request):\n if type(request.user) is AnonymousUser:\n return Response(\n {\n 'message' : 'UnAuthorize !!!'\n },\n status=status.HTTP_401_UNAUTHORIZED\n )\n serializedData = InboxSerializer(data=request.Get)\n if serializedData.is_valid():\n weeklyReport = WeeklyReport()\n attendanceTable = AttendanceTable()\n roll = InboxSerializer.data['userRole']\n user = Users.objects.get(user = request.user)\n if roll == 'FacultyTrainingStaff':\n request = Request.objects.filter(Q(applicant__major=user.roles.department) & Q(agreement__state__state=2))\n opinion = Opinion.objects.filter(request__state=1)\n elif roll == 'DepartmentHead':\n request = Request.objects.filter(Q(applicant__major=user.roles.department) & Q(agreement__state__state=1))\n opinion = Opinion.objects.filter(Q(user__roles__role='DepartmentHead') & Q(request__state=2))\n elif roll == 'UniversityTrainingStaff':\n request = Request.objects.filter(Q(applicant__major=user.roles.department) & Q(agreement__state__state=3))\n opinion = Opinion.objects.filter(Q(user__roles__role='UniversityTrainingStaff') & Q(request__state=3))\n elif roll == 'Teacher':\n request = Request.objects.filter(Q(applicant__major=user.roles.department) & Q(agreement__state__state=4))\n opinion = Opinion.objects.filter(Q(user__roles__role='UniversityTrainingStaff') & Q(request__state=3))\n weeklyReport = WeeklyReport.objects.filter(internShip__guideTeacher__user=request.user)\n attendanceTable = AttendanceTable.objects.filter(internShip__guideTeacher__user=request.user)\n\n\n\n\n\n\n else:\n return Response(\n {\n 'message': 'InAccessibility !!!'\n },\n status=status.HTTP_403_FORBIDDEN\n )\n\n if 'first_name' in serializedData.data:\n opinion.filter(\n request__student__user__first_name__contains = serializedData.data['first_name']\n )\n attendanceTable.objects.filter(\n internShip__student__user__first_name__contain = serializedData.data['first_name']\n )\n request.filter(\n applicant__user__first_name=serializedData.data['first_name']\n )\n if 'last_name' in serializedData.data:\n opinion.filter(\n request__student__user__last_name__contains = serializedData.data['last_name']\n )\n attendanceTable.objects.filter(\n internShip__student__user__last_name__contain=serializedData.data['last_name']\n )\n request.filter(\n applicant__user__first_name__contain=serializedData.data['last_name']\n )\n\n","sub_path":"public/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"44236759","text":"import lux\nimport numpy as np\n\n\ndef get_hash(vis: lux.vis.Vis) -> str:\n # Get the visualization hash for a Vis object\n # Vis(...) --> 'Vis (x: reviews_per_month, y: number_of_reviews)'\n vis_hash = vis.__repr__()\n return vis_hash.split(\"mark\")[0][1:-1]\n\n\ndef convert_vlist_to_hashmap(vlist):\n # Convert VisList to dictionary representation\n # {'Vis (x: ..., y: ...)': 0.55,\n # 'Vis (x: ..., y: ...)': 0.22,\n # ...}\n vdict = {}\n for vis in vlist:\n vdict[get_hash(vis)] = vis.score\n return vdict\n\n\ndef get_aligned_dict(vdict, global_map):\n # Align each vdict based on global map\n aligned_dict = {}\n for vis in global_map:\n if vis in vdict:\n aligned_dict[vis] = vdict[vis]\n else:\n aligned_dict[vis] = 0\n return aligned_dict\n\n\n# def dcg(r, k, method=0,debug=False):\n# r = np.asfarray(r)[:k]\n# val = 0\n# for i in range(1,len(r)+1):\n# val+= (r[i-1]) / np.log2(i+1)\n# if debug:\n# print (\"i=\",i,\":\",(r[i-1]) ,\"/\", np.log2(i+1))\n# print ((r[i-1]) / np.log2(i+1))\n# return val\n\n# def ndcg(ground_truth_r,r, k,debug=False):\n# return dcg(r, k,debug=debug) / dcg(ground_truth_r,k,debug=debug)\n\n\ndef compute_ndcg_between_vislists(\n l1: lux.vis.VisList, l2: lux.vis.VisList, k: int\n) -> float:\n if len(l1)==len(l2)==1: \n return 1\n l1_scores = [vis.score for vis in l1]\n map1 = convert_vlist_to_hashmap(l1)\n\n l2_scores = [vis.score for vis in l2]\n map2 = convert_vlist_to_hashmap(l2)\n\n # Combine two dictionaries map1,map2 into a single global_map\n global_map = set(map1.keys())\n global_map.update(set(map2.keys()))\n global_map = list(global_map)\n\n # Somehow our own NDCG calculation always leads to > 1\n # aligned_score1 = list(get_aligned_dict(map1,global_map).values())\n # aligned_score2 = list(get_aligned_dict(map2,global_map).values())\n # return ndcg(aligned_score1,aligned_score2,5)\n\n # from scipy.stats import stats\n # rank1 = stats.rankdata(aligned_score1)\n # rank2 =stats.rankdata(aligned_score2)\n # return ndcg(rank1,rank2,3)\n aligned_score1 = np.asarray([list(get_aligned_dict(map1, global_map).values())])\n aligned_score2 = np.asarray([list(get_aligned_dict(map2, global_map).values())])\n from sklearn.metrics import ndcg_score\n\n return ndcg_score(aligned_score1, aligned_score2, k=k)\n\n\n\ndef compute_prf_between_vislists(map1, map2) -> float:\n assert len(map1)==len(map2)\n map1 = sort_transform_dict(map1)\n map2 = sort_transform_dict(map2)\n gt = np.array(list(map1.keys()))\n retrieved = np.array(list(map2.keys()))\n binarize_ground_truth_r = np.ones_like(gt,dtype=int)\n binarize_r = []\n for x in gt:\n if x in retrieved:\n binarize_r.append(1)\n else : \n binarize_r.append(0)\n binarize_r = np.array(binarize_r)\n from sklearn import metrics\n p,r,f,_ = metrics.precision_recall_fscore_support(binarize_ground_truth_r,binarize_r,average='binary')\n return p,r,f\n\ndef sort_transform_dict(dictmap):\n # x and y swapped sometimes during correlation, causing the scores to be low\n # the sort transform orders the vis signature string so that it is independent of x or y (content only matching)\n srt_keys = []\n for key in list(dictmap.keys()):\n srt_keys.append(\"\".join(sorted(key)))\n return dict(zip(srt_keys,dictmap.values()))\n# Tests\n# ground_truth_ratings = [1,2,3,4,5,6]\n# example_ratings = [3,2,3,0,1,2]\n# ideal_ordering = [3,3,3,2,2,2,1,0]\n# assert np.isclose(dcg(example_ratings,6),6.861,1e-2) #check DCG calculation (Based on Wikipedia example)\n# assert np.isclose(ndcg(ideal_ordering,[3,2,3,0,1,2],6),0.785,1e-2) #check NDCG calculation (Based on Wikipedia example)\n# assert np.isclose(ndcg([3,1,2],[3, 1, 2],3),1) #sanity check\n\n","sub_path":"utils/rank_utils.py","file_name":"rank_utils.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"164472621","text":"# ch35_3.py\r\nfrom pytube import YouTube\r\nimport os\r\n\r\npath = \"d:\\\\myYouTube\"\r\nif not os.path.isdir(path): # 如果不存在則建立此資料夾\r\n os.mkdir(path)\r\n\r\nyt = YouTube(\"https://www.youtube.com/watch?v=p9QU72Tzhg8\")\r\nvideoViews = yt.views\r\nprint(\"影片觀賞次數 : \", videoViews)\r\nvideoSeconds = yt.length\r\nprint(\"影片長度(秒) : \", videoSeconds)\r\nvideoRating = yt.rating\r\nprint(\"影片評價 : \", videoRating)\r\nvideoTitle = yt.title\r\nprint(\"影片標題 : \", videoTitle, \"下載中 ... \")\r\nyt.streams.first().download(path) # 所下載影音檔案儲存在path\r\nprint(\"下載完成 ... \")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"exercise/learn_python_dm2039/ch35/ch35_3.py","file_name":"ch35_3.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"403168444","text":"from lxml import etree\nimport csv\nfrom glob import glob\nimport codecs\n\nset_list =[]\n\nfor f in glob(\"pset_xml\\qto\\*.xml\"):\n\n tree = etree.parse(f)\n root = tree.getroot()\n\n mynsmap = {}\n mynsmap = root.nsmap\n\n QtoSet_Name = [i.text for i in root.iterfind('Name', namespaces=mynsmap)]\n ApplicableClasses = [i.text for i in root.iterfind('ApplicableClasses/ClassName', namespaces=mynsmap)]\n\n QtoDef_Names = [i.text for i in root.iterfind('QtoDefs/QtoDef/Name', namespaces=mynsmap)]\n QtoDef_Definitions = [i.text for i in root.iterfind('QtoDefs/QtoDef/Definition', namespaces=mynsmap)]\n QtoDef_Type = [i.text for i in root.iterfind('QtoDefs/QtoDef/QtoType', namespaces=mynsmap)]\n\n QtoDef_NameAliase_jp =[i.text for i in root.iterfind('QtoDefs/QtoDef/NameAliases/NameAlias[@lang=\"ja-JP\"]', namespaces=mynsmap)]\n QtoDef_DinfinitionAlias_jp =[i.text for i in root.iterfind('QtoDefs/QtoDef/DefinitionAliases/DefinitionAlias[@lang=\"ja-JP\"]', namespaces=mynsmap)]\n\n # print(set_list)\n\n for i in range(len(QtoDef_Names)):\n row = []\n row.append(QtoSet_Name[0])\n row.append(ApplicableClasses[0])\n row.append(QtoDef_Names[i])\n row.append(QtoDef_Type[i])\n try:\n row.append(QtoDef_Definitions[i])\n except:\n row.append(\"none\")\n set_list.append(row)\n\nwith codecs.open('qset_list_EN.csv', 'a', \"utf-8\") as f:\n writer = csv.writer(f, delimiter='\\t')\n writer.writerows(set_list)\n\n","sub_path":"ifc4.0_quontity_set_xml_parser_EN.py","file_name":"ifc4.0_quontity_set_xml_parser_EN.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"21477330","text":"###########################################################################\n# Copyright 2020 IoT.bzh\n#\n# author: Fulup Ar Foll \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\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom configparser import ConfigParser, NoOptionError, NoSectionError\n\nimport os\nimport warnings\nimport logging\nlogger = logging.getLogger('dnf')\n\nimport dnf\nimport dnf.logging\nimport reddnf\n\n\n@dnf.plugin.register_command\nclass RedInstallCommand(dnf.cli.Command):\n\n aliases = ['red-install', 'rin']\n summary = \"Install rpm package in final redpath leaf\"\n _dnfcmd = None\n\n def __init__(self, cli):\n super(RedInstallCommand, self).__init__(cli)\n self.opts = None\n self.parser = None\n RedInstallCommand._dnfcmd = dnf.cli.commands.install.InstallCommand(cli)\n RedInstallCommand._dnfcmd2= dnf.cli.commands.reinstall.ReinstallCommand(cli)\n\n @staticmethod\n def set_argparser(parser):\n parser.add_argument(\"--redpath\", help=\"container hierarchical rootfs path ex: /var/redpak/platform/profile/project\")\n parser.add_argument(\"--update\", default=False, action='store_true', help=\"force reinstallation even when node exist\")\n RedInstallCommand._dnfcmd.set_argparser(parser)\n\n # Never request any default dnf activation\n def configure(self):\n demands = self.cli.demands\n demands.sack_activation = False\n demands.root_user = False\n demands.available_repos = False\n\n # needed for install\n demands.resolving=True\n demands.allow_erasing = True\n\n # check we redpath is defined and exist\n if not self.opts.redpath:\n raise dnf.exceptions.Error(\"Syntax Error: redpak --redpath=/xx/../xyz subcommand (missing --redpath)\")\n\n if not os.path.isdir(self.opts.redpath):\n raise dnf.exceptions.Error(\"Error: Directory redpak should exist [{}]\".format(self.opts.redpath))\n\n if not os.access(self.opts.redpath, os.W_OK):\n raise dnf.exceptions.Error(\"Redpath not writable redpath=/xx/../xyz (check user permission)\")\n\n # Merge source default with main config environment\n self.redconf=reddnf.config.rednode_defaults(self.opts, None)\n\n def checkdir(self, label, dirpath, create=False):\n\n if create:\n try:\n os.makedirs(dirpath)\n except FileExistsError:\n pass\n except OSError:\n raise dnf.exceptions.Error(\"Directory {} gail to create not exit path={}\".format(label, dirpath))\n\n if not os.access(dirpath, os.W_OK):\n raise dnf.exceptions.Error(\"Directory {} not writable (check user permission) path={}\".format(label, dirpath))\n\n def run(self):\n\n # check terminal leaf node and set dnf persisdir and copy environment to dnf conf\n node= reddnf.config.ParseNode(defaults=self.redconf, redpath=self.opts.redpath)\n node.CopyEnvTo(self.base.conf, \"gpgcheck\")\n node.CopyEnvTo(self.base.conf, \"persistdir\")\n\n # check persistant path exist and are writable\n self.checkdir(\"redpath\", self.opts.redpath)\n self.checkdir(\"dnf persistdir\", self.base.conf.persistdir, create=True)\n\n # Create an empty libsolv dependencies sack\n reddnf.sack.repo_create_empty(self.base, \"@rpmdb\")\n\n # Scan redpath and add existing rpm to libsolv\n dirlist = reddnf.config.redpath_split (self.opts.redpath)\n for entry in dirlist:\n # check rednode as a valid status\n reddnf.sack.repo_load_rpmdb (self.base, entry[0], entry[1])\n\n\n # finally add avaliable remote repo from redpath termination leaf\n dnf.conf.installroot=self.opts.redpath\n reddnf.sack.repo_load_available (self.base, self.opts.redpath)\n\n # update dnf command argument list, reset rootdir to rootpth and run\n if not self.opts.update:\n RedInstallCommand._dnfcmd.opts = self.opts\n RedInstallCommand._dnfcmd.run()\n else:\n RedInstallCommand._dnfcmd2.opts = self.opts\n RedInstallCommand._dnfcmd2.run()\n","sub_path":"red-dnf/plugin-dnf/red-install.py","file_name":"red-install.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270132178","text":"import datetime\nimport const.stat as ic\nfrom PyQt5.QtCore import *\n\n\nclass SellJob:\n def __init__(self, qobject):\n # parent object\n self.par = qobject\n self.today = datetime.date.today()\n\n # timer handler\n def watch_handler(self):\n current_time = QTime.currentTime()\n curtime = int(current_time.toString(\"HHmmss\"))\n self.par.logger.info(\"watch handler : \" + current_time.toString(\"HH:mm:ss\"))\n\n # retrieve account items\n if int(self.par.start_time) <= curtime < int(self.par.start_time+64000):\n self.acct_items()\n # program ends\n elif int(curtime) >= int(self.par.start_time)+70000:\n self.par.shut_down()\n\n # update unsold items\n\n\n # retrieve account items\n def acct_items(self):\n self.par.logger.info(\"retrieve account items\")\n\n param = dict()\n param[\"계좌번호\"] = ic.telegram[\"accnt_no\"]\n\n self.par.kiwoom.tr_request(param, \"OPT10085_req\", \"OPT10085\", 0, \"5454\")\n\n # determine to sell or not, notify when certain condition is met\n def determine(self, price, min_price, buy_price):\n self.par.logger.info(\"determine\")\n\n for key, value in price.items():\n # filter today's sold item\n if int(buy_price[key]) <= 0:\n continue\n\n rate = round((int(value[-1]) - int(buy_price[key])) / int(buy_price[key]), 2)\n self.par.logger.info(str(key) + \" | current : \" + str(value[-1]) + \", rate : \" + str(rate))\n\n # rate should be greater than 1%\n if rate > 0.01:\n # sell when it goes down less than minimum of 10 minutes\n if int(value[-1]) <= int(min_price[key]):\n self.sell_order(key, value[-1])\n\n # sell order(api call and db insert)\n def sell_order(self, item, price):\n print(item + \" : \" + price)\n\n # sell order callback(db update)","sub_path":"sell/sell.py","file_name":"sell.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289582289","text":"import pytest\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n '--test-db-url',\n action='store',\n dest='TEST_DB_URL',\n default='mongodb://localhost:27017',\n help=(\n 'DB url for testing (e.g. mongodb://mongodb:27017)'\n )\n )\n\n\n@pytest.fixture\ndef db_url(request):\n return request.config.getoption(\"TEST_DB_URL\")\n","sub_path":"application/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"467245480","text":"import base64\nimport hashlib\nimport hmac\nimport json\nimport os\nfrom functools import wraps\n\nimport requests\nfrom flask import Flask, Response, current_app, request, abort\n\n\nLANGUAGES = {\n 'ly133': 'en',\n 'ly132': 'fr',\n}\n\n\napp = Flask(__name__)\n\n\ndef _hmac_is_valid(data, secret, hmac_to_verify):\n hash_ = hmac.new(secret, msg=data, digestmod=hashlib.sha256)\n hmac_calculated = base64.b64encode(hash_.digest())\n return hmac.compare_digest(hmac_calculated, hmac_to_verify)\n\n\n@app.route('/products.xml')\ndef products():\n xml = '''\n\t\n\t \n\t TAMMY & BENJAMIN\n\t https://www.tammyandbenjamin.com\n\t Leather goods\n\n\t \n\t 6747611905\n\t ALEXIA - Figue\n\t Le ladybag par excellence\n\t https://www.tammyandbenjamin.com/products/alexia-figue\n\t https://cdn.shopify.com/s/files/1/0343/0553/products/ALEXIA_Fig_01_1200x630.jpg\n\t new\n\t in stock\n\t 500.00 EUR\n\t TAB\n\t \n\n\t \n\t 6747643585\n\t ALEXIA - Noir ébène\n\t Le ladybag par excellence\n\t https://www.tammyandbenjamin.com/products/alexia-noir-ebene\n\t https://cdn.shopify.com/s/files/1/0343/0553/products/ALEXIA_Black_01_1200x630.jpg\n\t new\n\t in stock\n\t 500.00 EUR\n\t TAB\n\t \n\n\t \n\t\n '''\n return Response(xml, mimetype='text/xml')\n\n\n@app.route('/order_hook', methods=['POST'])\ndef order_hook():\n try:\n topic = request.headers['X-Shopify-Topic']\n webhook_hmac = request.headers['X-Shopify-Hmac-Sha256'].encode()\n json.loads(request.get_data().decode())\n except Exception as e:\n current_app.logger.error(e)\n return abort(400)\n if not _hmac_is_valid(request.get_data(), os.environ['SHOPIFY_SECRET'].encode(), webhook_hmac):\n current_app.logger.error('HMAC not valid for webhook')\n return abort(403)\n\n mc_api_version = os.environ['MC_API_VERSION']\n mc_api_key = os.environ['MC_API_KEY']\n _, mc_zone = mc_api_key.split('-')\n mc_auth = ('tabfeeds', mc_api_key)\n mc_base_url = 'https://{}.api.mailchimp.com/{}/'.format(mc_zone, mc_api_version)\n\n data = request.get_json()\n customer_email = data['customer']['email']\n customer_lang = None\n for attr in data['note_attributes']:\n if attr['name'] == 'language':\n customer_lang = attr['value']\n customer_lang = LANGUAGES.get(customer_lang, 'fr')\n\n search_path = 'search-members'\n payload = {\n 'query': customer_email,\n }\n response = requests.get(mc_base_url + search_path, params=payload, auth=mc_auth)\n data = response.json()\n\n matches = data['exact_matches']\n if matches['total_items'] == 0:\n current_app.logger.warning('No member found for email {}', customer_email)\n return 'ok'\n member_urls = {'{}/lists/{}/members/{}'.format(mc_base_url, member['list_id'], member['id']) for member in matches['members']}\n for member_url in member_urls:\n payload = {\n 'language': customer_lang,\n }\n response = requests.patch(member_url, params=payload, auth=mc_auth)\n return 'ok'\n","sub_path":"tabfeeds/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"47651080","text":"from dontbreak.models import User, Streak, Commit, Tag, TaggedCommit\nfrom nose import tools as test\n\n\nclass TestCommit:\n def setup(self):\n self.user = User.create(email='testuser@gmail.com')\n self.streak = Streak.create(user=self.user, name='')\n\n def teardown(self):\n self.streak.delete_instance()\n self.user.delete_instance()\n\n def test_get_tags(self):\n commit = Commit.create(streak=self.streak, message='Hello #tag1 #tag2')\n tag1 = Tag.create(name='tag1', streak=self.streak)\n tag2 = Tag.create(name='tag2', streak=self.streak)\n TaggedCommit.create(commit=commit, tag=tag1)\n TaggedCommit.create(commit=commit, tag=tag2)\n test.assert_equal({'tag1', 'tag2'}, commit.get_tags())\n commit.delete_instance()\n Tag.delete().execute()\n TaggedCommit.delete().execute()\n\n def test_save(self):\n commit = Commit.create(streak=self.streak, message='Hello #tag1 #tag2')\n test.assert_equal({'tag1', 'tag2'}, commit.get_tags())\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"333511469","text":"'''\nGiven a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. \nIf target exists, then return its index, otherwise return -1.\n\nAssumption : No duplicates exists..\n'''\n\nclass binarySearch:\n def __init__(self, searchList):\n self.searchList = searchList\n \n def search(self, target):\n list1 = self.searchList\n left=0\n right=len(list1)-1\n while left <= right:\n pivot = int((left + right)/2)\n print(list1[pivot])\n if list1[pivot] == target:\n return pivot\n else:\n if list1[pivot] < target:\n left = pivot + 1\n else:\n right = pivot - 1\n return -1 \n \nlist1 = [1, 2, 3,4,5]\ntarget=6\nbs = binarySearch(list1)\nindex = bs.search(target)\nif str(index) == \"-1\":\n print(\"Target \" + str(target) + \" not found in given sorted array\")\nelse: \n print(\"Target \" + str(target) + \" found in given sorted array at position \" + str(index))\n\n \n","sub_path":"binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"113562793","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 6 19:03:00 2019\n\n@author: ZhuKai\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt#约定俗成的写法plt\nimport linecache\n\n#为了方便,避免忘记close掉这个文件对象,可以用下面这种方式替代\nkey_loss = \"eval mean loss:\"\nkey_IoU = \"eval point avg class IoU:\"\nkey_acc = \"eval point accuracy:\"\ntrain_loss = []\ntest_loss = []\ntrain_IoU = []\ntest_IoU = []\ntrain_acc = []\ntest_acc = []\ni=0\nwith open('log_train_1.txt',\"r\") as f: #设置文件对象,log2019_12_13_00_55_35下的实验是对比原始pointconv\n for line in f.readlines():\n i=i+1\n if key_loss in line:\n test_loss.append(float(line[len(key_loss):-1]))\n the_line = linecache.getline('log_train.txt', i-6) \n train_loss.append(float(the_line[10:-1]))\n if key_IoU in line:\n test_IoU.append(float(line[len(key_IoU):-1]))\n the_line = linecache.getline('log_train.txt', i-5) \n train_IoU.append(float(the_line[10:-1]))#-train_loss[-1]-np.random.rand()/50) #过拟合了\n if key_acc in line:\n test_acc.append(float(line[len(key_acc):-1]))\n the_line = linecache.getline('log_train.txt', i-7) \n train_acc.append(float(the_line[10:-1]))#-0.1) #过拟合了\n\nx=np.linspace(1,50,50,endpoint=True)\nl1, = plt.plot(x,test_loss,'r-')\nl2, = plt.plot(x,train_loss,'b--')\nplt.legend([l1, l2], ['test loss', 'train loss'], loc = 'upper right')\nplt.show()\n\nl1, = plt.plot(x,test_IoU,'r-')\nl2, = plt.plot(x,train_IoU,'b--')\nplt.legend([l1, l2], ['test IoU', 'train IoU'], loc = 'upper right')\nplt.show()\n\nl1, = plt.plot(x,test_acc,'r-')\nl2, = plt.plot(x,train_acc,'b--')\nplt.legend([l1, l2], ['test accuracy', 'train accuracy'], loc = 'upper right')\nplt.show()\n\n\n\n\n","sub_path":"Panicle-3D/log2019_11_12_14_59_50/ResultVisualization.py","file_name":"ResultVisualization.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"477469249","text":"import re\n\ndef main():\n\twith open('cybs.html', 'r', encoding='utf8') as fin:\n\t\tdata = fin.read()\n\t\tres = re.findall(r'(.*?)<\\/a>', data)\n\t\tprint(res)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"招聘面试/后端/编程/正则表达式/get_cybs.py","file_name":"get_cybs.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"88533550","text":"import numpy as np\nfrom astropy import units as u\nfrom astropy.table import Table\nfrom astropy.visualization import quantity_support\nfrom gammapy.extern.skimage import block_reduce\nfrom gammapy.utils.interpolation import ScaledRegularGridInterpolator\nfrom gammapy.utils.regions import compound_region_to_list\nfrom .core import Map\nfrom .geom import pix_tuple_to_idx\nfrom .region import RegionGeom\nfrom .utils import INVALID_INDEX\n\n__all__ = [\"RegionNDMap\"]\n\n\nclass RegionNDMap(Map):\n \"\"\"Region ND map\n\n Parameters\n ----------\n geom : `~gammapy.maps.RegionGeom`\n Region geometry object.\n data : `~numpy.ndarray`\n Data array. If none then an empty array will be allocated.\n dtype : str, optional\n Data type, default is float32\n meta : `dict`\n Dictionary to store meta data.\n unit : str or `~astropy.units.Unit`\n The map unit\n \"\"\"\n\n def __init__(self, geom, data=None, dtype=\"float32\", meta=None, unit=\"\"):\n if data is None:\n data = np.zeros(geom.data_shape, dtype=dtype)\n\n self._geom = geom\n self.data = data\n self.meta = meta\n self.unit = u.Unit(unit)\n\n def plot(self, ax=None, **kwargs):\n \"\"\"Plot region map.\n\n Parameters\n ----------\n ax : `~matplotlib.pyplot.Axis`\n Axis used for plotting\n **kwargs : dict\n Keyword arguments passed to `~matplotlib.pyplot.errorbar`\n\n Returns\n -------\n ax : `~matplotlib.pyplot.Axis`\n Axis used for plotting\n \"\"\"\n import matplotlib.pyplot as plt\n\n ax = ax or plt.gca()\n\n kwargs.setdefault(\"fmt\", \".\")\n\n if len(self.geom.axes) > 1:\n raise TypeError(\n \"Use `.plot_interactive()` if more the one extra axis is present.\"\n )\n\n axis = self.geom.axes[0]\n\n with quantity_support():\n xerr = (axis.center - axis.edges[:-1], axis.edges[1:] - axis.center)\n ax.errorbar(axis.center, self.quantity.squeeze(), xerr=xerr, **kwargs)\n\n if axis.interp == \"log\":\n ax.set_xscale(\"log\")\n\n ax.set_xlabel(axis.name.capitalize() + f\" [{axis.unit}]\")\n\n if not self.unit.is_unity():\n ax.set_ylabel(f\"Data [{self.unit}]\")\n\n ax.set_yscale(\"log\")\n return ax\n\n def plot_hist(self, ax=None, **kwargs):\n \"\"\"Plot as histogram.\n\n kwargs are forwarded to `~matplotlib.pyplot.hist`\n\n Parameters\n ----------\n ax : `~matplotlib.axis` (optional)\n Axis instance to be used for the plot\n **kwargs : dict\n Keyword arguments passed to `~matplotlib.pyplot.hist`\n\n Returns\n -------\n ax : `~matplotlib.pyplot.Axis`\n Axis used for plotting\n \"\"\"\n import matplotlib.pyplot as plt\n\n ax = plt.gca() if ax is None else ax\n\n kwargs.setdefault(\"histtype\", \"step\")\n kwargs.setdefault(\"lw\", 2)\n\n axis = self.geom.axes[0]\n\n with quantity_support():\n weights = self.data[:, 0, 0]\n ax.hist(axis.center.value, bins=axis.edges.value, weights=weights, **kwargs)\n\n ax.set_xlabel(axis.name.capitalize() + f\" [{axis.unit}]\")\n\n if not self.unit.is_unity():\n ax.set_ylabel(f\"Data [{self.unit}]\")\n\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n return ax\n\n def plot_interactive(self):\n raise NotImplementedError(\n \"Interactive plotting currently not support for RegionNDMap\"\n )\n\n def plot_region(self, ax=None, **kwargs):\n \"\"\"Plot region\n\n Parameters\n ----------\n ax : `~astropy.vizualisation.WCSAxes`\n Axes to plot on.\n **kwargs : dict\n Keyword arguments forwarded to `~regions.PixelRegion.as_artist`\n \"\"\"\n import matplotlib.pyplot as plt\n from matplotlib.collections import PatchCollection\n\n if ax is None:\n ax = plt.gca()\n\n regions = compound_region_to_list(self.geom.region)\n artists = [region.to_pixel(wcs=ax.wcs).as_artist() for region in regions]\n\n patches = PatchCollection(artists, **kwargs)\n ax.add_collection(patches)\n return ax\n\n @classmethod\n def create(cls, region, axes=None, dtype=\"float32\", meta=None, unit=\"\", wcs=None):\n \"\"\"\n\n Parameters\n ----------\n region : str or `~regions.SkyRegion`\n Region specification\n axes : list of `MapAxis`\n Non spatial axes.\n dtype : str\n Data type, default is 'float32'\n unit : str or `~astropy.units.Unit`\n Data unit.\n meta : `dict`\n Dictionary to store meta data.\n wcs : `~astropy.wcs.WCS`\n WCS projection to use for local projections of the region\n\n Returns\n -------\n map : `RegionNDMap`\n Region map\n \"\"\"\n geom = RegionGeom.create(region=region, axes=axes, wcs=wcs)\n return cls(geom=geom, dtype=dtype, unit=unit, meta=meta)\n\n def downsample(self, factor, preserve_counts=True, axis=\"energy\"):\n geom = self.geom.downsample(factor=factor, axis=axis)\n block_size = [1] * self.data.ndim\n idx = self.geom.get_axis_index_by_name(axis)\n block_size[-(idx + 1)] = factor\n\n func = np.nansum if preserve_counts else np.nanmean\n data = block_reduce(self.data, tuple(block_size[::-1]), func=func)\n\n return self._init_copy(geom=geom, data=data)\n\n def upsample(self, factor, preserve_counts=True, axis=\"energy\"):\n geom = self.geom.upsample(factor=factor, axis=axis)\n data = self.interp_by_coord(geom.get_coord())\n\n if preserve_counts:\n data /= factor\n\n return self._init_copy(geom=geom, data=data)\n\n def fill_by_idx(self, idx, weights=None):\n idx = pix_tuple_to_idx(idx)\n\n msk = np.all(np.stack([t != INVALID_INDEX.int for t in idx]), axis=0)\n idx = [t[msk] for t in idx]\n\n if weights is not None:\n if isinstance(weights, u.Quantity):\n weights = weights.to_value(self.unit)\n weights = weights[msk]\n\n idx = np.ravel_multi_index(idx, self.data.T.shape)\n idx, idx_inv = np.unique(idx, return_inverse=True)\n weights = np.bincount(idx_inv, weights=weights).astype(self.data.dtype)\n self.data.T.flat[idx] += weights\n\n def get_by_idx(self, idxs):\n return self.data[idxs[::-1]]\n\n def interp_by_coord(self, coords):\n pix = self.geom.coord_to_pix(coords)\n return self.interp_by_pix(pix)\n\n def interp_by_pix(self, pix, method=\"linear\", fill_value=None):\n grid_pix = [np.arange(n, dtype=float) for n in self.data.shape[::-1]]\n\n if np.any(np.isfinite(self.data)):\n data = self.data.copy().T\n data[~np.isfinite(data)] = 0.0\n else:\n data = self.data.T\n\n fn = ScaledRegularGridInterpolator(\n grid_pix, data, fill_value=fill_value, method=method\n )\n return fn(tuple(pix), clip=False)\n\n def set_by_idx(self, idx, value):\n self.data[idx[::-1]] = value\n\n @staticmethod\n def read(cls, filename):\n raise NotImplementedError\n\n def write(self, filename):\n raise NotImplementedError\n\n def to_hdulist(self):\n raise NotImplementedError\n\n @classmethod\n def from_hdulist(cls, hdulist, format=\"ogip\", ogip_column=\"COUNTS\"):\n \"\"\"Create from `~astropy.io.fits.HDUList`.\n\n\n Parameters\n ----------\n hdulist : `~astropy.io.fits.HDUList`\n HDU list.\n format : {\"ogip\"}\n Format specification\n ogip_column : str\n OGIP data format column\n\n Returns\n -------\n region_nd_map : `RegionNDMap`\n Region map.\n \"\"\"\n if format != \"ogip\":\n raise ValueError(\"Only 'ogip' format supported\")\n\n table = Table.read(hdulist[\"SPECTRUM\"])\n geom = RegionGeom.from_hdulist(hdulist, format=format)\n\n return cls(geom=geom, data=table[ogip_column].data, meta=table.meta)\n\n def crop(self):\n raise NotImplementedError(\"Crop is not supported by RegionNDMap\")\n\n def pad(self):\n raise NotImplementedError(\"Pad is not supported by RegionNDMap\")\n\n def sum_over_axes(self, keepdims=True):\n axis = tuple(range(self.data.ndim - 2))\n geom = self.geom.to_image()\n if keepdims:\n for ax in self.geom.axes:\n geom = geom.to_cube([ax.squash()])\n data = np.nansum(self.data, axis=axis, keepdims=keepdims)\n # TODO: summing over the axis can change the unit, handle this correctly\n return self._init_copy(geom=geom, data=data)\n\n def stack(self, other, weights=None):\n \"\"\"Stack other region map into map.\n\n Parameters\n ----------\n other : `RegionNDMap`\n Other map to stack\n weights : `RegionNDMap`\n Array to be used as weights. The spatial geometry must be equivalent\n to `other` and additional axes must be broadcastable.\n \"\"\"\n data = other.data\n\n # TODO: re-think stacking of regions. Is making the union reasonable?\n # self.geom.union(other.geom)\n\n if weights is not None:\n if not other.geom.to_image() == weights.geom.to_image():\n raise ValueError(\"Incompatible geoms between map and weights\")\n data = data * weights.data\n\n self.data += data\n\n def to_table(self):\n \"\"\"Convert to `~astropy.table.Table`.\n\n Data format specification: :ref:`gadf:ogip-pha`\n \"\"\"\n energy_axis = self.geom.axes[0]\n channel = np.arange(energy_axis.nbin, dtype=np.int16)\n counts = np.array(self.data[:, 0, 0], dtype=np.int32)\n\n names = [\"CHANNEL\", \"COUNTS\"]\n meta = {\"name\": \"COUNTS\"}\n\n return Table([channel, counts], names=names, meta=meta)\n","sub_path":"gammapy/maps/regionnd.py","file_name":"regionnd.py","file_ext":"py","file_size_in_byte":9986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"4624344","text":"import requests\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\n# Number of days between attempts\nexpiry_time = 7\ndate_format = \"%Y-%m-%d %H:%M\"\n\nclass Detail:\n def __init__(self, name, url):\n self.name = name\n self.url = url\n\ndef retrieve(config):\n url = config[\"destination\"]\n\n for path in config[\"paths\"]:\n last = datetime.strptime(path[\"last_updated\"],date_format)\n full_url = url+path[\"path\"]\n r = requests.get(full_url)\n if r.status_code == 200:\n _extract_details(r.content,last)\n\n\ndef _extract_details(content, last_updated):\n soup = BeautifulSoup(content, 'html.parser')\n tr = soup.find_all(\"tr\")\n\n items = []\n for line in tr:\n td = line.find_all('td')\n detail = _extract_detail(td, last)\n if detail is not None:\n items.append(detail)\n\n return items\n\ndef _extract_detail(rows, last_updated):\n iteration = 0\n date = None\n name = None\n url = None\n for row in rows:\n if iteration == 1:\n url = row.a['href']\n name = row.a.get_text()\n if iteration == 2:\n date = row.get_text().strip()\n iteration += 1\n if date is not None and name is not None and url is not None:\n detail_added = datetime.strptime(date,date_format)\n if detail_added > last_updated:\n return Detail(name,url)\n return None\n","sub_path":"kagu/retriever.py","file_name":"retriever.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"127260807","text":"from sympy.ntheory import factorint\nimport sys\nimport json\n\n#the goal, for all given integers 3<=n<=2*10^7\n#is to calculate the largest positive number m 1:\n max_n = int(sys.argv[1])\n\n\nprint(json.dumps(generate_samples(max_n)\n,indent=1))\n","sub_path":"OldWork/generate_samples.py","file_name":"generate_samples.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"52137467","text":"# -*- coding: utf-8 -*-\r\n\r\n##############################################################################\r\n# Copyright (C) 2020.\r\n# Author: Eng.Ramadan Khalil ()\r\n# website': https://www.linkedin.com/in/ramadan-khalil-a7088164\r\n#\r\n# It is forbidden to publish, distribute, sublicense, or sell copies\r\n# of the Software or modified copies of the Software.\r\n##############################################################################\r\n\r\nfrom odoo import api, fields, models, _\r\nfrom odoo.exceptions import ValidationError, UserError\r\nfrom datetime import date, datetime\r\nfrom pytz import timezone, utc\r\n\r\n\r\n\r\ndef get_float_from_time(time):\r\n str_time = datetime.strftime(time, \"%H:%M\")\r\n split_time = [int(n) for n in str_time.split(\":\")]\r\n float_time = split_time[0] + split_time[1] / 60.0\r\n return float_time\r\n\r\n\r\nclass HrAttendancePolicy(models.Model):\r\n _inherit = 'hr.attendance.policy'\r\n\r\n miss_rule_id = fields.Many2one(comodel_name=\"hr.miss.rule\",\r\n string=\"Missed Punch Rule\", required=False)\r\n shift_allowance_line_ids = fields.One2many('attendance.shift.allowance',\r\n 'policy_id',\r\n 'Attendance Shift Allowances')\r\n\r\n def get_late(self, period, cnt):\r\n res = period\r\n flag = False\r\n no = 1\r\n cnt_flag = False\r\n factor = 1\r\n if period <= 0:\r\n return 0, cnt\r\n if self.late_rule_id:\r\n time_ids = self.late_rule_id.line_ids.sorted(\r\n key=lambda r: r.time, reverse=True)\r\n for line in time_ids:\r\n if period >= line.time:\r\n for counter in cnt:\r\n if counter[0] == line.time:\r\n cnt_flag = True\r\n no = counter[1]\r\n counter[1] += 1\r\n break\r\n if no >= 5 and line.fifth > 0:\r\n factor = line.fifth\r\n elif no >= 4 and line.fourth > 0:\r\n factor = line.fourth\r\n elif no >= 3 and line.third > 0:\r\n factor = line.third\r\n elif no >= 2 and line.second > 0:\r\n factor = line.second\r\n elif no >= 1 and line.first > 0:\r\n factor = line.first\r\n elif no == 0:\r\n factor = 0\r\n if not cnt_flag:\r\n cnt.append([line.time, 2])\r\n flag = True\r\n if line.type == 'rate':\r\n res = line.rate * period * factor\r\n elif line.type == 'fix':\r\n res = line.amount * factor\r\n\r\n break\r\n\r\n if not flag:\r\n res = 0\r\n return res, cnt\r\n\r\n def get_diff(self, period, diff_cnt):\r\n res = period\r\n flag = False\r\n no = 1\r\n cnt_flag = False\r\n factor = 1\r\n if period <= 0:\r\n return 0, diff_cnt\r\n if self.diff_rule_id:\r\n time_ids = self.diff_rule_id.line_ids.sorted(\r\n key=lambda r: r.time, reverse=True)\r\n for line in time_ids:\r\n if period >= line.time:\r\n for counter in diff_cnt:\r\n if counter[0] == line.time:\r\n cnt_flag = True\r\n no = counter[1]\r\n counter[1] += 1\r\n break\r\n if no >= 5:\r\n factor = line.fifth\r\n elif no >= 4:\r\n factor = line.fourth\r\n elif no >= 3:\r\n factor = line.third\r\n elif no >= 2:\r\n factor = line.second\r\n elif no >= 1:\r\n factor = line.first\r\n elif no >= 0:\r\n factor = 1\r\n if not cnt_flag:\r\n diff_cnt.append([line.time, 2])\r\n flag = True\r\n if line.type == 'rate':\r\n res = line.rate * period * factor\r\n elif line.type == 'fix':\r\n res = line.amount * factor\r\n break\r\n if not flag:\r\n res = 0\r\n return res, diff_cnt\r\n\r\n def get_miss(self, cnt):\r\n self.ensure_one()\r\n res = 0\r\n flag = False\r\n if self:\r\n if self.miss_rule_id:\r\n miss_ids = self.miss_rule_id.line_ids.sorted(\r\n key=lambda r: r.counter, reverse=True)\r\n for ln in miss_ids:\r\n if cnt >= int(ln.counter):\r\n res = ln.amount\r\n flag = True\r\n break\r\n if not flag:\r\n res = 0\r\n return res\r\n\r\n def get_shift_allowance(self, date_from, date_to, tz):\r\n if not self.shift_allowance_line_ids:\r\n return 0\r\n date_start_native =utc.localize(\r\n date_from).astimezone(tz)\r\n date_end_native = utc.localize(\r\n date_to).astimezone(tz)\r\n time_start = get_float_from_time(date_start_native)\r\n time_end = get_float_from_time(date_end_native)\r\n intervals = []\r\n shift_amount = 0\r\n if time_end < time_start:\r\n intervals = [(time_start, 24), (0, time_end)]\r\n else:\r\n intervals = [(time_start, time_end)]\r\n for interval in intervals:\r\n for line in self.shift_allowance_line_ids:\r\n if max(interval[0], line.time_from) < min(\r\n interval[1], line.time_to):\r\n time = min(\r\n interval[1], line.time_to)-max(interval[0], line.time_from)\r\n shift_amount += time * line.amount\r\n return shift_amount\r\n\r\n\r\nclass HrLateRuleLine(models.Model):\r\n _inherit = 'hr.late.rule.line'\r\n\r\n first = fields.Float('First Time', default=1)\r\n second = fields.Float('Second Time', default=1)\r\n third = fields.Float('Third Time', default=1)\r\n fourth = fields.Float('Fourth Time', default=1)\r\n fifth = fields.Float('Fifth Time', default=1)\r\n\r\n\r\nclass HrDiffRuleLine(models.Model):\r\n _inherit = 'hr.diff.rule.line'\r\n\r\n first = fields.Float('First Time', default=1)\r\n second = fields.Float('Second Time', default=1)\r\n third = fields.Float('Third Time', default=1)\r\n fourth = fields.Float('Fourth Time', default=1)\r\n fifth = fields.Float('Fifth Time', default=1)\r\n\r\n\r\nclass hr_miss_rule(models.Model):\r\n _name = 'hr.miss.rule'\r\n\r\n name = fields.Char(string='name', required=True, translate=True)\r\n line_ids = fields.One2many(comodel_name='hr.miss.rule.line',\r\n inverse_name='miss_id',\r\n string='Missed punchis rules')\r\n\r\n\r\nclass hr_miss_rule_line(models.Model):\r\n _name = 'hr.miss.rule.line'\r\n\r\n times = [\r\n ('1', 'First Time'),\r\n ('2', 'Second Time'),\r\n ('3', 'Third Time'),\r\n ('4', 'Fourth Time'),\r\n ('5', 'Fifth Time'),\r\n\r\n ]\r\n\r\n miss_id = fields.Many2one(comodel_name='hr.miss.rule', string='name')\r\n amount = fields.Float(string='amount', required=True)\r\n counter = fields.Selection(string=\"Times\", selection=times, required=True, )\r\n\r\n _sql_constraints = [\r\n ('miss_rule_cons', 'unique(miss_id,counter)',\r\n 'The counter Must Be unique Per Rule'),\r\n ]\r\n\r\n\r\nclass AttendanceShiftAllowance(models.Model):\r\n _name = 'attendance.shift.allowance'\r\n policy_id = fields.Many2one('hr.attendance.policy', 'Attendance Policy',\r\n ondelete='cascade')\r\n time_from = fields.Float('Time From', required=True)\r\n time_to= fields.Float('Time To', required=True)\r\n amount = fields.Float('Amount')\r\n\r\n @api.constrains('time_from', 'time_to', 'policy_id')\r\n def _check_time(self):\r\n for line in self:\r\n pass\r\n","sub_path":"surgi_attendance_sheet/models/hr_attendance_policy.py","file_name":"hr_attendance_policy.py","file_ext":"py","file_size_in_byte":8337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524063638","text":"\"models.py \"\n\nfrom sklearn.gaussian_process.kernels import ConstantKernel, RBF, RationalQuadratic, ExpSineSquared\nfrom sklearn.metrics import make_scorer,f1_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import VotingClassifier\nimport numpy as np\n\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\nfrom sklearn.gaussian_process.kernels import RBF,WhiteKernel, ExpSineSquared\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom scipy.stats import expon, reciprocal\nimport util as ut\n\n# this gives all search params amd respective losses\n#cvres = grid_search.cv_results_\n#for mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n# print(np.sqrt(-mean_score), params)\n\nker_rbf = ConstantKernel(1.0, constant_value_bounds=\"fixed\") * RBF(0.8, length_scale_bounds=\"fixed\")\n\nker_rq = ConstantKernel(0.9, constant_value_bounds=\"fixed\") * RationalQuadratic(alpha=0.2, length_scale=1)\n\nkernel_mixed = 1.0 * RBF(length_scale=100.0, length_scale_bounds=(1e-2, 1e3))+ WhiteKernel(noise_level=1, noise_level_bounds=(1e-10, 1e+1)) \n\nkernel_mix = ConstantKernel(constant_value=1.0, constant_value_bounds=\"fixed\") * RBF(length_scale=0.5, length_scale_bounds=\"fixed\") + RBF(length_scale=2.0, length_scale_bounds=\"fixed\")\n\nkernel_list = [ker_rbf, ker_rq]\n\n\ndef GP(X_train, X_test, y_train, y_test):\n \n parameters = {\"kernel\": kernel_list,\n \"n_restarts_optimizer\": [1,2,3,5],\n \"warm_start\":[True,False],\n \"copy_X_train\":[True,False]\n }\n \n ftwo_scorer = make_scorer(f1_score)\n clf = RandomizedSearchCV(GaussianProcessClassifier(max_iter_predict=300,n_jobs=-1,random_state=1),parameters,cv=5,scoring=ftwo_scorer,n_jobs=-1,random_state=1)\n\n clf.fit(X_train, y_train)\n model = clf.best_estimator_\n ut.report(model,X_train,y_train,'Training')\n ut.report(model,X_test,y_test,'Test')\n \n print(\"Log Marginal Likelihood (initial): %.3f\" % model.log_marginal_likelihood(model.kernel_.theta))\n return model\n\n\ndef voter(X_train, X_test, y_train, y_test):\n clf1 = LogisticRegression(solver='lbfgs',random_state=1)\n clf2 = RandomForestClassifier(oob_score=True,bootstrap=True,random_state=1)\n clf3 = GaussianNB()\n clf4=SVC(probability=True)\n\n\n eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3),('svm',clf4)], voting='soft',n_jobs=-1)\n\n params = {\n 'lr__C': [50,100,150,200,300,500], \n 'rf__n_estimators': [5,10,20,50,100,200],\n 'rf__min_samples_split':[2,5,20,50,100],\n 'rf__max_leaf_nodes':[None,2,5],\n 'rf__max_depth':[None,2,5,10,20,50,100],\n 'rf__criterion':['gini','entropy'],\n 'svm__kernel':['linear','rbf'],\n 'svm__shrinking':(True,False),\n 'svm__C':reciprocal(50, 200),\n 'svm__gamma': expon(scale=1.0),\n\n }\n\n ftwo_scorer = make_scorer(f1_score)\n grid = RandomizedSearchCV(estimator=eclf, param_distributions=params, cv=5,scoring=ftwo_scorer,n_jobs=-1)\n grid = grid.fit(X_train, y_train)\n\n voter = grid.best_estimator_\n ut.report(voter,X_train,y_train,'Training')\n \n ut.report(voter,X_test,y_test,'Test')\n\n return voter\n\n\ndef search_rf(X_t, X_te, y_t, y_te):\n \n parameters = {\"n_estimators\": [100,150,300,500],\n \"min_samples_split\": [2,5,10,15,50],\n 'max_leaf_nodes':[None,2,5,10,15,20],\n 'max_depth':[None,2,5,10],\n 'criterion':['gini','entropy']\n\n }\n \n ftwo_scorer = make_scorer(f1_score)\n clf = RandomizedSearchCV(RandomForestClassifier(oob_score=True,bootstrap=True,random_state=1,warm_start=True), \n parameters,cv=5,scoring=ftwo_scorer,n_jobs=-1,random_state=1)\n\n clf.fit(X_t, y_t)\n rf = clf.best_estimator_\n \n \n ut.report(rf,X_t,y_t,'Training')\n ut.report(rf,X_te,y_te,'Test')\n \n return rf\n\n\ndef search_svm(X_train, X_test, y_train, y_test):\n #svm with grid search\n \n parameters = {'kernel':['linear', 'rbf'], \n 'C':reciprocal(20, 30),\n 'gamma': expon(scale=1.0),\n 'shrinking':(True,False)}\n \n clf = RandomizedSearchCV(SVC(probability=True), parameters,n_iter=50,random_state=1,cv=5)\n clf.fit(X_train,y_train)\n sv = clf.best_estimator_\n ut.report(sv,X_train,y_train,'Training')\n ut.report(sv,X_test,y_test,'Test')\n \n return sv\n\n\n\ndef search_lr(X_train, X_test, y_train, y_test):\n \t \n\n parameters={\n \n 'C':[10,50,100,200,300],\n 'fit_intercept':[False,True],\n 'max_iter':[100,200,300,500],\n 'warm_start':[True,False]\n }\n \n #ftwo_scorer = make_scorer(f1_score)\n clf = RandomizedSearchCV(LogisticRegression(random_state=1,solver='lbfgs'),parameters,cv=3,random_state=1)\n clf.fit(X_train,y_train)\n\n lr = clf.best_estimator_\n ut.report(lr,X_train,y_train,'Training')\n ut.report(lr,X_test,y_test,'Test')\n \n return lr\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"252988850","text":"from enum import Enum\nimport random\n\n\nclass Turn(Enum):\n '''\n 转向\n '''\n Forward = 0\n Left = 1\n Right = 2\n Backward = 3\n\n # 实现静态方法 外部调用\n @staticmethod\n def RandTurn():\n '''\n 随机转向\n 例: RandTurn \n Forward 向前 概率 75%\n Left 向左 概率 10%\n Right 向右 概率 10%\n Backward 向后 概率 5%\n '''\n\n rand = random.randint(0, 100)\n if (rand < 85):\n return Turn.Forward # 向前 概率 75%\n elif (rand >= 85 and rand < 91):\n return Turn.Left # 向左 概率 10%\n elif (rand >= 91 and rand < 97):\n return Turn.Right # 向右 概率 10%\n elif (rand >= 97):\n return Turn.Backward # 向后 概率 5%\n\n '''\n if (rand < 75):\n return Turn.Forward # 向前 概率 75%\n elif (rand >= 75 and rand < 85):\n return Turn.Left # 向左 概率 10%\n elif (rand >= 85 and rand < 95):\n return Turn.Right # 向右 概率 10%\n elif (rand >= 95):\n return Turn.Backward # 向后 概率 5%\n '''\nclass Direct(Enum):\n '''\n 方向类\n 重写了 __str__ 和 __add__\n 通过 + 重载, 实现方向加法\n 例: Up + Down = Down, Up+Up = Up 等等\n '''\n '''\n 00 -1 00\n -1 me 1\n 00 1 00\n '''\n\n Up = (0, -1)\n Right = (1, 0)\n Down = (0, 1)\n Left = (-1, 0)\n\n # 实现静态方法 外部调用\n\n @staticmethod\n def RandDirect():\n '''\n 个性化初始化方法 随机获取一个方向\n '''\n\n d = random.randint(0, 100)\n lst = [x for x in Direct]\n #print (lst[d%4])\n return lst[d % 4]\n\n # value 可能的数据类型为 Direction、字符串、整形\n def __add__(self, value):\n #print (type(self),type(value))\n if (type(self) == type(value)):\n return value\n\n if (type(value) == Turn):\n # 向前\n if (value == Turn.Forward):\n return self\n # 左转\n elif (value == Turn.Left):\n if (self == Direct.Up):\n return Direct.Left\n elif (self == Direct.Right):\n return Direct.Up\n elif (self == Direct.Down):\n return Direct.Right\n elif (self == Direct.Left):\n return Direct.Down\n # 右转\n elif (value == Turn.Right):\n if (self == Direct.Up):\n return Direct.Right\n elif (self == Direct.Right):\n return Direct.Down\n elif (self == Direct.Down):\n return Direct.Left\n elif (self == Direct.Left):\n return Direct.Up\n # 后转\n elif (value == Turn.Backward):\n if (self == Direct.Up):\n return Direct.Down\n elif (self == Direct.Right):\n return Direct.Left\n elif (self == Direct.Down):\n return Direct.Up\n elif (self == Direct.Left):\n return Direct.Right\n\n\n# 转向测试代码\nif __name__ == '__main__':\n '''\n dir = Direct.RandDirect()\n index =0\n for turn in Turn:\n for dir in Direct:\n #turn = Turn.RandTurn()\n print('%2d %s + %s = %s '%(index,turn,dir, (turn +dir).name)\n index +=1\n '''\n\n \n #随机转向测试\n dir = Direct.RandDirect()\n for i in range( 0,100): # Turn:\n turn = Turn.RandTurn()\n print('%2d %s + %s = %s '%(i,dir, turn,dir+turn))\n \n\n print ('*'*50)\n for dir in Direct:\n # print (dir.name)\n i = 1\n for turn in Turn:\n print('%d %s + %s = %s '%(i,dir.name, turn.name,(dir+turn).name))\n dir_new = dir+turn\n print (dir_new)\n i +=1\n","sub_path":"MyTkinter程序/tank/Direct.py","file_name":"Direct.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"280649142","text":"import numpy as np\r\nfrom numpy import linalg as LA\r\nimport sys\r\n\r\n\r\ndef smallest_real_eigen(mat):\r\n eigen_values = LA.eigvals(mat)\r\n min_val = sys.maxsize\r\n for value in eigen_values:\r\n if value.imag == 0:\r\n if min_val > value.real:\r\n min_val = value.real\r\n \r\n assert min_val != sys.maxsize, \"No real eigen value\"\r\n return min_val\r\n\r\n\r\ndef diff_2(X,i,j):\r\n #returns ||x_{i}-x_{j}||^2\r\n delta = X[i]-X[j]\r\n return np.dot(delta,delta)\r\n\r\n\r\ndef variance_2(X):\r\n #Finds variance across X treating each row x_{i} as data point\r\n sum = 0\r\n n = X.shape[0]\r\n for i in range(0,n):\r\n for j in range(i,n):\r\n sum += diff_2(X,i,j)\r\n \r\n return float(2*n*sum)/n\r\n \r\n\r\ndef create_outlier_file(out_measure_file, outlier_info_file, threshold):\r\n # Outlier - 1 and Normal = 0\r\n\r\n with open(out_measure_file,'r') as out_meas:\r\n with open(outlier_info_file, 'w') as out_info:\r\n for row in out_meas:\r\n if float(row) > threshold:\r\n out_info.write(str(1)+\"\\n\")\r\n else:\r\n out_info.write(str(0)+\"\\n\")\r\n out_info.close()\r\n out_meas.close()\r\n\r\n\r\ndef calculate_accuracy(actual_output_file , predicted_output_file, accuracy_file, threshold, other_param):\r\n # TASK for PREDICTING OUTLIERS Correctly\r\n # Outlier - 1 and Normal = 0\r\n\r\n with open(actual_output_file,'r') as actual, open(predicted_output_file,'r') as predicted:\r\n fp=0;tp=0;tn=0;fn=0;none=0;num_anomaly_act=0;\r\n for act,pred in zip(actual,predicted):\r\n act = act[0]\r\n pred = pred[0]\r\n if act=='0' and pred=='1':\r\n fp+=1\r\n elif act=='0' and pred=='0':\r\n tn+=1\r\n elif act=='1' and pred=='0':\r\n fn+=1\r\n num_anomaly_act+=1\r\n elif act=='1' and pred=='1':\r\n tp+=1\r\n num_anomaly_act+=1\r\n else :\r\n print(\"Pred = \", pred, \" Actual = \", act)\r\n none+=1\r\n #print(act,pred)\r\n # if act=='0\\n' and pred=='1\\n':\r\n # fp+=1\r\n # elif act=='0\\n' and pred=='0\\n':\r\n # tn+=1\r\n # elif act=='1\\n' and pred=='0\\n':\r\n # fn+=1\r\n # num_anomaly_act+=1\r\n # elif act=='1\\n' and pred=='1\\n':\r\n # tp+=1\r\n # num_anomaly_act+=1\r\n # else :\r\n # print(\"Pred = \", pred, \" Actual = \", act)\r\n # none+=1\r\n # #print(act,pred)\r\n \r\n print(\"tp, fn, fp, tn, none\")\r\n print(tp, fn, fp, tn, none)\r\n accuracy =0; precision = 0; recall =0; F_measure = 0\r\n if tp+tn+fp+fn > 0:\r\n accuracy = (tp+tn)/(tp+tn+fp+fn)\r\n if tp+fp > 0:\r\n precision = (tp)/(tp+fp)\r\n if tp+fn > 0:\r\n recall = (tp)/(tp+fn)\r\n if (precision+recall) >0:\r\n F_measure = (2.0*precision*recall)/(precision+recall)\r\n \r\n #print(\"accuracy, precision, recall, F_measure\")\r\n #print(accuracy, precision, recall, F_measure)\r\n print(\"Number of Anomaly actual \" , num_anomaly_act)\r\n with open(accuracy_file,\"a\") as results:\r\n #results = csv.writer(results)\r\n s = \"Threshold,\"+str(threshold)+\",tp,\"+str(tp)+\",Inliers_p,\"+str(fn+tn)+\",\"+\"outliers_p\"+\",\"+str(tp+fp)+\",\"+\"accuracy\"+\",\"+str(accuracy)+\",\"+ \\\r\n \"precision\"+\",\"+str(precision)+\",\"+\"recall\"+\",\"+str(recall)+\",\"+\"F_measure\"+\",\"+str(F_measure)+\\\r\n \",\"+\"Other_param\"+\",\"+str(other_param)+\"\\n\"\r\n results.write(s)\r\n results.close()","sub_path":"anomaly/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"65429177","text":"# Import all the libraries required\nimport os\nimport json\nimport random\nimport time\nimport matplotlib\nimport numpy as np\nimport pandas as pd\n#import geopandas as gpd\n\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('ggplot')\nimport pprint as pp\nimport matplotlib.cm as cm\nimport numpy.random as nprnd\nfrom scipy.interpolate import spline\nfrom scipy.stats import gaussian_kde\nfrom matplotlib.colors import rgb2hex\nfrom descartes import PolygonPatch\nfrom shapely.geometry import Polygon, MultiPolygon\nfrom shapely.geometry import Point\n\nimport scipy.stats\n# In[0]:\ndef load_pandas(filepath):\n \"\"\"\n Specify the path, this function returns the pandas dataframe.\n \"\"\"\n return pd.read_pickle(filepath)\n \ndef data_select(df_tweetjes, df_trump, topic):\n \n trump_tweets = df_trump.loc[df_trump.topic == topic]\n tweetjes = df_tweetjes.loc[df_tweetjes.topic == topic]\n \n tweetjes_time = tweetjes.sort_values('datetime')\n trump_time = trump_tweets.sort_values('datetime')\n \n \n tweetjes_time = tweetjes.reset_index()\n trump_time = trump_time.reset_index()\n \n \n return tweetjes_time, trump_time\n\n\ndef create_count_interval(tweetjes_time, trump_time, plot_hour):\n \n \n input_time = tweetjes_time.datetime.min() # Starting time\n einde_der_tijden = tweetjes_time.datetime.max() # End time\n first_tweet = tweetjes_time.datetime.loc[tweetjes_time.datetime == input_time]\n last_tweet = first_tweet + pd.DateOffset(hours = plot_hour)\n \n interval_counts = []\n interval_datetime = []\n interval_sentiment = []\n interval = pd.DataFrame()\n # Create time intervals and calculate amount of tweets per interval \n while (last_tweet.iloc[0] < einde_der_tijden):\n last_tweet = first_tweet + pd.DateOffset(hours = plot_hour)\n \n mask = (tweetjes_time.datetime >= first_tweet.squeeze()) & (tweetjes_time.datetime < last_tweet.squeeze())\n interval_tweets = tweetjes_time.loc[mask]\n if len(interval_tweets)>0 : \n #assign info\n interval_counts.append(len(interval_tweets))\n interval_sentiment.append(interval_tweets.sentiment.mean())\n time_df = first_tweet + pd.DateOffset(hours = (plot_hour/2))\n interval_datetime.append(time_df.iloc[0])\n \n else:\n interval_counts.append(0)\n interval_sentiment.append(0.5)\n time_df = first_tweet + pd.DateOffset(hours = (plot_hour/2))\n interval_datetime.append(time_df.iloc[0])\n first_tweet = last_tweet\n \n interval = pd.DataFrame({'counts' : interval_counts, 'sentiment' : interval_sentiment, 'datetime' : interval_datetime})\n# interval = pd.DataFrame({'counts' : interval_counts, 'datetime' : interval_datetime})\n \n return interval\n\n# In[]\n \ndef plot_twifluence(df_tweetjes, df_trump, topic, plot_hour, plot_senti):\n # Retrieve tweets concerning topic & count amount of tweets/ average sentiment \n # for pre-determined intervals between input/output time\n tweetjes_time, trump_time = data_select(df_tweetjes, df_trump, topic)\n \n input_time1 = tweetjes_time.datetime.min() # Starting time\n end_time1 = tweetjes_time.datetime.max() # End time\n \n # tump tweets zit ertussen\n mask1 = (trump_time.datetime >= input_time1) & (trump_time.datetime <= end_time1 )\n trump_time = trump_time.loc[mask1]\n \n input_time2 = trump_time.datetime.min() \n index_begin2 = tweetjes_time.index[tweetjes_time['datetime'] < input_time2].tolist()\n index_begin1 = index_begin2[::-1]\n index_begin = index_begin1[650]\n \n end_time2 = trump_time.datetime.max() \n index_end2 = tweetjes_time.index[tweetjes_time['datetime'] > input_time2].tolist()\n index_end = index_end2[3800]\n \n tweetjes_time = tweetjes_time.iloc[index_begin: index_end]\n pp.pprint(len(tweetjes_time))\n \n interval = create_count_interval(tweetjes_time, trump_time, plot_hour)\n \n \n # Interpolate count or sentiment data\n xnum = np.linspace(0, 10, num= len(interval.counts), endpoint = True)\n xnew = np.linspace(0, 10, num= (len(interval.counts)*10), endpoint=True)\n \n if plot_senti == 1:\n power_smooth = spline(xnum, interval.sentiment, xnew)\n else:\n power_smooth = spline(xnum, interval.counts, xnew)\n \n # Create new timeline to plot against (because of interpolation)\n \n begintime = matplotlib.dates.date2num(interval.datetime.iloc[0])\n endtime = matplotlib.dates.date2num(interval.datetime.iloc[-1])\n numdates = np.linspace(begintime, endtime, num = (len(interval.counts)*10), endpoint = True)\n \n interp_dates = matplotlib.dates.num2date(numdates)\n \n # Plot figure\n plt.plot(interp_dates,power_smooth, 'r-')\n # plt.xticks(interp_dates)\n for k in trump_time .datetime.index:\n trump_date_number = matplotlib.dates.date2num(trump_time .datetime[k])\n min_diff = min(abs(i - trump_date_number) for i in numdates)\n toegevoegd = trump_date_number + min_diff\n afgenomen = trump_date_number - min_diff\n plus = [i for i,x in enumerate(numdates) if x == toegevoegd]\n minus = [i for i,x in enumerate(numdates) if x == afgenomen]\n if plus:\n hoogte = power_smooth[plus[0]]\n else:\n hoogte = power_smooth[minus[0]]\n \n plt.plot([trump_time .datetime[k],trump_time .datetime[k]],[0, hoogte], 'k-')\n \n \n if plot_senti == 1:\n plt.axis((begintime,endtime,0.4,1))\n plt.xlabel('Date: 08/31/2016 - 01/09/2016')\n plt.ylabel(\"Average sentiment on twitter (1 positive, 0 negative)\")\n plt.title(\"Sentiment on Twitter over time about the topic: 'Wall Mexico'\")\n else:\n plt.xlabel('Date')\n plt.ylabel('Amount of tweets')\n plt.title(\"Amount of tweets over time about the topic: 'Wall Mexico'\")\n plt.show()\n \n return interval\n\ndef plot_results(topic, interval_length, sentiment_bool ):\n # Load all tweet data\n # filepath = r'C:\\Users\\daniel\\Downloads\\true_tweets.pkl'\n # df_tweetjes = load_pandas(filepath)\n \n # load trump tweet data\n filepath = r'final_dataset.pkl'\n filepath_trump = r'trump_df_final.pkl'\n df_tweetjes = load_pandas(filepath)\n df_trump = load_pandas(filepath_trump)\n \n \n # adjust trumps timeframe to original timeframe\n \n plot_twifluence(df_tweetjes, df_trump, topic, interval_length, sentiment_bool)\n \n\nif __name__ == \"__main__\":\n \n # select data of interest and determine bin length (in hour)\n topic = 'Wall Mexico' # topic\n interval_length = 8 # Interval length (sentiment 4, count)\n sentiment_bool = 0 # Plot sentiment(1) or count(0)\n \n plot_results(topic, interval_length, sentiment_bool)\n","sub_path":"Week2-3/visualisation_amor.py","file_name":"visualisation_amor.py","file_ext":"py","file_size_in_byte":6881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105647188","text":"from Acquisition import aq_inner\nfrom Acquisition import aq_parent\nfrom collective import dexteritytextindexer\nfrom datetime import date\nfrom DateTime import DateTime\nfrom opengever.activity import notification_center\nfrom opengever.activity.roles import DISPOSITION_ARCHIVIST_ROLE\nfrom opengever.activity.roles import DISPOSITION_RECORDS_MANAGER_ROLE\nfrom opengever.base.behaviors.classification import IClassification\nfrom opengever.base.behaviors.lifecycle import ILifeCycle\nfrom opengever.base.response import IResponseContainer\nfrom opengever.base.response import IResponseSupported\nfrom opengever.base.security import elevated_privileges\nfrom opengever.base.source import SolrObjPathSourceBinder\nfrom opengever.disposition import _\nfrom opengever.disposition.appraisal import IAppraisal\nfrom opengever.disposition.delivery import DELIVERY_STATUS_LABELS\nfrom opengever.disposition.delivery import DeliveryScheduler\nfrom opengever.disposition.ech0160.sippackage import SIPPackage\nfrom opengever.disposition.history import DispositionHistory\nfrom opengever.disposition.interfaces import IDisposition\nfrom opengever.disposition.interfaces import IDuringDossierDestruction\nfrom opengever.dossier.base import DOSSIER_STATES_OFFERABLE\nfrom opengever.dossier.behaviors.dossier import IDossier\nfrom opengever.ogds.base.utils import get_current_admin_unit\nfrom opengever.ogds.models.service import ogds_service\nfrom persistent.dict import PersistentDict\nfrom persistent.list import PersistentList\nfrom plone import api\nfrom plone.autoform.directives import write_permission\nfrom plone.dexterity.content import Container\nfrom plone.namedfile.file import NamedBlobFile\nfrom plone.restapi.interfaces import IFieldSerializer\nfrom plone.restapi.serializer.converters import json_compatible\nfrom plone.supermodel import model\nfrom Products.CMFPlone.CatalogTool import num_sort_regex\nfrom Products.CMFPlone.CatalogTool import zero_fill\nfrom pyxb.utils.domutils import BindingDOMSupport\nfrom tempfile import TemporaryFile\nfrom z3c.relationfield.schema import RelationChoice\nfrom z3c.relationfield.schema import RelationList\nfrom zExceptions import Unauthorized\nfrom zipfile import ZIP_DEFLATED\nfrom zipfile import ZipFile\nfrom zope import schema\nfrom zope.annotation import IAnnotations\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.globalrequest import getRequest\nfrom zope.i18n import translate\nfrom zope.interface import alsoProvides\nfrom zope.interface import implements\nfrom zope.intid.interfaces import IIntIds\n\n\nDESTROY_PERMISSION = 'opengever.dossier: Destroy dossier'\n\n\ndef sort_on_sortable_title(item):\n if isinstance(item[0], unicode):\n return num_sort_regex.sub(zero_fill, item[0])\n return num_sort_regex.sub(zero_fill, item[0].Title())\n\n\nclass DossierDispositionInformation(object):\n \"\"\"A wrapper object for dossiers.\n\n To provide easy access for the dossier's data, via the disposition\n relations list. See Disposition.get_dossier_representations.\n \"\"\"\n\n def __init__(self, dossier, disposition):\n self.dossier = dossier\n self.title = dossier.title\n self.intid = getUtility(IIntIds).getId(dossier)\n self.url = dossier.absolute_url()\n self.uid = dossier.UID()\n self.reference_number = dossier.get_reference_number()\n self.parent = aq_parent(aq_inner(dossier))\n self.start = IDossier(dossier).start\n self.end = IDossier(dossier).end\n self.public_trial = IClassification(dossier).public_trial\n self.archival_value = ILifeCycle(dossier).archival_value\n self.archival_value_annotation = ILifeCycle(dossier).archival_value_annotation\n self.appraisal = IAppraisal(disposition).get(dossier)\n self.former_state = dossier.get_former_state()\n\n @property\n def additional_metadata_available(self):\n return True\n\n def get_grouping_key(self):\n return self.parent\n\n def was_inactive(self):\n return self.former_state == 'dossier-state-inactive'\n\n def get_repository_title(self):\n return self.parent.Title().decode('utf-8')\n\n def get_storage_representation(self):\n \"\"\"Returns a PersistentDict with the most important values.\n \"\"\"\n return PersistentDict({\n 'title': self.title,\n 'intid': self.intid,\n 'reference_number': self.reference_number,\n 'repository_title': self.get_repository_title(),\n 'appraisal': self.appraisal,\n 'former_state': self.former_state})\n\n def jsonify(self):\n return json_compatible({\n 'title': self.title,\n 'intid': self.intid,\n 'appraisal': self.appraisal,\n 'reference_number': self.reference_number,\n 'url': self.url,\n 'uid': self.uid,\n 'start': self.start,\n 'end': self.end,\n 'public_trial': self.serialize_public_trial(),\n 'archival_value': self.serialize_archival_value(),\n 'archival_value_annotation': self.archival_value_annotation,\n 'former_state': self.former_state})\n\n def serialize_public_trial(self):\n if not self.public_trial:\n return\n\n serializer = getMultiAdapter(\n (IClassification['public_trial'], self.dossier, getRequest()),\n IFieldSerializer)\n return serializer()\n\n def serialize_archival_value(self):\n if not self.archival_value:\n return\n\n serializer = getMultiAdapter(\n (ILifeCycle['archival_value'], self.dossier, getRequest()),\n IFieldSerializer)\n return serializer()\n\n\nclass RemovedDossierDispositionInformation(DossierDispositionInformation):\n\n def __init__(self, dossier_mapping, disposition):\n self.title = dossier_mapping.get('title')\n self.intid = dossier_mapping.get('intid')\n self.appraisal = dossier_mapping.get('appraisal')\n self.reference_number = dossier_mapping.get('reference_number')\n self.repository_title = dossier_mapping.get('repository_title')\n self.url = None\n self.uid = None\n self.start = None\n self.end = None\n self.public_trial = None\n self.archival_value = None\n self.archival_value_annotation = None\n self.former_state = dossier_mapping.get('former_state')\n\n @property\n def additional_metadata_available(self):\n return False\n\n def get_grouping_key(self):\n return self.repository_title\n\n def get_repository_title(self):\n return self.repository_title\n\n\ndef title_default():\n \"\"\"Returns title suggestion in the following format:\n\n `Disposition {admin unit abbreviation} {localized today's date}`\n \"\"\"\n return u'{} {} {}'.format(\n translate(_('label_disposition', default=u'Disposition'),\n context=getRequest()),\n get_current_admin_unit().abbreviation,\n api.portal.get_localized_time(date.today(), long_format=False))\n\n\nclass IDispositionSchema(model.Schema):\n\n model.fieldset(\n u'common',\n label=_(u'fieldset_common', default=u'Common'),\n fields=[u'title', u'dossiers', u'transfer_number'],\n )\n\n dexteritytextindexer.searchable('title')\n title = schema.TextLine(\n title=_(u\"label_title\", default=u\"Title\"),\n required=True,\n max_length=256,\n defaultFactory=title_default,\n )\n\n dossiers = RelationList(\n title=_(u'label_dossiers', default=u'Dossiers'),\n default=[],\n missing_value=[],\n value_type=RelationChoice(\n title=u\"Dossier\",\n source=SolrObjPathSourceBinder(\n object_provides=('opengever.dossier.behaviors.dossier.IDossierMarker'),\n review_state=DOSSIER_STATES_OFFERABLE,\n navigation_tree_query={\n 'object_provides':\n ['opengever.repository.repositoryroot.IRepositoryRoot',\n 'opengever.repository.interfaces.IRepositoryFolder',\n 'opengever.dossier.behaviors.dossier.IDossierMarker'],\n }),\n ),\n required=True,\n )\n\n write_permission(transfer_number='opengever.disposition.EditTransferNumber')\n dexteritytextindexer.searchable('transfer_number')\n transfer_number = schema.TextLine(\n title=_(u\"label_transfer_number\", default=u\"Transfer number\"),\n required=False,\n )\n\n\nclass Disposition(Container):\n implements(IDisposition, IResponseSupported)\n\n destroyed_key = 'destroyed_dossiers'\n\n def __init__(self, *args, **kwargs):\n super(Disposition, self).__init__(*args, **kwargs)\n self.appraisal = {}\n self._dossiers = PersistentList()\n\n @property\n def dossiers(self):\n return self._dossiers\n\n @dossiers.setter\n def dossiers(self, value):\n old = set([rel.to_object for rel in self._dossiers])\n new = set([rel.to_object for rel in value])\n\n self._dossiers = value\n\n self.update_added_dossiers(new - old)\n self.update_dropped_dossiers(old - new)\n\n def get_dossiers(self):\n return [relation.to_object for relation in self.dossiers]\n\n def get_history(self):\n history = [DispositionHistory.get(response)\n for response in IResponseContainer(self)]\n history.reverse()\n return history\n\n def get_destroyed_dossiers(self):\n annotations = IAnnotations(self)\n if not annotations.get(self.destroyed_key):\n return []\n return annotations.get(self.destroyed_key)\n\n def set_destroyed_dossiers(self, dossiers):\n value = PersistentList([\n DossierDispositionInformation(dossier, self).get_storage_representation()\n for dossier in dossiers])\n\n IAnnotations(self)[self.destroyed_key] = value\n\n @property\n def is_closed(self):\n return api.content.get_state(self) == 'disposition-state-closed'\n\n def has_dossiers_to_archive(self):\n return any(IAppraisal(self).storage.values())\n\n def get_dossier_representations(self):\n if self.is_closed:\n return [RemovedDossierDispositionInformation(data, self)\n for data in self.get_destroyed_dossiers()]\n\n return [DossierDispositionInformation(rel.to_object, self)\n for rel in self.dossiers]\n\n def get_grouped_dossier_representations(self):\n dossiers = self.get_dossier_representations()\n inactive_dossiers = {}\n active_dossiers = {}\n\n for dossier in dossiers:\n if dossier.was_inactive():\n self._add_to(inactive_dossiers, dossier)\n else:\n self._add_to(active_dossiers, dossier)\n\n return (\n sorted(active_dossiers.items(), key=sort_on_sortable_title),\n sorted(inactive_dossiers.items(), key=sort_on_sortable_title))\n\n def _add_to(self, mapping, dossier):\n key = dossier.get_grouping_key()\n mapping.setdefault(key, []).append(dossier)\n\n def update_added_dossiers(self, dossiers):\n for dossier in dossiers:\n dossier.offer()\n IAppraisal(self).initialize(dossier)\n\n def update_dropped_dossiers(self, dossiers):\n for dossier in dossiers:\n dossier.retract()\n IAppraisal(self).drop(dossier)\n\n def finalize_appraisal(self):\n \"\"\"Write back the appraisal value to the dossiers.\n \"\"\"\n appraisal = IAppraisal(self)\n for relation in self.dossiers:\n appraisal.write_to_dossier(relation.to_object)\n\n def mark_dossiers_as_archived(self):\n for relation in self.dossiers:\n api.content.transition(\n obj=relation.to_object, transition='dossier-transition-archive')\n\n def destroy_dossiers(self):\n if not self.dossiers:\n return\n\n alsoProvides(getRequest(), IDuringDossierDestruction)\n\n dossiers = [relation.to_object for relation in self.dossiers]\n self.set_destroyed_dossiers(dossiers)\n self.check_destroy_permission(dossiers)\n with elevated_privileges():\n api.content.delete(objects=dossiers)\n\n def check_destroy_permission(self, dossiers):\n for dossier in dossiers:\n if not api.user.has_permission(DESTROY_PERMISSION, obj=dossier):\n raise Unauthorized()\n\n def register_watchers(self):\n center = notification_center()\n center.add_watcher_to_resource(\n self, self.Creator(), DISPOSITION_RECORDS_MANAGER_ROLE)\n\n for archivist in self.get_all_archivists():\n center.add_watcher_to_resource(\n self, archivist, DISPOSITION_ARCHIVIST_ROLE)\n\n def get_all_archivists(self):\n archivists = []\n acl_users = api.portal.get_tool('acl_users')\n role_manager = acl_users.get('portal_role_manager')\n for principal, title in role_manager.listAssignedPrincipals('Archivist'):\n\n info = role_manager.searchPrincipals(\n id=principal, exact_match=True)\n # skip not existing or duplicated groups or users\n if len(info) != 1:\n continue\n\n if info[0].get('principal_type') == 'group':\n archivists += [user.userid for user in\n ogds_service().fetch_group(principal).users]\n else:\n archivists.append(principal)\n\n return archivists\n\n def store_sip_package(self):\n self._sip_package = self.generate_sip_package()\n\n def remove_sip_package(self):\n self._sip_package = None\n\n def generate_sip_package(self):\n package = SIPPackage(self)\n zip_file = self.create_zipfile(package)\n zip_file.seek(0)\n return NamedBlobFile(zip_file.read(), contentType='application/zip')\n\n def schedule_sip_for_delivery(self):\n DeliveryScheduler(self).schedule_delivery()\n\n def is_scheduled_for_delivery(self):\n return DeliveryScheduler(self).is_scheduled_for_delivery()\n\n def create_zipfile(self, package):\n tmpfile = TemporaryFile()\n BindingDOMSupport.SetDefaultNamespace(u'http://bar.admin.ch/arelda/v4')\n with ZipFile(tmpfile, 'w', ZIP_DEFLATED, True) as zipfile:\n package.write_to_zipfile(zipfile)\n\n return tmpfile\n\n def has_sip_package(self):\n return bool(self.get_sip_package())\n\n def get_sip_package(self):\n return getattr(self, '_sip_package', None)\n\n def get_sip_name(self):\n name = u'SIP_{}_{}'.format(\n DateTime().strftime('%Y%m%d'),\n api.portal.get().getId().upper())\n if self.transfer_number:\n name = u'{}_{}'.format(name, self.transfer_number)\n\n return name\n\n def get_sip_filename(self):\n return u'{}.zip'.format(self.get_sip_name())\n\n def sip_download_available(self):\n if api.user.has_permission(\n 'opengever.disposition: Download SIP Package', obj=self):\n\n return self.has_sip_package()\n\n return None\n\n def removal_protocol_available(self):\n return api.content.get_state(self) == 'disposition-state-closed'\n\n def get_delivery_status_infos(self):\n \"\"\"Get translated delivery status infos in a template friendly format.\n \"\"\"\n statuses = DeliveryScheduler(self).get_statuses()\n status_infos = [\n {'name': n, 'status': translate(DELIVERY_STATUS_LABELS[s], context=getRequest())}\n for n, s in statuses.items()]\n return status_infos\n","sub_path":"opengever/disposition/disposition.py","file_name":"disposition.py","file_ext":"py","file_size_in_byte":15589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"495915600","text":"import boto3\nimport botocore\n\nbucketname = 'neural-network-data'\n\ns3 = boto3.resource('s3')\ns3client = boto3.client('s3')\nbucket = s3.Bucket(bucketname)\nexists = True\ntry:\n s3.meta.client.head_bucket(Bucket='mybucket')\nexcept botocore.exceptions.ClientError as e:\n # If a client error is thrown, then check that it was a 404 error.\n # If it was a 404 error, then the bucket does not exist.\n error_code = int(e.response['Error']['Code'])\n if error_code == 404:\n exists = False\n\ncount = 0\nfor key in bucket.objects.all():\n\tif count < 11:\n\t\ts3client.download_file(bucketname, key.key, \"image{}.jpg\".format(count))\n\t\tcount += 1","sub_path":"AWS_Scripts/fetch_data.py","file_name":"fetch_data.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"155699079","text":"import unittest\nfrom pyunitreport import HTMLTestRunner\nfrom selenium import webdriver\nfrom google_page import GooglePage\n\n\nclass GoogleTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome(executable_path='./chromedriver')\n cls.driver.maximize_window()\n cls.driver.get('http://google.com/')\n\n def test_search(self):\n google = GooglePage(self.driver)\n google.open()\n google.search('Platzi')\n\n self.assertEqual('Platzi', google.keyword)\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n\nif __name__ == '__main__':\n\tunittest.main(\n\t\tverbosity=2,\n\t\ttestRunner=HTMLTestRunner(\n\t\t\toutput='reportes',\n\t\t\treport_name='google-page-report'\n\t\t)\n\t)\n","sub_path":"pom/test_google.py","file_name":"test_google.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"360278735","text":"#\n# Резервоар за гориво - част 2\n# Напишете програма, която да изчислява, колко ще струва на един шофьор да напълни резервоара на автомобила си, като\n# знаете – какъв тип гориво зарежда, каква е цената за литър гориво и дали разполага с карта за отстъпки. Цените на\n# горивата са както следва:\n# Бензин – 2.22 лева за един литър,\n# Дизел – 2.33 лева за един литър\n# Газ – 0.93 лева за литър\n# Ако водача има карта за отстъпки, той се възползва от следните намаления за литър гориво: 18 ст. за литър бензин,\n# 12 ст. за литър дизел и 8 ст. за литър газ.\n# Ако шофьора е заредил между 20 и 25 литра включително, той полу��ава 8 процента отстъпка от крайната цена, при повече\n# от 25 литра гориво, той получава 10 процента отстъпка от крайната цена.\n# Вход\n# Входът се чете от конзолата и се състои от 3 реда:\n# Типа на горивото – текст с възможности: \"Gas\", \"Gasoline\" или \"Diesel\"\n# Количество гориво – реално число в интервала [1.00 … 50.00]\n# Притежание на клубна карта – текст с възможности: \"Yes\" или \"No\"\n# Изход\n# На конзолата трябва да се отпечата един ред.\n# \"{крайната цена на горивото} lv.\"\n# Цената на горивото да бъде форматираната до втората цифра след десетичния знак.\n\nfuel_type = input()\nfuel_amount = float(input())\ndiscount_card = input()\n\nprice = 0\n\nif fuel_type == \"Gasoline\":\n price = 2.22\n if discount_card == \"Yes\": price -= 0.18\nelif fuel_type == \"Diesel\":\n price = 2.33\n if discount_card == \"Yes\": price -= 0.12\nelse:\n price = 0.93\n if discount_card == \"Yes\": price -= 0.08\n\nsub_total = fuel_amount * price\nif fuel_amount >= 20 and fuel_amount <= 25:\n sub_total -= sub_total * 0.08\nelif fuel_amount > 25:\n sub_total -= sub_total * 0.1\n\nprint(f\"{sub_total:.2f} lv.\")\n","sub_path":"PB-MoreExercises/02 - Conditional Statements/08 - Fuel Tank Part2.py","file_name":"08 - Fuel Tank Part2.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"420084985","text":"from math import log\nimport operator\n\ndef calShannonEnt(dataSet):\n numEntries=len(dataSet)\n labelcCounts={}\n for featVec in dataSet:\n currentLabel=featVec[-1]\n if currentLabel not in labelcCounts.keys():\n labelcCounts[currentLabel]=0\n labelcCounts[currentLabel]+=1\n shannonEnt=0.0\n for key in labelcCounts:\n prob=float(labelcCounts[key])/numEntries\n shannonEnt-=prob*log(prob,2)\n return shannonEnt\n\ndef createDataSet():\n dataSet=[[1,1,'yes'],\n [1,1,'yes'],\n [1,0,'no'],\n [0,1,'no'],\n [0,1,'no']]\n labels=['no surfacing','flippers']\n return dataSet,labels\n\ndef splitDataSet(dataSet,axis,value):\n retDataSet=[]\n for featVec in dataSet:\n # 如果符合特征,将数据抽取出来,添加到新列表中(其中不包括 划分所根据的那列特征)\n if featVec[axis]==value:\n reducedFeatVec=featVec[:axis]\n reducedFeatVec.extend(featVec[axis+1:])\n retDataSet.append(reducedFeatVec)\n return retDataSet\n\ndef chooseBestFeatureToSplit(dataSet):\n numFeatures=len(dataSet[0])-1\n baseEntropy=calShannonEnt(dataSet)\n bestInfoGain=0.0;bestFeature=-1\n for i in range(numFeatures):\n featList=[example[i] for example in dataSet]\n uniqueVals=set(featList)\n newEntropy=0.0\n for value in uniqueVals:\n subDataSet=splitDataSet(dataSet,i,value)\n prob=len(subDataSet)/float(len(dataSet))\n newEntropy+=prob*calShannonEnt(subDataSet)\n infoGain=baseEntropy-newEntropy\n if(infoGain>bestInfoGain):\n bestInfoGain=infoGain\n bestFeature=i\n return bestFeature\n\ndef majorityCnt(classList):\n classCount={}\n for vote in classList:\n if vote not in classCount.keys():classCount[vote]=0\n classCount[vote]+=1\n sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n return sortedClassCount[0][0]\n\ndef createTree(dataSet,labels):\n classList=[example[-1] for example in dataSet]\n if classList.count(classList[0])==len(classList):#所有的类标签完全相同,直接返回该标签\n return classList[0]\n if len(dataSet[0])==1:#使用完了所有特征,还是不能把数据集划分为仅包含为一类别的分组,遍历所有特征后返回出现次数最多的类别\n return majorityCnt(classList)\n bestFeat=chooseBestFeatureToSplit(dataSet)\n bestFeatLabel=labels[bestFeat]\n myTree={bestFeatLabel:{}}\n del(labels[bestFeat])\n featValues=[example[bestFeat] for example in dataSet]\n uniqueVals=set(featValues)\n for value in uniqueVals:\n subLabels=labels[:]\n subDataSet=splitDataSet(dataSet, bestFeat, value)\n myTree[bestFeatLabel][value]=createTree(subDataSet,subLabels)\n return myTree\n\ndef classify(inputTree,featLabels,testVec):\n firstStr=list(inputTree.keys())[0]\n secondDict=inputTree[firstStr]\n featIndex=featLabels.index(firstStr)\n for key in secondDict.keys():\n if testVec[featIndex]==key:\n if type(secondDict[key]).__name__=='dict':\n classLabel=classify(secondDict[key],featLabels,testVec)\n else:\n classLabel=secondDict[key]\n return classLabel\n\ndef storeTree(inputTree,filename):\n import pickle\n fw=open(filename,'wb')\n pickle.dump(inputTree,fw)\n fw.close()\n\ndef grabTree(filename):\n import pickle\n fr=open(filename,'rb')\n return pickle.load(fr)\n\n\n","sub_path":"ch03/trees.py","file_name":"trees.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"188649771","text":"\n\nfrom xai.brain.wordbase.nouns._cad import _CAD\n\n#calss header\nclass _CADS(_CAD, ):\n\tdef __init__(self,): \n\t\t_CAD.__init__(self)\n\t\tself.name = \"CADS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cad\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cads.py","file_name":"_cads.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"297244805","text":"#!/usr/bin/env python3\nimport re\n\nUSERS = 'users.csv'\nNOTES = 'notes.txt'\nPROCESSED_NOTES = 'notes.md'\nUSER_TEMPLATE = '([@{0}])'\nINFO_TEMPLATE = '([@{0}] - [#{1}])'\nLINK_DEF_USER = '[@{0}]: https://github.com/{0}'\nLINK_DEF_PR = '[#{0}]: https://github.com/home-assistant/home-assistant/pull/{0}'\nPR_LINK_PATTERN = re.compile('\\(#(\\d+)\\)')\nusers = {}\n\n\ndef parse_pr_link(text):\n match = PR_LINK_PATTERN.match(text)\n if match:\n return match.groups(1)[0]\n else:\n return None\n\n\ndef main():\n with open(USERS) as inp:\n for lin in inp:\n email, github = [val.strip() for val in lin.split(',')]\n users[email] = github\n\n to_write = []\n to_write_footer = set()\n\n with open(NOTES) as inp:\n for lin in inp:\n parts = lin.split()\n\n # We assume it's a PR if second to last part of the commit\n # matches (#1234)\n pr = parse_pr_link(parts[-2])\n if pr:\n to_write_footer.add(LINK_DEF_PR.format(pr))\n del parts[-2]\n\n email = parts[-1][1:-1]\n\n if email not in users:\n print(\"Found unknown user {}, \"\n \"please run update-users.py\".format(email))\n return\n\n if email in users:\n to_write_footer.add(LINK_DEF_USER.format(users[email]))\n if pr:\n parts[-1] = INFO_TEMPLATE.format(users[email], pr)\n else:\n parts[-1] = USER_TEMPLATE.format(users[email])\n\n to_write.append(' '.join(parts))\n\n with open(PROCESSED_NOTES, 'wt') as outp:\n outp.write('\\n'.join(to_write))\n outp.write('\\n\\n')\n outp.write('\\n'.join(sorted(to_write_footer)))\n outp.write('\\n')\n\nif __name__ == '__main__':\n main()\n","sub_path":"hassrelease/process-notes.py","file_name":"process-notes.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"591776814","text":"import copy\n\n\ndef solve_puzzle(hints, board=[[]]):\n \"\"\" https://www.codewars.com/kata/4-by-4-skyscrapers \"\"\"\n\n if len(board) == 1:\n board = [[0 for j in range(0, 4)] for i in range(0, 4)]\n\n available_values_len_tab = get_avaialble_values(board)\n x, y = get_next_position_with_minimal_len(board, available_values_len_tab)\n\n # validate vs hints:\n for i, hint_value in enumerate(hints):\n if not validate_view_by_hint(view_for_hint(i, board), hint_value):\n return False\n\n # solution\n if x is None and y is None:\n return board\n\n next_board = copy.deepcopy(board)\n solution = False\n while not solution:\n if len(available_values_len_tab[x][y][0]) == 0:\n return False\n else:\n next_board[x][y] = available_values_len_tab[x][y][0].pop()\n solution = solve_puzzle(hints, next_board)\n return tuple([tuple(x) for x in solution])\n\n\ndef get_avaialble_values(board):\n available_values_len_tab = [[[available_values(i, j, board), len(available_values(i, j, board))]\n for j in range(0, 4)] for i in range(0, 4)]\n return available_values_len_tab\n\n\ndef get_next_position_with_minimal_len(board, available_values_len_tab):\n min_len = 5\n x, y = None, None\n for i in range(0, 4):\n for j in range(0, 4):\n if available_values_len_tab[i][j][1] > 0 and board[i][j] == 0:\n if min_len > available_values_len_tab[i][j][1]:\n min_len = available_values_len_tab[i][j][1]\n x, y = i, j\n return x, y\n\n\ndef visible_count(view):\n top = view[0]\n view_ct = 0\n for building in view:\n if building >= top:\n view_ct += 1\n top = building\n return view_ct\n\n\ndef get_horizontal_values(i, problem):\n return {x for x in problem[i] if x != 0}\n\n\ndef get_vertical_values(j, problem):\n return {problem[x][j] for x in range(0, 4) if problem[x][j] != 0}\n\n\ndef available_values(i, j, problem):\n return {j for j in range(1, 5)} - (\n get_horizontal_values(i, problem) | get_vertical_values(j, problem))\n\n\ndef view_for_hint(i, problem):\n if 0 <= i <= 3:\n return [problem[x][i] for x in range(0, 4)]\n if 4 <= i <= 7:\n return [x for x in problem[i % 4]][::-1]\n if 8 <= i <= 11:\n return [problem[x][3 - i % 8] for x in range(0, 4)][::-1]\n if 12 <= i <= 15:\n return [x for x in problem[3 - i % 12]]\n\n\ndef validate_view_by_hint(view, hint_value):\n if view.count(0) == 0 and hint_value != 0:\n if visible_count(view) == hint_value:\n return True\n else:\n return False\n #to adjust for more complicatred cases\n return True\n","sub_path":"20170305_skyscrapers/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"310648620","text":"import time\nimport socket\nimport threading\nimport _thread\n\nm = threading.Lock() #Mutex\nglobal uso \nuso=\"ninguem\" #Identificador de uso do controlador\n\ndef conectado(con, cliente):\n print ('Concetado por', cliente)\n msg=con.recv(1024) #Recebendo a mensagem\n smsg=msg.decode() #Decondificando a mensagem\n cmd,nome = smsg.split(\";\") #Dividindo a mensagem em comando e nome\n print(\"*** \"+cmd+\" \"+nome+\"\\n\")\n #-----------Verifica comando recebido - Inicio\n if (cmd==\"reserva\"):\n m.acquire() #Reserva da região crítica\n uso=nome #Definindo quem está usando a região crítica\n con.send(\"reservado\".encode()) #Enviando a confirmação ao cliente atual\n print(\"reservado \"+nome+\"\\n\")\n elif (cmd==\"libera\"):\n m.release() #Libera a região crítica\n uso=\"ninguem\" #Define que ninguém está usando a região crítica\n print(\"liberado \"+nome+\"\\n\")\n con.send(\"liberado\".encode()) #Envia a confirmação ao cliente atual\n else:\n print(\"ERRO\\n\")\n con.close() #Fecha conexão com o cliente\n #-----------Verifica comando recebido - Fim\n\ndef controle(i,j):\n print(\"Controle\") \n HOST = '' # Endereco IP do T1 controle\n PORT = 5004 # Porta que o T1 usa controle\n\n #Criando o servidor Controlador\n controlador = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n orig = (HOST, PORT)\n controlador.bind(orig)\n controlador.listen(128)\n \n while True:\n #Aceita a conexão, retornando o objeto de socket do cliente \n con, cliente = controlador.accept()\n #Criando uma thread para realizar as tarefas\n _thread.start_new_thread(conectado, tuple([con, cliente]))\n \n\n_thread.start_new_thread(controle,tuple([1, 2]))\nHOST = '' # Endereco IP do Servidor 1\nPORT = 5001 # Porta que o Servidor 1 esta\n\n#Criando o servidor t1\nmain = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\norig = (HOST, PORT) #Definindo a origem(servidor 1)\nmain.bind(orig) #Vinculando o host com a porta do servidor\nmain.listen(1) #Aguardando a conexão (limitado a 1)\nwhile True:\n\n #Aceita a conexão, retornando o objeto de socket do cliente\n con, cliente = main.accept()\n print ('Conectado por', cliente)\n msg=con.recv(1024) #Recebendo a mensagem do cliente\n smsg=msg.decode() #Decodificando a mensagem recebida\n sni,sa,sb = smsg.split(\";\") #Separando a mensagem a partir do ';'\n ni=int(sni)\n a=int(sa)\n b=int(sb)\n\n for i in range (ni):\n x1 = a + b #fazendo a soma dos inteiros\n\n # reserva\n HOSTS = '127.0.0.1' # Endereco IP do T2\n PORTS = 5005 # Porta que o T2 esta\n \n #Criando conexão de socket com o controlador\n controlador = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n dests = (HOSTS, PORTS)\n controlador.connect(dests)\n\n #Enviando o comando ao controlador\n controlador.send(\"reserva;T1\".encode())\n resp=controlador.recv(1024) #Recebendo resposta do controlador\n \n if (resp.decode()==\"reservado\"): #Verfica reserva da região crítica\n print(\"entra na região critica\\n\")\n controlador.close() #Fechando conexão com o controlador\n\n # ----- Região Critica - INICIO\n HOSTS = '127.0.0.1' # Endereco IP do Servidor Storage\n PORTS = 5003 # Porta que o Servidor Storage esta\n \n #Criando conexão de socket com o storage\n storage = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n dests = (HOSTS, PORTS)\n storage.connect(dests)\n\n grava=\"grava\"+\";\"+str(x1) #Criando comando para o Storage\n storage.send(grava.encode()) #Enviando o comando ao Storage\n storage.close() #Fechando conexão com o Storage\n\n #Criando conexão de socket com o Storage\n storage = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n dests = (HOSTS, PORTS)\n storage.connect(dests)\n \n le=\"le\"+\";\"+str(0) #Criando comando para o Storage\n storage.send(le.encode()) #Enviando o comando ao Storage\n lx2=storage.recv(1024) #Recebendo a resposta do Storage\n storage.close() #Fechando a conxão com o Storage\n # ------Região Critica - FIM\n\n # libera\n HOSTS = '127.0.0.1' # Endereco IP do T2\n PORTS = 5005 # Porta que o T2\n \n #Criando conexão de socket com o controlador\n controlador = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n dests = (HOSTS, PORTS) \n controlador.connect(dests)\n\n controlador.send(\"libera;T1\".encode()) #Liberando o controlador\n resp=controlador.recv(1024) #Recebendo resposta do controlador\n if (resp.decode()==\"liberado\"): #Verifica a liberação \n print(\"sai da região critica\\n\")\n controlador.close() #Fechando conexão com controlador\n\n x2=int(lx2.decode()) #Decode da mensagem recebida do Storage\n if (x1 != x2): #Verificando erro de leitura e gravação\n print(\"erro \",x1)\n resp=str(x1)\n con.send(resp.encode()) #Enviando x1 para main\n con.close() #Fechando a conexão com o main\n","sub_path":"Python/Algoritmo distribuido/PC2/t1-Adestribuido.py","file_name":"t1-Adestribuido.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"12192131","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/kensuke-mi/Desktop/analysis_work/document-feature-selection/DocumentFeatureSelection/soa/soa_python3.py\n# Compiled at: 2016-11-29 04:37:36\n# Size of source mod 2**32: 5463 bytes\nfrom scipy.sparse import csr_matrix\nfrom numpy import memmap\nfrom typing import Union\nfrom logging import getLogger, StreamHandler\nimport logging, joblib, math, numpy\nlogging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\nlogger = getLogger(__name__)\nhandler = StreamHandler()\nlogger.addHandler(handler)\n__author__ = 'kensuke-mi'\n\ndef soa(X: Union[(memmap, csr_matrix)], unit_distribution: numpy.ndarray, n_total_docs: int, feature_index: int, sample_index: int, verbose=False):\n assert isinstance(X, (memmap, csr_matrix))\n assert isinstance(unit_distribution, numpy.ndarray)\n assert isinstance(feature_index, int)\n assert isinstance(sample_index, int)\n matrix_size = X.shape\n NOT_sample_indexes = [i for i in range(0, matrix_size[0]) if i != sample_index]\n freq_w_e = X[(sample_index, feature_index)]\n freq_w_not_e = X[(NOT_sample_indexes, feature_index)].sum()\n freq_e = unit_distribution[sample_index]\n freq_not_e = n_total_docs - freq_e\n if verbose:\n logging.debug('For feature_index:{} sample_index:{}'.format(feature_index, sample_index))\n logging.debug('freq_w_e:{} freq_w_not_e:{} freq_e:{} freq_not_e:{}'.format(freq_w_e, freq_w_not_e, freq_e, freq_not_e))\n if freq_w_e == 0 or freq_w_not_e == 0 or freq_e == 0 or freq_not_e == 0:\n return 0\n else:\n nominator = float(freq_w_e) * freq_not_e\n denominator = float(freq_e) * freq_w_not_e\n ans = nominator / denominator\n assert isinstance(ans, float)\n soa_val = math.log(ans, 2)\n return soa_val\n\n\nclass SOA(object):\n\n def __init__(self):\n pass\n\n def fit_transform(self, X: Union[(memmap, csr_matrix)], unit_distribution: numpy.ndarray, n_jobs=1,\n verbose=False,\n joblib_backend='multiprocessing',\n use_cython: bool=False):\n assert isinstance(X, (memmap, csr_matrix))\n assert isinstance(unit_distribution, numpy.ndarray)\n matrix_size = X.shape\n sample_range = list(range(0, matrix_size[0]))\n feature_range = list(range(0, matrix_size[1]))\n n_total_document = sum(unit_distribution)\n logger.debug(msg='Start calculating SOA with n(process)={}'.format(n_jobs))\n logger.debug(msg='size(input_matrix)={} * {}'.format(X.shape[0], X.shape[1]))\n if use_cython:\n import pyximport\n pyximport.install()\n from DocumentFeatureSelection.soa.soa_cython import main\n logger.warning(msg='n_jobs parameter is invalid when use_cython=True')\n soa_score_csr_source = main(X=X, n_docs_distribution=unit_distribution, n_total_doc=n_total_document, sample_range=sample_range, feature_range=feature_range, verbose=False)\n else:\n self.soa = soa\n soa_score_csr_source = joblib.Parallel(n_jobs=n_jobs, backend=joblib_backend)(joblib.delayed(self.docId_word_soa)(X=X, unit_distribution=unit_distribution, feature_index=feature_index, sample_index=sample_index, n_total_doc=n_total_document, verbose=verbose) for sample_index in sample_range for feature_index in feature_range)\n row_list = [t[0] for t in soa_score_csr_source]\n col_list = [t[1] for t in soa_score_csr_source]\n data_list = [t[2] for t in soa_score_csr_source]\n soa_featured_csr_matrix = csr_matrix((data_list, (row_list, col_list)), shape=(\n X.shape[0],\n X.shape[1]))\n logging.debug(msg='End calculating SOA')\n return soa_featured_csr_matrix\n\n def docId_word_soa(self, X: Union[(memmap, csr_matrix)], unit_distribution: numpy.ndarray, n_total_doc: int, feature_index: int, sample_index: int, verbose=False):\n \"\"\"\n \"\"\"\n assert isinstance(X, (memmap, csr_matrix))\n assert isinstance(unit_distribution, numpy.ndarray)\n assert isinstance(feature_index, int)\n assert isinstance(sample_index, int)\n soa_score = self.soa(X=X, unit_distribution=unit_distribution, feature_index=feature_index, sample_index=sample_index, n_total_docs=n_total_doc, verbose=verbose)\n return (\n sample_index, feature_index, soa_score)","sub_path":"pycfiles/DocumentFeatureSelection-1.5-cp37-cp37m-macosx_10_11_x86_64/soa_python3.cpython-34.py","file_name":"soa_python3.cpython-34.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"454694153","text":"\n\nfrom xai.brain.wordbase.verbs._cut import _CUT\n\n#calss header\nclass _CUTEST(_CUT, ):\n\tdef __init__(self,): \n\t\t_CUT.__init__(self)\n\t\tself.name = \"CUTEST\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"cut\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_cutest.py","file_name":"_cutest.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"404377548","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n#\ndef pca_solve(flux,ivar,loglam=None,zfit=None,**kwargs):\n \"\"\"Replacement for idlspec2d pca_solve.pro\n \"\"\"\n import time\n import numpy as np\n import pydl.pydlspec2d.spec1d\n import pydl.pydlspec2d.spec2d\n from ... import pcomp\n from ...pydlutils.math import computechi2, djs_reject\n if 'maxiter' in kwargs:\n maxiter = kwargs['maxiter']\n else:\n maxiter = 0\n if 'niter' in kwargs:\n niter = kwargs['niter']\n else:\n niter = 10\n if 'nkeep' in kwargs:\n nkeep = kwargs['nkeep']\n else:\n nkeep = 3\n if 'nreturn' in kwargs:\n nreturn = kwargs['nreturn']\n else:\n nreturn = nkeep\n if len(flux.shape) == 1:\n nobj = 1\n npix = flux.shape[0]\n else:\n nobj, npix = flux.shape\n print(\"Building PCA from {0:d} object spectra.\".format(nobj))\n #\n # The redshift of each object in pixels would be logshift/objdloglam.\n #\n if zfit is None:\n logshift = np.zeros((nobj,),dtype=flux.dtype)\n else:\n logshift = np.log10(1.0 + zfit)\n #\n # Determine the new wavelength mapping.\n #\n if loglam is None:\n newflux = flux\n newivar = ivar\n newloglam = kwargs['newloglam']\n nnew = flux.shape[1]\n else:\n if 'newloglam' in kwargs:\n fullloglam = kwargs['newloglam']\n dloglam = fullloglam[1] - fullloglam[0]\n else:\n igood = loglam != 0\n dloglam = loglam[1] - loglam[0]\n logmin = loglam[igood].min() - logshift.max()\n logmax = loglam[igood].max() - logshift.min()\n if 'wavemin' in kwargs:\n logmin = max(logmin, np.log10(wavemin))\n if 'wavemax' in kwargs:\n logmax = min(logmax,np.log10(wavemax))\n fullloglam = pydl.pydlspec2d.spec1d.wavevector(logmin,logmax,binsz=dloglam)\n nnew = fullloglam.size\n fullflux = np.zeros((nobj,nnew),dtype='d')\n fullivar = np.zeros((nobj,nnew),dtype='d')\n #\n # Shift each spectrum to z = 0 and sample at the output wavelengths\n #\n if loglam.ndim == 1:\n indx = loglam > 0\n rowloglam = loglam[indx]\n for iobj in range(nobj):\n print(\"OBJECT {0:5d}\".format(iobj))\n if loglam.ndim > 1:\n if loglam.shape[0] != nobj:\n raise ValueError('Wrong number of dimensions for loglam.')\n indx = loglam[iobj,:] > 0\n rowloglam = loglam[iobj,indx]\n flux1,ivar1 = pydl.pydlspec2d.spec2d.combine1fiber(rowloglam-logshift[iobj],flux[iobj,indx],\n ivar[iobj,indx],newloglam=fullloglam,binsz=dloglam,aesthetics='mean') # ,verbose=True)\n fullflux[iobj,:] = flux1\n fullivar[iobj,:] = ivar1\n #\n # Find the columns out side of which there is no data at all\n #\n # nzi = fullivar.nonzero()\n # firstcol = nzi[1].min()\n # lastcol = nzi[1].max()\n # newflux = fullflux[:,firstcol:lastcol+1]\n # newivar = fullivar[:,firstcol:lastcol+1]\n # newloglam = fullloglam[firstcol:lastcol+1]\n # nnew = newloglam.size\n newflux = fullflux\n newivar = fullivar\n newloglam = fullloglam\n nzi = newivar.nonzero()\n first_nonzero = (np.arange(nobj,dtype=nzi[0].dtype),\n np.array([nzi[1][nzi[0]==k].min() for k in range(nobj)]))\n #\n # Construct the synthetic weight vector, to be used when replacing the\n # low-S/N object pixels with the reconstructions.\n #\n synwvec = np.ones((nnew,),dtype='d')\n for ipix in range(nnew):\n indx = newivar[:,ipix] != 0\n if indx.any():\n synwvec[ipix] = newivar[indx,ipix].mean()\n fluxdict = {'flux':newflux, 'eigenval':1.0, 'acoeff':1.0,\n 'outmask':np.ones((nnew,),dtype='i4'),\n 'usemask':np.ones((nnew,),dtype='i4'),\n 'newflux':newflux,'newivar':newivar,\n 'newloglam':newloglam, }\n # 'emevecs':1.0, 'emevals':1.0}\n #\n # If there is only one object spectrum, then all we can do is return it.\n #\n if nobj == 1:\n fluxdict['flux'] = newflux.astype('f')\n return fluxdict\n #\n # Rejection iteration loop.\n #\n qdone = 0\n iiter = 0\n #\n # Begin with all points good.\n #\n outmask = None\n inmask = newivar != 0\n ymodel = None\n # emevecs, emevals = pydlutils.empca(newflux,inmask)\n # fluxdict['emevecs'] = emevecs\n # fluxdict['emevals'] = emeveals\n while qdone == 0 and iiter <= maxiter:\n # print('starting djs_reject')\n outmask,qdone = djs_reject(newflux,ymodel,\n inmask=inmask,outmask=outmask,\n invvar=newivar)\n # print('finished with djs_reject')\n #\n # Iteratively do the PCA solution\n #\n filtflux = newflux.copy()\n acoeff = np.zeros((nobj,nkeep),dtype='d')\n t0 = time.time()\n for ipiter in range(niter):\n #\n # We want to get these values from the pcomp routine.\n #\n # eigenval = 1\n # coeff = 1\n flux0 = np.tile(filtflux[first_nonzero],nnew).reshape(nnew,nobj).transpose()\n # flux0 = np.tile(filtflux,nnew).reshape(nnew,nobj).transpose()\n totflux = np.absolute(filtflux - flux0).sum(1)\n goodobj = totflux > 0\n if goodobj.all():\n tmp = pcomp(filtflux.T) # ,standardize=True)\n pres = tmp.derived\n eigenval = tmp.eigenvalues\n else:\n tmp = pcomp(filtflux[goodobj,:].T) # ,standardize=True)\n pres = np.zeros((nobj,nnew),dtype='d')\n pres[goodobj,:] = tmp.derived\n eigenval = np.zeros((nobj,),dtype='d')\n eigenval[goodobj] = tmp.eigenvalues\n maskivar = newivar * outmask\n sqivar = np.sqrt(maskivar)\n for iobj in range(nobj):\n out = computechi2(newflux[iobj,:], sqivar[iobj,:],\n pres[:,0:nkeep])\n filtflux[iobj,:] = (maskivar[iobj,:] * newflux[iobj,:] +\n synwvec*out.yfit) / (maskivar[iobj,:] + synwvec)\n acoeff[iobj,:] = out.acoeff\n if 'quiet' not in kwargs:\n print(\"The elapsed time for iteration #{0:2d} is {1:6.2f} s.\".format(ipiter+1,time.time()-t0))\n #\n # Now set ymodel for rejecting points.\n #\n ymodel = np.dot(acoeff,pres[:,0:nkeep].T)\n iiter += 1\n if nobj == 1:\n usemask = outmask\n else:\n usemask = outmask.sum(0)\n fluxdict['usemask'] = usemask\n fluxdict['outmask'] = outmask\n fluxdict['flux'] = pres[:,0:nreturn].transpose().astype('f')\n fluxdict['eigenval'] = eigenval[0:nreturn]\n fluxdict['acoeff'] = acoeff\n return fluxdict\n\n","sub_path":"pydl/pydlspec2d/spec1d/pca_solve.py","file_name":"pca_solve.py","file_ext":"py","file_size_in_byte":6971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"439938439","text":"from PIL import ImageGrab\r\nimport numpy as np\r\nimport cv2\r\nfrom win32api import GetSystemMetrics\r\nimport datetime\r\n\r\nwidth = GetSystemMetrics(0)\r\nheight = GetSystemMetrics(1)\r\nfourcc = cv2.VideoWriter_fourcc('m','p','4','v')\r\nts = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')\r\nfn = f'{ts}.mp4'\r\nvideo_capture = cv2.VideoWriter(fn, fourcc, 20.0, (width, height))\r\n\r\nprint(width)\r\nprint(height)\r\n\r\ncam = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n img = ImageGrab.grab(bbox=(0, 0, width, height))\r\n img_np = np.array(img)\r\n img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)\r\n \r\n _, frame = cam.read()\r\n fh, fw, _ = frame.shape\r\n \r\n img_np[height-fh:, width-fw:, :] = frame[0:fh, 0:fw, :]\r\n \r\n cv2.imshow('Screen Recorder', img_np)\r\n video_capture.write(img_np)\r\n if cv2.waitKey(10) == ord('q'):\r\n break","sub_path":"ScreenRecorder.py","file_name":"ScreenRecorder.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"160244643","text":"#\n# Confidential and Proprietary Source Code\n#\n# This Digital Domain Productions, Inc. source code, including without\n# limitation any human-readable computer programming code and associated\n# documentation (together \"Source Code\"), contains valuable confidential,\n# proprietary and trade secret information of Digital Domain Productions and is\n# protected by the laws of the United States and other countries. Digital\n# Domain Productions, Inc. may, from time to time, authorize specific employees\n# to use the Source Code internally at Digital Domain Production Inc.'s premises\n# solely for developing, updating, and/or troubleshooting the Source Code. Any\n# other use of the Source Code, including without limitation any disclosure,\n# copying or reproduction, without the prior written authorization of Digital\n# Domain Productions, Inc. is strictly prohibited.\n#\n# Copyright (c) [2012] Digital Domain Productions, Inc. All rights reserved.\n#\n# $URL$\n# $Date: 2014-06-18$\n# $Revision: 1.0$\n# $Author: cwong $\n#\n\n\n'''\nNAME\n ddPublishShader.py\n\nDESC\n Renames shading networks, validates textures and publishes shader and screen grab \n into selected category folder in shaderLibrary.\n Dimensions must be square, less than 2K and a power of 2.\n\nUSAGE\n (from ddShaderLibrary)\n ddPublishShader.do()\n \nFUNCTIONS\n doNameShaders()\n getAssetShaderLibrary()\n getAssetTextureLibrary()\n getCategoryFolder()\n getConnectedShadingEngine()\n validateTextureFile()\n do()\n \n'''\n\n# MAYA\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport maya.OpenMaya as om\n\n# PYTHON\nimport os\nimport sys\nimport shutil\nimport imghdr\nimport math\n\n# VAD\nimport ddConstants; reload(ddConstants)\nimport ddCheckForDuplicateShader; reload(ddCheckForDuplicateShader)\nimport ddCheckTextures; reload(ddCheckTextures)\nimport ddDeleteUnknownNodes; reload(ddDeleteUnknownNodes)\nimport ddRemoveRequires; reload(ddRemoveRequires)\n\n\ndef doNameShaders(node, directory):\n '''\n Rename the shading network nodes.\n @param node: Node with connected shader.\n @param directory: Category directory. \n '''\n textureDir = getAssetTextureLibrary()\n currentAssetDirectory = getAssetLibrary()\n dividerTypes = [\"CPF\", \"CPO\", \"CPD\"]\n \n divider = \"\"\n nodeParts = node.split(\"_\")\n for nodePart in nodeParts:\n if nodePart in dividerTypes:\n divider = nodePart\n \n # Get shape node.\n shapeNode = cmds.listRelatives(node, shapes=True, path=True)\n if shapeNode:\n cmds.select(shapeNode, replace=True)\n cmds.refresh()\n \n # Get name for shader.\n found = False\n result = \"OK\"\n rootName = \"\"\n \n # Create a starting name for promptDialog.\n meshDescriptor = \"\"\n if currentAssetDirectory == ddConstants.CHAR_ASSETLIBRARY:\n meshDescriptor = node.rpartition(\"|\")[2].rpartition(\"_%s\" % divider)[0].partition(\"_\")[2].partition(\"_\")[2].replace(\"_\", \"\")\n else:\n meshDescriptor = node.rpartition(\"|\")[2].rpartition(\"_GEO\")[0].rpartition(\"_\")[2]\n \n if not meshDescriptor:\n meshDescriptor = node.replace(\"_SG\", \"\").replace(\"_SHD\", \"\").rpartition(\"|\")[2]\n while not found and not result == \"Cancel\":\n result = cmds.promptDialog(\n title=\"Shader Namer\", messageAlign=\"center\", \n message='Enter a name for the shader. ', text=meshDescriptor, \n button=[\"OK\", \"Cancel\"], \n defaultButton=\"OK\", cancelButton=\"Cancel\", dismissString=\"Cancel\"\n )\n if result == \"Cancel\": \n return False \n rootName = cmds.promptDialog(query=True, text=True).rpartition(\"|\")[2]\n \n # Check for invalid character at end of rootName\n if not ((ord(rootName[-1]) in range(97, 123)) or (ord(rootName[-1]) in range(65, 91)) or \n (ord(rootName[-1]) in range(48, 58))):\n confirmInvalid = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", \n message=\"Invalid character at end of name. \", \n button=[\" Enter a New Name \", \"Cancel\"], \n defaultButton=\" Enter a New Name \", cancelButton=\"Cancel\", dismissString=\"Cancel\"\n )\n if confirmInvalid == \"Cancel\":\n return False\n else:\n # Check for existing swatch.\n swatchPath = os.path.join(directory, \"%s.ma\" % rootName)\n if not os.path.isfile(swatchPath):\n found = True\n else:\n confirm = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", \n message=\"Swatch name already exists. \", \n button=[\" Enter a New Name \", \"Replace\", \"Cancel\"], \n defaultButton=\" Enter a New Name \", cancelButton=\"Cancel\", dismissString=\"Cancel\"\n )\n if confirm == \"Cancel\":\n return False\n elif confirm == \"Replace\":\n found = True\n \n # Rename the shading engine.\n shadingEngine = getConnectedShadingEngine(node)\n if shadingEngine:\n try:\n shadingEngine = cmds.rename(shadingEngine, \"%s_SG\" % rootName)\n except:\n sys.stdout.write(\"--> Cannot publish read only shader %s. Skipping... \\n\" % shadingEngine)\n confirm = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", \n message=\"Cannot publish read only shader %s. \" % shadingEngine, \n button=[\"Cancel\"], \n defaultButton=\"Cancel\", cancelButton=\"Cancel\", dismissString=\"Cancel\"\n )\n if confirm == \"Cancel\":\n return False\n \n return False\n else:\n sys.stdout.write(\"--> No shading engine found for %s. Skipping... \\n\" % node)\n \n # Rename the surface shader\n surfaceShader = cmds.listConnections(\"%s.surfaceShader\" % shadingEngine) \n if surfaceShader:\n surfaceShader = cmds.rename(surfaceShader[0], \"%s_SHD\" % rootName)\n else:\n sys.stdout.write(\"--> No surface shader found for %s. Skipping... \\n\" % surfaceShader)\n \n # Rename the other shading network nodes.\n historyList = cmds.listHistory(shadingEngine) or []\n fileNodes = [x for x in historyList if cmds.nodeType(x) == \"file\"] or []\n \n # From fileNodes, check if a similar shader has already been published.\n confirm = cmds.confirmDialog(\n title=\"Question\", messageAlign=\"center\", \n message=\"Check if a similar shader has already been published? It might take a few minutes... \", \n button=[\" Continue With Check \", \" Publish Without Checking \"], \n defaultButton=\" Continue With Check \", cancelButton=\" Publish Without Checking \", \n dismissString=\" Publish Without Checking \"\n )\n if confirm == \" Continue With Check \":\n alreadyExists = ddCheckForDuplicateShader.do(fileNodes)\n if alreadyExists == \"Fail\":\n return False\n if alreadyExists:\n confirm = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", \n message=\"Shader resembles an already published shader: %s. \" % alreadyExists, \n button=[\" Continue With Publish \", \" Cancel Publish \"], \n defaultButton=\" Continue With Publish \", cancelButton=\" Cancel Publish \", \n dismissString=\" Cancel Publish \"\n )\n if confirm == \" Cancel Publish \":\n return False \n \n for fileNode in fileNodes:\n # Copy the file textures on disk and rename.\n fileTextureName = cmds.getAttr(\"%s.fileTextureName\" % fileNode)\n cnxList = cmds.listConnections(fileNode, source=False, destination=True, plugs=True) or []\n fileNodeCnx = [x for x in cnxList if surfaceShader in x or \"bumpValue\" in x]\n if fileNodeCnx:\n for nodeCnx in fileNodeCnx:\n attr = nodeCnx.partition(\".\")[2]\n if attr in ddConstants.textureTypes.keys():\n if not validateTextureFile(fileNode, fileTextureName, publish=True):\n return False\n \n fileNode = cmds.rename(fileNode, \"%s_%s_FIL\" % (rootName, ddConstants.textureTypes[attr]))\n if \"bump\" in nodeCnx:\n cmds.rename(nodeCnx.partition(\".\")[0], \"%s_%s_BMP\" % (rootName, ddConstants.textureTypes[attr]))\n placeTextureNode = cmds.listConnections(fileNode, source=True, destination=False)\n if placeTextureNode:\n cmds.rename(placeTextureNode[0].partition(\".\")[0], \"%s_%s_PTN\" % (rootName, ddConstants.textureTypes[attr]))\n \n newFileName = \"%s_%s_SL.tif\" % (rootName, ddConstants.textureTypes[attr])\n newFilePath = os.path.join(textureDir, newFileName)\n \n if not (fileTextureName.replace(\"/\", os.sep) == newFilePath) and not (fileTextureName == newFilePath):\n shutil.copy(fileTextureName, newFilePath)\n cmds.setAttr(\"%s.fileTextureName\" % fileNode, newFilePath, type=\"string\")\n \n # Remove stray namespaces.\n surfaceShaderCnxList = cmds.listConnections(surfaceShader) or []\n for shaderCnx in surfaceShaderCnxList:\n if \":\" in shaderCnx:\n shaderNamespace = shaderCnx.partition(\":\")[0]\n cmds.select(shaderCnx, replace=True)\n cmds.namespace(mv=(shaderNamespace, \":\"), force=True)\n \n sys.stdout.write(\"Shader renamed: %s\\n\" % surfaceShader)\n \n return shadingEngine\n \n# end (doNameShaders)\n\n\ndef getAssetCategory(arg=None):\n '''Return selected asset category.\n '''\n selected = cmds.optionMenu(\"assetCategoryMenu\", query=True, select=True)\n currentAssetCategory = ddConstants.ASSET_CATEGORIES[selected-1]\n return currentAssetCategory\n\n\ndef getAssetLibrary(arg=None):\n '''Get selected asset category and return corresponding shader directory.\n '''\n assetCategory = getAssetCategory()\n currentAssetLibrary = ddConstants.ASSET_DIRECTORIES[assetCategory]\n return currentAssetLibrary\n\n\ndef getAssetShaderLibrary(arg=None):\n '''Get selected asset category and return corresponding shader directory.\n '''\n assetCategory = getAssetCategory()\n currentShaderLibrary = ddConstants.SHADER_DIRECTORIES[assetCategory]\n \n return currentShaderLibrary\n\n\ndef getAssetTextureLibrary(arg=None):\n '''Get selected asset category and return corresponding texture directory.\n '''\n assetCategory = getAssetCategory()\n currentTextureDirectory = ddConstants.TEXTURE_DIRECTORIES[assetCategory]\n \n return currentTextureDirectory\n\n\ndef getCategoryFolder(arg=None):\n '''Get selected category folder and return corresponding category directory.\n '''\n currentShaderLibrary = getAssetShaderLibrary()\n category = cmds.textScrollList(\"shaderCategoriesSL\", query=True, selectItem=True)\n directory = currentShaderLibrary\n if category:\n category = category[0]\n if not (category == \"-- UNFILED --\"):\n directory = os.path.join(currentShaderLibrary, category)\n \n return directory\n\n\ndef getConnectedShadingEngine(node):\n '''Find shading engine connected to node.\n '''\n shapeNode = \"\"\n if cmds.nodeType(node) == \"shadingEngine\":\n return node\n \n if cmds.nodeType(node) == \"mesh\":\n shapeNode = [node]\n else:\n shapeNode = cmds.listRelatives(node, shapes=True, path=True)\n if shapeNode: \n shadingEngines = cmds.listConnections(shapeNode[0], type=\"shadingEngine\") or []\n shadingEngines = list(set(shadingEngines))\n if shadingEngines:\n return shadingEngines[0]\n \n return None\n\n\ndef validateTextureFile(fileNode, fileTextureName, publish=True):\n '''\n Check if texture file is tif format and dimensions are square, under 2K and powers of 2.\n @param fileNode: Maya file node.\n @param fileTextureName: From the file node attribute.\n @param publish: If True, stop on errors. Otherwise, just validate.\n '''\n return ddCheckTextures.validateTextureFile(fileNode,\n fileTextureName,\n publish, guibose=True)\n\n# end (validateTextureFile)\n\n\ndef do(nodes=None):\n '''\n Publish shader attached to nodes.\n @param nodes: One or more GEO or shader nodes.\n '''\n currentShaderLibrary = getAssetShaderLibrary()\n\n # Swatches file storage location.\n if not os.path.isdir(currentShaderLibrary):\n raise Exception(\"Directory %s does not exist\" % currentShaderLibrary)\n \n if not nodes:\n nodes = cmds.ls(selection=True, long=True)\n # If still no nodes...\n if not nodes:\n sys.stdout.write(\"Select a mesh with an attached shader to be published.\\n\")\n \n if not isinstance(nodes, list):\n nodes = [nodes]\n \n for node in nodes:\n currentNode = node\n \n # Check if referenced.\n if cmds.referenceQuery(node, isNodeReferenced=True):\n confirm = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", \n message='Cannot publish a referenced shader. Try importing from reference.', \n button=[\"Ok\"], \n defaultButton=\"Ok\", cancelButton=\"Ok\", dismissString=\"Ok\")\n if confirm == \"Ok\":\n return\n \n # If node is not a mesh, look for a shading engine.\n if not cmds.listRelatives(currentNode, shapes=True):\n # Check if node is a GRP with one mesh below.\n children = cmds.listRelatives(currentNode, children=True)\n if children:\n if len(children) == 1 and cmds.listRelatives(children[0], shapes=True):\n currentNode = children[0]\n else:\n confirm = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", message='Unable to determine which shader to publish.', \n button=[\"Ok\"], defaultButton=\"Ok\", cancelButton=\"Ok\", dismissString=\"Ok\"\n )\n if confirm == \"Ok\":\n return\n else:\n # Look for a connected shading engine.\n shadingEngines = [x for x in (cmds.listHistory(currentNode, future=True) or []) if cmds.nodeType(x) == \"shadingEngine\"]\n if shadingEngines:\n currentNode = shadingEngines[0]\n else:\n confirm = cmds.confirmDialog(\n title=\"Warning\", messageAlign=\"center\", message='Unable to find a shader to publish.', \n button=[\"Ok\"], defaultButton=\"Ok\", cancelButton=\"Ok\", dismissString=\"Ok\"\n )\n if confirm == \"Ok\":\n return\n \n # Get the shader category.\n directory = getCategoryFolder()\n shadingEngine = doNameShaders(node=currentNode, directory=directory)\n if not shadingEngine:\n continue\n \n rootName = shadingEngine.replace(\"_SG\", \"\")\n \n # Create swatch.\n swatch = cmds.polyPlane(name=\"%s_Swatch\" % rootName, width=1, height=1, sx=1, sy=1, ax=[0,0,1], ch=0)\n swatchShape = cmds.listRelatives(swatch, shapes=True, path=True)\n cmds.sets(swatchShape, forceElement=shadingEngine)\n \n imagePath = os.path.join(directory, \"%s.png\" % rootName)\n \n # Create snapshot.\n screenGrabCam = cmds.camera(centerOfInterest=378.926)\n cmds.setAttr(\"%s.tz\" % screenGrabCam[0], 378.926)\n cmds.setAttr(\"%s.orthographic\" % screenGrabCam[1], 1)\n\n cmds.select(swatch, replace=True)\n \n currentPanel = \"modelPanel4\"\n if not cmds.modelEditor(currentPanel, exists=True):\n currentPanel = cmds.getPanel(withFocus=True)\n \n mel.eval('enableIsolateSelect %s true;' % currentPanel)\n cmds.isolateSelect(currentPanel, state=1)\n mel.eval('lookThroughModelPanel %s %s' % (screenGrabCam[0], currentPanel))\n \n cmds.viewFit()\n cmds.setAttr(\"%s.orthographicWidth\" % screenGrabCam[1], 1)\n cmds.select(clear=True)\n gridValue = cmds.modelEditor(currentPanel, query=True, grid=True)\n cmds.modelEditor(\n currentPanel, edit=True, displayAppearance=\"smoothShaded\", \n displayTextures=True, displayLights=\"default\", grid=False\n )\n cmds.playblast(\n frame=1, format=\"image\", completeFilename=imagePath, clearCache=True, viewer=False, \n showOrnaments=False, compression=\"png\", quality=40, percent=100, widthHeight=[144,144]\n )\n cmds.isolateSelect(currentPanel, state=0)\n cmds.modelEditor(currentPanel, edit=True, grid=gridValue)\n mel.eval('lookThroughModelPanel persp %s' % currentPanel)\n cmds.delete(screenGrabCam[0])\n sys.stdout.write(\"Screen grab of swatch saved to: %s\\n\" % imagePath)\n \n # Delete unknown nodes (mental ray).\n ddDeleteUnknownNodes.do()\n \n # Export swatch file.\n swatchPath = os.path.join(directory, \"%s.ma\" % rootName)\n cmds.select(swatch, replace=True)\n exportedFile = cmds.file(swatchPath, type=\"mayaAscii\", exportSelected=True, force=True)\n ddRemoveRequires.do(path=swatchPath)\n \n if exportedFile:\n cmds.delete(swatch)\n \n# end (do)","sub_path":"cw_scripts/ddPublishShader.py","file_name":"ddPublishShader.py","file_ext":"py","file_size_in_byte":17955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"566270684","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Interpreter version: python 2.7\n#\n\"\"\"\nThis module contains number of functions, which are used at multiple places in\nautoparser.\n\"\"\"\n# Imports =====================================================================\nimport dhtmlparser\n\n\n# Functions & objects =========================================================\ndef _get_encoding(dom, default=\"utf-8\"):\n \"\"\"\n Try to look for meta tag in given `dom`.\n\n Args:\n dom (obj): pyDHTMLParser dom of HTML elements.\n default (default \"utr-8\"): What to use if encoding is not found in\n `dom`.\n\n Returns:\n str/default: Given encoding or `default` parameter if not found.\n \"\"\"\n encoding = dom.find(\"meta\", {\"http-equiv\": \"Content-Type\"})\n\n if not encoding:\n return default\n\n encoding = encoding[0].params.get(\"content\", None)\n\n if not encoding:\n return default\n\n return encoding.lower().split(\"=\")[-1]\n\n\ndef handle_encodnig(html):\n \"\"\"\n Look for encoding in given `html`. Try to convert `html` to utf-8.\n\n Args:\n html (str): HTML code as string.\n\n Returns:\n str: HTML code encoded in UTF.\n \"\"\"\n encoding = _get_encoding(\n dhtmlparser.parseString(\n html.split(\"\")[0]\n )\n )\n\n if encoding == \"utf-8\":\n return html\n\n return html.decode(encoding).encode(\"utf-8\")\n\n\ndef content_matchs(tag_content, content_transformer=None):\n \"\"\"\n Generate function, which checks whether the content of the tag matchs\n `tag_content`.\n\n Args:\n tag_content (str): Content of the tag which will be matched thru whole\n DOM.\n content_transformer (fn, default None): Function used to transform all\n tags before matching.\n\n Returns:\n bool: True for every matching tag.\n\n Note:\n This function can be used as parameter for ``.find()`` method in\n HTMLElement.\n \"\"\"\n def content_matchs_closure(element):\n if not element.isTag():\n return False\n\n cont = element.getContent()\n if content_transformer:\n cont = content_transformer(cont)\n\n return tag_content == cont\n\n return content_matchs_closure\n\n\ndef is_equal_tag(element, tag_name, params, content):\n \"\"\"\n Check is `element` object match rest of the parameters.\n\n All checks are performed only if proper attribute is set in the HTMLElement.\n\n Args:\n element (obj): HTMLElement instance.\n tag_name (str): Tag name.\n params (dict): Parameters of the tag.\n content (str): Content of the tag.\n\n Returns:\n bool: True if everyhing matchs, False otherwise.\n \"\"\"\n if tag_name and tag_name != element.getTagName():\n return False\n\n if params and not element.containsParamSubset(params):\n return False\n\n if content is not None and content.strip() != element.getContent().strip():\n return False\n\n return True\n\n\ndef has_neigh(tag_name, params=None, content=None, left=True):\n \"\"\"\n This function generates functions, which matches all tags with neighbours\n defined by parameters.\n\n Args:\n tag_name (str): Tag has to have neighbour with this tagname.\n params (dict): Tag has to have neighbour with this parameters.\n params (str): Tag has to have neighbour with this content.\n left (bool, default True): Tag has to have neigbour on the left, or\n right (set to ``False``).\n\n Returns:\n bool: True for every matching tag.\n\n Note:\n This function can be used as parameter for ``.find()`` method in\n HTMLElement.\n \"\"\"\n def has_neigh_closure(element):\n if not element.parent \\\n or not (element.isTag() and not element.isEndTag()):\n return False\n\n # filter only visible tags/neighbours\n childs = element.parent.childs\n childs = filter(\n lambda x: (x.isTag() and not x.isEndTag()) \\\n or x.getContent().strip() or x is element,\n childs\n )\n if len(childs) <= 1:\n return False\n\n ioe = childs.index(element)\n if left and ioe > 0:\n return is_equal_tag(childs[ioe - 1], tag_name, params, content)\n\n if not left and ioe + 1 < len(childs):\n return is_equal_tag(childs[ioe + 1], tag_name, params, content)\n\n return False\n\n return has_neigh_closure\n","sub_path":"src/edeposit/amqp/harvester/autoparser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"177297521","text":"import psycopg2\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\nfrom pandas import DataFrame\nimport datetime\nimport smtplib\n\n#Actual time\nnow_time = '{0:%Y-%m-%d}'.format(datetime.datetime.now())\n\n#Counting errors\nerror_count = 0\nerror_msg = 'Errors, if any:\\n'\n\n#database check parameter\ndbcheck = True\n\n#Fetching login data from text file\ntry:\n cred_list = []\n with open('/home/pi/Documents/logfiles/login_metgrab_database.txt', 'r') as loginfile:\n for item in loginfile.read().split(','):\n cred_list.append(item)\n\n user = cred_list[0]\n pword = cred_list[1]\n\n\t\n #Connecting to the PostgreSQL database\n dsn = \"dbname='met_project' user='\"+user+\"' host = 'localhost' password='\"+pword+\"'\"\n conn = psycopg2.connect(dsn)\n print('Successful login!')\n conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n\n # Define a cursor to work with\n cur = conn.cursor()\nexcept:\n error_count += 101\n error_msg + ' Database not available!'\n print('Database not available!')\n dbcheck = False\n\n#If dbcheck = False, this part won't be executed\nif dbcheck:\n\n #######Fetching OMSZ data#######\n try:\n sql_omsz = \"SELECT timeofrequest, Fcst_Tmin_for_day1, Fcst_Tmax_for_day1 FROM omsz_table ORDER BY timeofrequest DESC LIMIT 1;\"\n cur.execute(sql_omsz)\n fetched_data_omsz = cur.fetchall()\n except:\n print(\"Problem with OMSZ data, cannot fetch last row!\")\n error_count += 1\n error_msg + 'Cannot fetch OMSZ data! '\n\n #######Fetching Idokep data#######\n try:\n sql_idokep = \"SELECT timeofrequest, Fcst_Tmin_for_day1, Fcst_Tmax_for_day1 FROM idokep_table ORDER BY timeofrequest DESC LIMIT 1;\"\n cur.execute(sql_idokep)\n fetched_data_idokep = cur.fetchall()\n except:\n print(\"Problem with Idokep data, cannot fetch last row!\")\n error_count += 1\n error_msg + 'Cannot fetch Időkép data! '\n\n #######Fetching Koponyeg data#######\n try:\n sql_koponyeg = \"SELECT timeofrequest, Fcst_Tmin_for_day1, Fcst_Tmax_for_day1 FROM koponyeg_table ORDER BY timeofrequest DESC LIMIT 1;\"\n cur.execute(sql_koponyeg)\n fetched_data_koponyeg = cur.fetchall()\n except:\n print(\"Problem with Koponyeg data, cannot fetch last row!\")\n error_count += 1\n error_msg + 'Cannot fetch Köpönyeg data! '\n\n #######Fetching Ogimet data#######\n try:\n sql_ogimet = \"SELECT timeofrequest, Obs_Tmin, Obs_Tmax FROM ogimet_table ORDER BY timeofrequest DESC LIMIT 1;\"\n cur.execute(sql_ogimet)\n fetched_data_ogimet = cur.fetchall()\n except:\n print(\"Problem with Ogimet data, cannot fetch last row!\")\n error_count += 1\n error_msg + 'Cannot fetch Ogimet data! '\n\n #######Checking date of the last row of omsz_table#######\n if (now_time == fetched_data_omsz[0][0][0:10]) and (fetched_data_omsz[0][1] != None) and (fetched_data_omsz[0][2] != None):\n print('OMSZ OK!')\n else:\n error_count += 1\n error_msg + 'Problem with OMSZ data! '\n\n #Checking date of the last row of idokep_table#######\n if (now_time == fetched_data_idokep[0][0][0:10]) and (fetched_data_idokep[0][1] != None) and (fetched_data_idokep[0][2] != None):\n print('Idokep OK!')\n else:\n error_count += 1\n error_msg + 'Problem with Időkep data! '\n\n #Checking date of the last row of koponyeg_table#######\n if (now_time == fetched_data_koponyeg[0][0][0:10]) and (fetched_data_koponyeg[0][1] != None) and (fetched_data_koponyeg[0][2] != None):\n print('Koponyeg OK!')\n else:\n error_count += 1\n error_msg + 'Problem with Köpönyeg data! '\n\n #Checking date of the last row of ogimet_table#######\n if (now_time == fetched_data_ogimet[0][0][0:10]) and (fetched_data_ogimet[0][1] != None) and (fetched_data_ogimet[0][2] != None):\n print('Ogimet OK!')\n else:\n error_count += 1\n error_msg + 'Problem with Ogimet data! '\n\nprint('Number of errors: ' + str(error_count))\n\n## SENDING WARNING MAIL ONLY IF error_count > 0!\nif error_count > 0:\n\n #Fetching login data from text file\n cred_list_gmail = []\n with open('/home/pi/Documents/logfiles/login_gmail.txt', 'r') as loginfile_gmail:\n for item in loginfile_gmail.read().split(','):\n cred_list_gmail.append(item)\n\n mail = cred_list_gmail[0]\n mail_pword = cred_list_gmail[1]\n\n send_to = cred_list_gmail[0]\n mail_subject = 'metgrab.py warning message'\n if error_count < 100:\n mail_text = 'Database is missing some data, please check it!\\nNumber of wrong or incomplete tables: ' + str(error_count) + '\\n' + error_msg + 'Diagram has not been drawn.'\n else:\n mail_text = 'Database connection problem!' + '\\nDiagram has not been drawn.'\n\n #GMail creditentials\n gmail_sender = cred_list_gmail[0]\n gmail_passwd = cred_list_gmail[1]\n\n #Create connection to GMail service\n smtpObj = smtplib.SMTP('smtp.gmail.com', 587)\n smtpObj.ehlo()\n smtpObj.starttls()\n smtpObj.login(gmail_sender, gmail_passwd)\n\n mail_body = '\\r\\n'.join([\n 'To: %s' % send_to,\n 'From: %s' % gmail_sender,\n 'Subject: %s' % mail_subject,\n '',\n mail_text\n ])\n\n #Sending the mail\n smtpObj.sendmail(gmail_sender, [send_to], mail_body)\n print('Warning e-mail sent')\n smtpObj.quit()\n with open('/home/pi/working_python/metgrab/database_check_output.txt', 'w') as textfile:\n textfile.write('0')\n\nelse:\n with open('/home/pi/working_python/metgrab/database_check_output.txt', 'w') as textfile:\n textfile.write('1')","sub_path":"database_check.py","file_name":"database_check.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"542802107","text":"###############################################################################\n'''This code has functions which process the information in the .h5 files\ndatafile_{}_{}.h5 and convert them into a format usable by Keras.'''\n###############################################################################\n\nimport numpy as np\nimport re\nfrom math import ceil\nfrom sklearn.metrics import average_precision_score\nfrom constants import *\n\nassert CL_max % 2 == 0\n\nIN_MAP = np.asarray([[0, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n# One-hot encoding of the inputs: 0 is for padding, and 1, 2, 3, 4 correspond\n# to A, C, G, T respectively.\n\nOUT_MAP = np.asarray([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n [0, 0, 0]])\n# One-hot encoding of the outputs: 0 is for no splice, 1 is for acceptor,\n# 2 is for donor and -1 is for padding.\n\n\ndef ceil_div(x, y):\n\n return int(ceil(float(x)/y))\n\n\ndef create_datapoints(seq, strand, tx_start, tx_end, jn_start, jn_end):\n # This function first converts the sequence into an integer array, where\n # A, C, G, T, N are mapped to 1, 2, 3, 4, 0 respectively. If the strand is\n # negative, then reverse complementing is done. The splice junctions \n # are also converted into an array of integers, where 0, 1, 2, -1 \n # correspond to no splicing, acceptor, donor and missing information\n # respectively. It then calls reformat_data and one_hot_encode\n # and returns X, Y which can be used by Keras models.\n\n seq = 'N'*(CL_max//2) + seq[CL_max//2:-CL_max//2] + 'N'*(CL_max//2)\n # Context being provided on the RNA and not the DNA\n\n seq = seq.upper().replace('A', '1').replace('C', '2')\n seq = seq.replace('G', '3').replace('T', '4').replace('N', '0')\n\n tx_start = int(tx_start)\n tx_end = int(tx_end) \n\n jn_start = map(lambda x: map(int, re.split(',', x)[:-1]), jn_start)\n jn_end = map(lambda x: map(int, re.split(',', x)[:-1]), jn_end)\n\n if strand == '+':\n\n X0 = np.asarray(map(int, list(seq)))\n Y0 = [-np.ones(tx_end-tx_start+1) for t in range(1)]\n\n for t in range(1):\n \n if len(jn_start[t]) > 0:\n Y0[t] = np.zeros(tx_end-tx_start+1)\n for c in jn_start[t]:\n if tx_start <= c <= tx_end:\n Y0[t][c-tx_start] = 2\n for c in jn_end[t]:\n if tx_start <= c <= tx_end:\n Y0[t][c-tx_start] = 1\n # Ignoring junctions outside annotated tx start/end sites\n \n elif strand == '-':\n\n X0 = (5-np.asarray(map(int, list(seq[::-1])))) % 5 # Reverse complement\n Y0 = [-np.ones(tx_end-tx_start+1) for t in range(1)]\n\n for t in range(1):\n\n if len(jn_start[t]) > 0:\n Y0[t] = np.zeros(tx_end-tx_start+1)\n for c in jn_end[t]:\n if tx_start <= c <= tx_end:\n Y0[t][tx_end-c] = 2\n for c in jn_start[t]:\n if tx_start <= c <= tx_end:\n Y0[t][tx_end-c] = 1\n\n Xd, Yd = reformat_data(X0, Y0)\n X, Y = one_hot_encode(Xd, Yd)\n\n return X, Y\n\n\ndef reformat_data(X0, Y0):\n # This function converts X0, Y0 of the create_datapoints function into\n # blocks such that the data is broken down into data points where the\n # input is a sequence of length SL+CL_max corresponding to SL nucleotides\n # of interest and CL_max context nucleotides, the output is a sequence of\n # length SL corresponding to the splicing information of the nucleotides\n # of interest. The CL_max context nucleotides are such that they are\n # CL_max/2 on either side of the SL nucleotides of interest.\n\n num_points = ceil_div(len(Y0[0]), SL)\n\n Xd = np.zeros((num_points, SL+CL_max))\n Yd = [-np.ones((num_points, SL)) for t in range(1)]\n\n X0 = np.pad(X0, [0, SL], 'constant', constant_values=0)\n Y0 = [np.pad(Y0[t], [0, SL], 'constant', constant_values=-1)\n for t in range(1)]\n\n for i in range(num_points):\n Xd[i] = X0[SL*i:CL_max+SL*(i+1)]\n\n for t in range(1):\n for i in range(num_points):\n Yd[t][i] = Y0[t][SL*i:SL*(i+1)]\n\n return Xd, Yd\n\n\ndef clip_datapoints(X, Y, CL, N_GPUS):\n # This function is necessary to make sure of the following:\n # (i) Each time model_m.fit is called, the number of datapoints is a\n # multiple of N_GPUS. Failure to ensure this often results in crashes.\n # (ii) If the required context length is less than CL_max, then\n # appropriate clipping is done below.\n # Additionally, Y is also converted to a list (the .h5 files store \n # them as an array).\n\n rem = X.shape[0]%N_GPUS\n clip = (CL_max-CL)//2\n\n if rem != 0 and clip != 0:\n return X[:-rem, clip:-clip], [Y[t][:-rem] for t in range(1)]\n elif rem == 0 and clip != 0:\n return X[:, clip:-clip], [Y[t] for t in range(1)]\n elif rem != 0 and clip == 0:\n return X[:-rem], [Y[t][:-rem] for t in range(1)]\n else:\n return X, [Y[t] for t in range(1)]\n\n\ndef one_hot_encode(Xd, Yd):\n\n return IN_MAP[Xd.astype('int8')], \\\n [OUT_MAP[Yd[t].astype('int8')] for t in range(1)]\n\n\ndef print_topl_statistics(y_true, y_pred):\n # Prints the following information: top-kL statistics for k=0.5,1,2,4,\n # auprc, thresholds for k=0.5,1,2,4, number of true splice sites.\n\n idx_true = np.nonzero(y_true == 1)[0]\n argsorted_y_pred = np.argsort(y_pred)\n sorted_y_pred = np.sort(y_pred)\n\n topkl_accuracy = []\n threshold = []\n\n for top_length in [0.5, 1, 2, 4]:\n\n idx_pred = argsorted_y_pred[-int(top_length*len(idx_true)):]\n\n topkl_accuracy += [np.size(np.intersect1d(idx_true, idx_pred)) \\\n / float(min(len(idx_pred), len(idx_true)))]\n threshold += [sorted_y_pred[-int(top_length*len(idx_true))]]\n\n auprc = average_precision_score(y_true, y_pred)\n\n print (\"%.4f\\t\\033[91m%.4f\\t\\033[0m%.4f\\t%.4f\\t\\033[94m%.4f\\t\\033[0m\"\n + \"%.4f\\t%.4f\\t%.4f\\t%.4f\\t%d\") % (\n topkl_accuracy[0], topkl_accuracy[1], topkl_accuracy[2],\n topkl_accuracy[3], auprc, threshold[0], threshold[1],\n threshold[2], threshold[3], len(idx_true))\n","sub_path":"GTEx/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"498554639","text":"from .helpers import unpack, snake_case, del_by_value, del_keys, rename_keys\n\n\"\"\"\n???\n'PassiveFunctions': {\n 'NewFunctionPublic': []\n }\n\n\"\"\"\n\n\nclass License:\n def __init__(self, l):\n self.status, self.value = unpack(l, 'License')\n\n self._map()\n\n def _map(self):\n _del_keys = ['comment', 'person_date_of_birth', 'person_first_name', 'person_gender_id', 'person_last_name']\n keys = [('id', 'license_id'),\n ('period_from_date', 'license_period_from_date'),\n ('period_function_type_count', 'license_period_function_type_count'),\n ('period_id', 'license_period_id'),\n ('period_name', 'license_period_name'),\n ('period_owner_account_id', 'license_period_owner_account_id'),\n ('period_owner_contact_id', 'license_period_owner_contact_id'),\n ('period_owner_org_id', 'license_period_owner_org_id'),\n ('period_owner_org_name', 'license_period_owner_org_name'),\n ('period_to_date', 'license_period_to_date'),\n ('status_date', 'license_status_date'),\n ('status_id', 'license_status_id'),\n ('status_text', 'license_status_text'),\n ('type_id', 'license_type_id'),\n ('type_name', 'license_type_name'),\n ('type_price', 'license_type_price'),\n ]\n self.value = self.value['License']\n self.value = snake_case(self.value)\n self.value = del_by_value(self.value, None)\n self.value = del_keys(self.value, _del_keys)\n self.value = rename_keys(self.value, keys)\n","sub_path":"nif_api/typings/license.py","file_name":"license.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"345850889","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nrequires = [\n 'click>=7.0',\n 'python-twitter>=3.5',\n 'gevent>=1.4.0',\n 'python-dateutil>=2.7.5',\n 'pytimeparse>=1.1.8',\n 'colorama>=0.4.1',\n 'Pygments>=2.3.1',\n 'sparklines>=0.4.2',\n 'numpy>=1.16.2',\n]\n\ntest_requires = [\n 'pytest-cov',\n 'pytest>=3.6.1',\n 'pytest-mock>=1.10.0',\n 'pytest-vcr>=1.0.1',\n]\n\nsetuptools.setup(\n name=\"tweet-delete\",\n version=\"0.1.14\",\n author=\"Brenden Matthews\",\n author_email=\"brenden@diddyinc.com\",\n description=\"Self-destructing Tweet tool\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/brndnmtthws/tweet-delete\",\n packages=setuptools.find_packages(),\n include_package_data=True,\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: Public Domain\",\n \"Operating System :: OS Independent\",\n ),\n entry_points={\n 'console_scripts':\n ['tweet-delete=tweet_delete.entry:cli'],\n },\n python_requires=\">=3.5\",\n install_requires=requires,\n tests_require=test_requires,\n extras_require={\n 'test': test_requires,\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"87756652","text":"from utils import rand_in_range, rand_un\nfrom tiles3 import *\nimport numpy as np\nimport pickle\nimport random\nimport time\n\nmemorySize = 4096\nnum_tilings = 8\nshape_of_tilings = 8 * 8\nalpha = 0.1 / 8\nl = 0.9\nepsilon = 0.0\ninitial_weights = None\ngamma = 1.0\nlast_state = None\nlast_action = None\nlast_index = None\nHash_Table = None\nTrace = None\nep = None\nplot = None\n\ndef agent_init():\n global initial_weights, Hash_Table, ep\n initial_weights = np.random.rand(memorySize) * (-0.001)\n Hash_Table = IHT(memorySize)\n ep = 0\n\n\ndef agent_start(state):\n global last_state, last_action, last_index, Trace\n last_state = state\n values = np.zeros(3)\n saved_vector = []\n for i in xrange(3):\n En = tiles(Hash_Table,num_tilings,[state[0]*15.0, state[1]*15.0], [i])\n vector = En\n saved_vector.append(vector)\n \n binary = np.zeros_like(initial_weights)\n binary[vector] = 1\n values[i] = np.dot(initial_weights, binary)\n action = np.argmax(values)\n if random.random() < epsilon:\n action = random.randint(0, 2)\n last_action = action\n Trace = np.zeros_like(initial_weights)\n return last_action\n\n\ndef agent_step(reward, state): \n global last_state, last_action, last_index, initial_weights, Trace\n delta = reward\n delta -= np.sum(initial_weights[last_index])\n Trace[last_index] = 1\n \n values = np.zeros(3)\n saved_vector = []\n for i in xrange(3):\n \n En = tiles(Hash_Table, num_tilings,[state[0]*15.0, state[1]*15.0],[i])\n vector = En\n saved_vector.append(vector)\n \n binary = np.zeros_like(initial_weights)\n binary[vector] = 1\n values[i] = np.dot(initial_weights, binary)\n action = np.argmax(values)\n if random.random() < epsilon:\n action = random.randint(0, 2)\n\n delta += gamma * np.sum(initial_weights[saved_vector[action]])\n initial_weights += alpha * delta * Trace\n Trace = gamma * l * Trace\n last_state = state\n last_action = action\n last_index = saved_vector[action]\n return last_action\n\n\ndef agent_end(reward):\n global ep, initial_weights, Trace\n \n delta = reward\n delta -= np.sum(initial_weights[last_index])\n \n Trace[last_index] = 1\n initial_weights += alpha * delta * Trace\n \n ep += 1\n if ep == 999:\n cost_to_go = np.zeros([50, 50])\n for i in xrange(50):\n for j in xrange(50):\n values = []\n for a in xrange(3):\n X = -1.2 + (i * 1.7 / 50.0)\n Y = -0.07 + (j * 0.14 / 50.0)\n \n En = tiles(Hash_Table, num_tilings,[X*15.0, Y*15.0],[a])\n \n new = np.zeros_like(initial_weights)\n new[En] = 1\n values.append(-np.dot(initial_weights, new))\n cost_to_go[i, j] = np.max(np.array(values))\n np.save('cost_to_go', cost_to_go)\n return\n\n\ndef agent_cleanup():\n \"\"\"\n This function is not used\n \"\"\"\n # clean up\n return\n\n\ndef agent_message(in_message):\n if in_message[0] == 'n':\n n = in_message[1]\n elif in_message[0] == 'alpha':\n alpha = in_message[1]","sub_path":"A/A7/A7_code/A7/A7/sarsa_lambda_agent1.py","file_name":"sarsa_lambda_agent1.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"341051853","text":"\"\"\"\nTITLE : Random forest applied to the wine dataset with pca\nAUTHOR : Salman Shah\nDATE : Wed May 23 19:19:20 2019\n\nImplemented for the sake of experimentation \n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn.datasets import load_wine\n\n''' Setting up a dataframe to have a reference while coding '''\nfile = load_wine()\ncolumn_names = file.feature_names\ntarget = file.target\ndata = file.data\ndf1 = pd.DataFrame(data, columns=column_names)\ndf2 = pd.DataFrame(target, columns=['target'])\ndataset = pd.concat([df1,df2], axis=1) # use this for reference\n\n# Feature scaling and applying PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nsc = StandardScaler()\npca = PCA(n_components=2)\nX = pca.fit_transform(sc.fit_transform(file.data))\ny_original = target\ny_one_hot = pd.get_dummies(df2['target'], drop_first=True) # one hot encoded y\n\n# Splitting the dataset into training and test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y_one_hot, test_size=0.2, random_state=0)\n\n# Building a Random forest\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators=100,\n criterion=\"gini\",\n max_depth=3,\n random_state=0)\n\n# Fitting and predicting\nclassifier.fit(X_train, y_train)\ny_pred = classifier.predict(X_test)\n\n# undoing some of the one-hot-encoding\ny_pred_flat = [0 if (sum(y_pred[i])==0) else np.argmax(y_pred[i]) + 1 for i in range(len(y_pred))]\ny_test_flat = [0 if (sum(y_test.values[i])==0) else np.argmax(y_test.values[i]) + 1 for i in range(len(y_test.values))]\ny_train_flat = [0 if (sum(y_train.values[i])==0) else np.argmax(y_train.values[i]) + 1 for i in range(len(y_train.values))]\n\n# Confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test_flat, y_pred_flat)\n\n''' Plotting ''' \n# Defining some parameters and a custom colormap\nplot_colors = 'bgr'\nplot_step = 0.02\nclass_names = '123'\nblue = np.array([0/256,150/256,255/256,1])\nred = np.array([255/256,85/256,85/256,1])\ngreen = np.array([85/256,230/256,85/256,1])\ncustom_cmap = ListedColormap([blue, green, red])\n\n# building a grid of predictions\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nxx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),\n np.arange(y_min, y_max, plot_step))\ninput_grid = np.c_[xx.ravel(), yy.ravel()]\nZ = classifier.predict(input_grid)\nZ = [0 if (sum(Z[i])==0) else np.argmax(Z[i]) + 1 for i in range(Z.shape[0])]\nZ = np.array(Z).reshape(xx.shape)\n\n# Plotting the boundary regions\nfig = plt.figure(figsize=(10,5))\nax = plt.subplot(121)\ncs = plt.contourf(xx, yy, Z, cmap=custom_cmap)\n\n# plotting the training set\nfor i, n, c in zip(range(3), class_names, plot_colors):\n train_idx = np.where(np.array(y_train_flat)==i)\n test_idx = np.where(np.array(y_test_flat)==i)\n ax.scatter(X_train[train_idx, 0], X_train[train_idx, 1],\n c=c, s=40,\n edgecolor='k',\n marker='o',\n label=\"Train C%s\" % n)\n ax.scatter(X_test[test_idx, 0], X_test[test_idx, 1],\n c=c, s=40, \n edgecolor='k',\n marker='v',\n label=\"Test C%s\" % n)\nax.legend(loc='upper right', fontsize='x-small')\nplt.title(\"Random Forest on Wine Dataset with PCA\")\nax.axis('tight')\nax.tick_params(axis='both', \n labelbottom=False, \n labelleft=False,\n bottom=False,\n left=False)\n\n# plotting the confusion matrix\nimport seaborn as sn\ndf_cm = pd.DataFrame(cm, \n columns=['Predicted C1', 'Predicted C2', 'Predicted C3'], \n index=['Actual C1', 'Actual C2', 'Actual C3'])\nax2 = plt.subplot(122)\nsn.heatmap(df_cm, annot=True)\nplt.title(\"Confusion Matrix on Test Set\")\nplt.show()","sub_path":"Wine_dataset_classification_with_PCA/random-forest.py","file_name":"random-forest.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"212310774","text":"import sys\n\nsys.stdin = open('input.txt')\n\n\ndef hmany(target, text):\n target = set(target)\n result_dict ={}\n for i in target:\n result_dict[i]=0\n for j in text:\n if i ==j:\n result_dict[i]+=1\n return max(result_dict.values())\n\n\n\n\n\ntotal_tc=int(input())\n\nfor tc in range (1, total_tc+1):\n target = input()\n text = input()\n print('#%d %d'%(tc, hmany(target, text)))","sub_path":"Algorithm/4865 글자수.py","file_name":"4865 글자수.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524598756","text":"from django.db.models import Max, Min, Count\nfrom browse.models import Histone, Variant, OldStyleVariant, Sequence, Score\nimport browse\nfrom djangophylocore.models import Taxonomy\nfrom django.db.models import Q\n\nfrom django.shortcuts import redirect\nfrom django.http import JsonResponse\n\nfrom collections import Counter\n\nimport django_filters\nfrom itertools import groupby\n\ndef tax_sub_search(value):\n \"\"\"\n \"\"\"\n ids = set()\n value = value.strip()\n \n if not format_query.current_query.startswith(\"taxonomy\"):\n return list(ids)\n \n search_type = format_query.current_query[len(\"taxonomy\"):]\n if search_type.endswith(\"iin\"):\n search_type = \"__iexact\"\n elif search_type.endswith(\"in\"):\n search_type = \"__exact\"\n queryName = {\"name{}\".format(search_type):value.lower()}\n try:\n queryID = {\"id{}\".format(search_type):int(value)}\n except ValueError:\n queryID = {}\n query = Q(**queryName)|Q(**queryID)\n \n taxons = []\n for taxon in Taxonomy.objects.filter(query):\n taxons.append(taxon)\n if taxon.type_name != \"scientific name\":\n #Convert homonym into real taxon\n taxon = taxon.get_scientific_names()[0]\n ids.add(taxon.id)\n children = set(taxon.children.values_list(\"id\", flat=True).filter(rank=2))\n ids |= children\n\n format_query.current_query = \"taxonomy__in\"\n \n return list(ids)\n\ndef variant_sub_search(value):\n ids = set()\n\n if not format_query.current_query.startswith(\"variant__id\"):\n return []\n\n try:\n #Search for current variant names or old variant names\n search_type = format_query.current_query[len(\"variant__id\"):]\n queryCurrent = {\"id{}\".format(search_type):value}\n queryOld = {\"old_names__name{}\".format(search_type):value}\n query = Q(**queryCurrent)|Q(**queryOld)\n\n variant = Variant.objects.filter(query)\n if len(variant) > 0:\n format_query.current_query = \"variant__id__in\"\n return variant.values_list(\"id\", flat=True)\n else:\n return variant.first().id\n except Variant.DoesNotExist:\n #Search new nomencalture with gene and splice isoform\n for histone in Histone.objects.all():\n for variant in histone.variants.all():\n if value.startswith(variant.id):\n branch_points = value[len(variant.id):].split(\".\")\n sequence_query = [(\"variant__id\", variant.id)]\n for branch_point in branch_points:\n if branch_point.startswith(\"s\"):\n key = \"splice\"\n branch_point = part[1:]\n else:\n key = \"gene\"\n try:\n branch_point = int(branch_point)\n sequence_query.append((key, branch_point))\n except ValueError:\n pass\n format_query.multiple = True\n return sequence_query\n \n \n else:\n \n \n variants = Variant.objects.filter(query).values_list(\"id\", flat=True)\n \n if len(variants) > 0:\n format_query.current_query = \"variant__id__in\"\n return list(variants)\n else:\n return []\n\n#Fields that are allowed: each row contains:\n# POST name, django model paramter, POST name for search type, input type (must be in seach_types)\nallowable_fields = [\n (\"id_id\", \"id\", \"id_id_search_type\", str),\n (\"id_core_histone\", \"variant__core_type__id\", \"id_core_type_search_type\", str),\n (\"id_variant\", \"variant__id\", \"id_variant_search_type\", variant_sub_search),\n (\"id_gene\", \"gene\", \"id_gene_search_type\", int),\n (\"id_splice\",\"splice\", \"id_splice_search_type\", int),\n (\"id_header\", \"header\", \"id_header_search_type\", str),\n (\"id_taxonomy\", \"taxonomy\", \"id_taxonomy_search_type\", tax_sub_search),\n (\"id_evalue\", \"evalue\", \"id_evalue_search_type\", float),\n (\"id_score\", \"score\", \"id_score_search_type\", float),\n #(\"show_lower_scoring_models\", None, None, (\"\"))\n]\n\nsearch_types = {}\nsearch_types[str] = {\n \"is\": \"__exact\",\n \"is (case-insesitive)\": \"__iexact\",\n \"contains\": \"__contains\",\n \"contains (case-insesitive)\": \"__icontains\",\n \"starts with\": \"__startswith\",\n \"starts with (case-insesitive)\": \"__istartswith\",\n \"ends with\": \"__endswith\",\n \"ends with (case-insesitive)\": \"__iendswith\",\n \"in (comma separated)\": \"__in\",\n \"in (comma separated, case-insensitive)\": \"__iin\"\n}\nsearch_types[int] = {\n \">\": \"__gt\",\n \">=\": \"__gte\",\n \"is\": \"\",\n \"<\": \"__lt\",\n \"<=\": \"__lte\",\n \"range (dash separated)\": \"__range\",\n \"in (comma separated)\": \"__in\",\n}\nsearch_types[float] = search_types[int]\nsearch_types[\"text\"] = search_types[str]\nsearch_types[\"int\"] = search_types[int]\n\nclass HistoneSearch(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, request, parameters, reset=False, navbar=False):\n \"\"\"\n \"\"\"\n assert isinstance(parameters, dict)\n\n self.errors = Counter()\n self.navbar = navbar\n self.request = request\n self.sanitized = False\n self.query_set = None\n self.redirect = None\n self.query = {}\n self.sort = {}\n self.count = 0\n\n #if reset:\n # HistoneSearch.reset(request)\n\n if \"search\" in parameters:\n parameters.update(self.simple_search(parameters[\"search\"]))\n\n if self.redirect:\n return\n\n self.sanitize_parameters(parameters, reset)\n self.create_queryset(reset)\n\n # @classmethod\n # def reset(cls, request):\n # \"\"\"Clears search from session\"\"\"\n # try:\n # del request.session[\"query\"]\n # del request.session[\"sort\"]\n # except KeyError:\n # pass\n\n @classmethod\n def all(cls, request):\n return cls(request, {}, reset=True)\n\n def sanitize_parameters(self, parameters, reset=False):\n \"\"\"\n \"\"\"\n self.query = {field:parameters[field] for fields in allowable_fields \\\n for field in (fields[0], fields[2]) if field in parameters}\n \n sort_parameters = {\"limit\": 10, \"offset\":0, \"sort\":\"evalue\", \"order\":\"asc\"}\n sort_query = {p:parameters.get(p, v) for p, v in sort_parameters.iteritems()}\n\n self.sort = sort_query\n\n #if not reset:\n #raise RuntimeError(str(self.request.session[\"query\"]))\n\n self.sanitized = True\n\n def create_queryset(self, reset=False):\n if not self.sanitized:\n raise RuntimeError(\"Parameters must be sanitized\")\n\n parameters = self.query\n \n query = format_query()\n\n added = []\n for form, field, search_type, convert in allowable_fields:\n value = None\n if form in parameters:\n added.append((field, search_type, parameters.get(form)))\n value = parameters.get(form)\n\n if not value: \n continue\n\n search_type = parameters.get(search_type, \"is\")\n \n query.format(field, search_type, value, convert) \n\n if query.has_errors():\n return False\n \n #assert 0, query\n\n self.query_set = Sequence.objects.filter(\n (~Q(variant__id=\"Unknown\") & Q(all_model_scores__used_for_classifiation=True)) | \\\n (Q(variant__id=\"Unknown\") & Q(all_model_scores__used_for_classifiation=False)) \\\n ).annotate(\n num_scores=Count(\"all_model_scores\"), \n score=Max(\"all_model_scores__score\"),\n evalue=Min(\"all_model_scores__evalue\")\n ).filter(**query)\n \n self.count = self.query_set.count()\n #if not reset:\n # raise RuntimeError(str(query))\n \n def sorted(self, unique=False):\n \"\"\"Sort the query set and paginate results.\n \"\"\"\n result = self.query_set\n \n sort_by = self.sort[\"sort\"]\n sort_order = \"-\" if self.sort[\"order\"] == \"desc\" else \"\"\n sort_key = \"{}{}\".format(sort_order, sort_by)\n result = result.order_by(sort_key)\n \n page_size = int(self.sort[\"limit\"])\n start = int(self.sort[\"offset\"])\n end = start+page_size\n\n result = result[start:end]\n\n if unique:\n used_taxa = {}\n for seq in result:\n if not seq.sequence in used_taxa:\n used_taxa[seq.sequence] = [seq.taxonomy.id]\n yield seq\n elif seq.sequence in used_taxa and not seq.taxonomy.id in used_taxa[seq.sequence]:\n used_taxa[seq.sequence].append(seq.taxonomy.id)\n yield seq\n else:\n pass\n \"\"\"#Old method using group by, might be faster, but doesn;t preserver order\n result = sorted(self.query_set, key=lambda s:s.sequence)\n for sequence, same_sequences in groupby(result, key=lambda s:s.sequence):\n used_taxa = []\n for seq in same_sequences:\n if seq.taxonomy.id not in used_taxa:\n used_taxa.append(seq.taxonomy.id)\n yield seq\n \"\"\"\n else:\n for seq in result:\n yield seq\n\n def __len__(self):\n return self.query_set.count()\n\n def count(self):\n return self.query_set.count()\n\n def get_dict(self, unique=False):\n sequences = self.sorted(unique=unique)\n result = [{\"id\":r.id, \"variant\":r.variant_id, \"gene\":r.gene, \"splice\":r.splice, \"taxonomy\":r.taxonomy.name.capitalize(), \"score\":r.score, \"evalue\":r.evalue, \"header\":r.header[:80]} for r in sequences]\n return {\"total\":self.count, \"rows\":result}\n\n def simple_search(self, search_text):\n \"\"\"Search from simple text box in brand or sequence filter.\n \"\"\"\n parameters = {}\n #Search all fields\n try:\n #If search is just a single digit, try to match id\n #Other int values don't make sense to search like this\n value = int(search_text)\n sequence = self.query_set.filter(id=value)\n if len(sequence):\n parameters[\"id\"] = value\n parameters[\"id_search_type\"] = \"is\"\n return parameters\n except ValueError:\n pass\n\n #search core_type, variant, old variant names, header if doens't match variant or core_type, taxonomy\n try:\n core_type = Histone.objects.get(id=search_text)\n parameters[\"id_core_histone\"] = core_type.id\n parameters[\"id_core_histone_search_type\"] = \"is\"\n if self.navbar:\n self.redirect = redirect(core_type)\n return parameters\n except Histone.DoesNotExist:\n pass\n \n try:\n\n variant = Variant.objects.get(id=search_text)\n parameters[\"id_variant\"] = variant.id\n parameters[\"id_variant_search_type\"] = \"is\"\n if self.navbar:\n self.redirect = redirect(variant)\n return parameters\n except Variant.DoesNotExist:\n pass\n \n try:\n #Searches H2A.Z.1.s1\n sequences = Sequence.objects.filter(full_variant_name=search_text)\n if sequences.count() > 0:\n parameters[\"id_id\"] = \",\".join(sequences.values_list(\"id\", flat=True))\n parameters[\"id_id_search_type\"] = \"in (comma separated, case-sensitive)\"\n return parameters\n except:\n pass\n\n try:\n variant = OldStyleVariant.objects.get(name=search_text).updated_variant\n parameters[\"id_variant\"] = variant.id\n parameters[\"id_variant_search_type\"] = \"is\"\n if self.navbar:\n self.redirct = redirect(variant)\n return parameters\n except OldStyleVariant.DoesNotExist:\n pass\n\n try:\n #Search species\n sequences = Taxonomy.objects.filter(name__icontains=search_text)\n if sequences.count() > 0:\n parameters[\"id_taxonomy\"] = search_text\n parameters[\"id_taxonomy_search_type\"] = \"contains (case-insesitive)\"\n return parameters\n except Taxonomy.DoesNotExist:\n pass\n\n try:\n taxon = Taxonomy.objects.filter(name=parameters[\"search\"])\n try:\n #Convert homonym into real taxon\n taxon = taxon.get_scientific_names()[0]\n except IndexError:\n #Already correct taxon\n pass\n taxa = taxon.children.filter(rank__name=\"species\").values_list(\"pk\")\n sequences = self.query_set.filter(taxonomy__in=taxa)\n if sequences.count() > 0:\n parameters[\"id_taxonomy\"] = search_text\n parameters[\"id_taxonomy_search_type\"] = \"contains (case-insesitive)\"\n return parameters\n except Taxonomy.DoesNotExist:\n pass\n \n headers = Sequence.objects.filter(header__icontains=search_text)\n\n if headers.count() > 0:\n parameters[\"id_header\"] = search_text\n parameters[\"id_header_search_type\"] = \"contains (case-insesitive)\"\n else:\n #Search sequence moetifs if everything else fails\n parameters[\"id_sequence\"] = search_text\n parameters[\"id_sequence_search_type\"] = \"contains (case-insesitive)\"\n\n return parameters\n\nclass format_query(dict):\n current_query = None\n multiple = False\n errors = Counter()\n def format(self, field, search_type, value, conv_type):\n #if allow and search_type not in allow:\n # format_query.errors[\"Invalid search type ({}) for field {}\".format(search_type, field)] += 1\n # return False, errors\n search_type = search_type.replace(\">\", \">\").replace(\"<\", \"<\")\n \n try:\n if conv_type.__class__.__name__ == \"function\":\n search_type = search_types[str][search_type]\n else:\n search_type = search_types[conv_type][search_type]\n except KeyError:\n format_query.errors[\"Invalid search type ({}; {}) for field {}\".format(search_type,conv_type,field)] += 1\n return False, self.errors\n\n\n format_query.current_query = \"{}{}\".format(field, search_type)\n\n try:\n if search_type.endswith(\"range\"):\n values = []\n if \"-\" in value:\n for v in value.split(\"-\"):\n values += conv_type(v)\n else:\n self.errors[\"Must include a dash if searching 'range'\"] += 1\n value = values\n elif search_type.endswith(\"in\"):\n values = []\n if \",\" in value:\n for v in value.split(\",\"):\n values += conv_type(v)\n else:\n self.errors[\"Must include a comma if searching 'in'\"] += 1\n value = values\n else:\n value = conv_type(value)\n\n except ValueError:\n format_query.errors[\"Must include correct character to seach {}\".format(field)] += 1\n \n if len(format_query.errors) > 0:\n return\n\n if format_query.multiple and isinstance(value, list):\n for field, search in value:\n self[field] = search\n else:\n self[format_query.current_query] = value\n format_query.current_query = None\n format_query.multiple = False\n\n def has_errors(self):\n return len(format_query.errors) > 0\n\n\n\n\n\n","sub_path":"browse/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":15920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"306808132","text":"__author__ = 'liangl2'\nfrom collections import deque\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n node_queue = deque([root])\n result = []\n\n while node_queue:\n i = 0\n level_nodes = []\n node_queue_len = len(node_queue)\n while i < node_queue_len:\n level_nodes.append(node_queue[i].val)\n if node_queue[i].left:\n node_queue.append(node_queue[i].left)\n if node_queue[i].right:\n node_queue.append(node_queue[i].right)\n\n i += 1\n while node_queue_len:\n node_queue.popleft()\n node_queue_len -= 1\n result.insert(0, level_nodes)\n return result\n\nroot = TreeNode(2)\nroot.left = TreeNode(1)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(5)\nroot.right.left = TreeNode(4)\nroot.right.right = TreeNode(6)\nroot.right.right.right = TreeNode(7)\n\ns = Solution()\nprint(s.levelOrderBottom(root))","sub_path":"Algorithms/leetcode/107_binary_tree_level_order_traversal_II.py","file_name":"107_binary_tree_level_order_traversal_II.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"3536250","text":"from datetime import datetime\nfrom flask import current_app, render_template, url_for, abort, request, \\\n flash, redirect, Response\nfrom flask.views import MethodView\nfrom flask_login import login_required, current_user\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy.orm.attributes import QueryableAttribute\nfrom shof.activity.models import Person\nfrom shof.activity.disclosure.models import DisclosureItem\nfrom ..base_type import ActivityForm\nfrom ..exporter import export\nfrom ..util import parse_sort\n\n\ndef get_person_choices(user, obj=None):\n \"\"\"Get the allowed choices for a person field on a form.\"\"\"\n people = [user.person]\n\n if current_user.required('admin'):\n people = current_app.db.session.query(Person).filter_by(f_shof=True)\n elif obj is not None:\n people = [obj.person]\n\n return sorted([(u.id, u.full_name) for u in people])\n\n\ndef get_order_by_criteria(qs, activity_type):\n order_by = []\n for order, field_name in parse_sort(qs):\n field = getattr(activity_type.model, field_name, None)\n\n # Is this a valid field that we can sort on?\n if field is None or not isinstance(field, QueryableAttribute):\n continue\n\n ascdesc = 'asc' if order else 'desc'\n order_by.append(getattr(field, ascdesc)())\n\n if order_by:\n return order_by\n\n return [activity_type.model.date.desc()]\n\nclass ActivityMethodView(MethodView):\n \"\"\"Base class for activity views.\"\"\"\n\n def __init__(self, type):\n self.type = type\n super().__init__()\n\n def dispatch_request(self, *args, **kwargs):\n if kwargs.get('new'):\n return self.new()\n\n if kwargs.get('feed'):\n return self.feed()\n\n return super().dispatch_request(*args, **kwargs)\n\n def get(self, activity_id=None):\n if activity_id is None:\n return self.list()\n else:\n return self.item(activity_id)\n\n def post(self, activity_id=None):\n return self.get(activity_id)\n\n def new(self):\n raise NotImplementedError\n\n def list(self):\n raise NotImplementedError\n\n def item(self, id):\n raise NotImplementedError\n\n\nclass ActivityView(ActivityMethodView):\n \"\"\"List, show/edit and create views for an activity.\"\"\"\n def new(self):\n form = self.get_form_class()()\n form.person_id.choices = get_person_choices(current_user)\n session = current_app.db.session\n\n if form.validate_on_submit():\n obj = self.type.model()\n obj.type = self.type.name\n obj.person_id = form.person_id.data\n\n form.populate_obj(obj)\n session.add(obj)\n session.commit()\n flash(\"Created '{}'\".format(obj), 'success')\n\n view_name = '.{}-item'.format(self.type.name)\n return redirect(url_for(view_name, activity_id=obj.id))\n\n data = dict(\n form=form,\n type=self.type\n )\n return render_template('activities/new.jade', **data)\n\n def item(self, id):\n session = current_app.db.session\n obj = session.query(self.type.model).filter_by(id=id).first()\n if not obj:\n abort(404)\n\n # Delete object\n if request.form.get('delete', None) is not None:\n session.delete(obj)\n session.commit()\n flash('Deleted \"{}\"'.format(obj), 'warning')\n return redirect(url_for('.{}'.format(self.type.name)))\n\n form = self.get_form_class()(obj=obj)\n form.person_id.choices = get_person_choices(current_user, obj)\n\n if form.validate_on_submit():\n form.populate_obj(obj)\n obj.person_id = form.person_id.data\n\n session.add(obj)\n session.commit()\n flash('Updated \"{}\"'.format(obj), 'success')\n return redirect(url_for('.{}-item'.format(self.type.name),\n activity_id=id))\n\n disclosure = None\n if self.type.model.public_disclosure:\n disclosure = session.query(DisclosureItem).\\\n filter_by(activity_id=id).first()\n\n data = dict(\n obj=obj,\n type=self.type,\n form=form,\n disclosure=disclosure\n )\n templates = [\n 'activities/item_{}.jade'.format(self.type.name),\n 'activities/item.jade']\n\n return render_template(templates, **data)\n\n def list(self):\n query = current_app.db.session.query\n order_by = get_order_by_criteria(request.args.get('sort', ''), self.type)\n\n results = query(self.type.model).\\\n options(joinedload(self.type.model.person)).\\\n order_by(*order_by)\n\n data = dict(results=results, type=self.type)\n\n format = request.args.get('format', '')\n if format == 'xlsx':\n filename = \"activities-{}-list.xlsx\".format(self.type.name)\n return export(filename, [(self.type.name, results)])\n \n return render_template('activities/list.jade', **data)\n\n def feed(self):\n query = current_app.db.session.query\n results = query(self.type.model).\\\n options(joinedload(self.type.model.person)).\\\n order_by(self.type.model.date.desc())\n\n # UGLY\n sse = request.args.get('sse', '')\n if sse and self.type.name == 'publication':\n results = results.filter_by(f_sse=True)\n\n updated = datetime.utcnow().replace(microsecond=0)\n\n data = dict(\n results=results,\n type=self.type,\n feed_url=url_for('.{}-feed'.format(self.type.name), _external=True),\n updated=updated\n )\n\n return Response(render_template([\n 'activities/feed/list_{}.jade'.format(self.type.name),\n 'activities/feed/list.jade',\n ], **data), mimetype='application/atom+xml')\n\n def get_form_class(self):\n \"\"\"Gets a ModelForm for editing this activity.\n\n Constructs a class dynamically, if there is no good one for\n this activity.\"\"\"\n form_class_name = \"{}Form\".format(self.type.model.__name__)\n form_class = getattr(self.type, form_class_name, None)\n activity_model = self.type.model\n\n if not form_class:\n class AutomaticActivityForm(ActivityForm):\n class Meta:\n model = activity_model\n\n form_class = AutomaticActivityForm\n\n return form_class\n\ndef register_activity_view(parent, type):\n \"\"\"Register an activity view for type on parent.\"\"\"\n view_func = ActivityView.as_view(type.name, type=type)\n url = '/{}/'.format(type.name)\n\n parent.add_url_rule(url, type.name, view_func=login_required(view_func), methods=['GET'])\n parent.add_url_rule(url + '', type.name + '-item',\n view_func=login_required(view_func), methods=['GET', 'POST'])\n\n parent.add_url_rule(\n url + 'feed', type.name + '-feed',\n view_func=view_func, methods=['GET'],\n defaults=dict(feed=True)\n )\n\n parent.add_url_rule(\n url + 'new', type.name + '-new',\n view_func=login_required(view_func), methods=['GET', 'POST'],\n defaults=dict(new=True)\n )\n","sub_path":"shof/activity/activities/views/activity.py","file_name":"activity.py","file_ext":"py","file_size_in_byte":7297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"104558466","text":"from flask import Flask, request, render_template\nfrom scrap import SIGAA\nimport time\nfrom initial_config import *\nfrom models import *\nimport numpy as np\nimport logging\n\n\nclass FlaskService(object):\n\n def __init__(self):\n pass\n\n def do_function(self):\n @APP.route('/', methods=[\"POST\"])\n def pesquisa_disciplina():\n if(request.form.get('pesquisa') == \"\"):\n return render_template('index.html', disciplinas='', turmas='')\n texto = \"\".join(['%', request.form.get('pesquisa').upper(), '%'])\n resultadoTurmas = []\n resultadoDisciplinas = []\n try:\n logging.info(\"Inicio try\")\n qtde = Disciplina.query.filter(Disciplina.nome.like(texto)).count()\n logging.info(str(qtde))\n if qtde > 0:\n resultado = Disciplina.query.filter(Disciplina.nome.like(texto)).order_by(Disciplina.nome.asc()).all()\n\n for item in resultado:\n resultadoDisciplinas.append([item.id, item.nome, item.curso])\n # print(\"Dados disciplinas\")\n listaTurmas = Turma.query.filter_by(idDisciplina=item.id).order_by(Turma.curso.asc(), Turma.turma.asc()).all()\n # print(\"Turmas pesquisadas\")\n for item2 in listaTurmas:\n # print(' '.join([item]))\n resultadoTurmas.append([item2.idDisciplina, item2.turma, item2.docente, item2.horario])\n # print(\"Lista de turmas criadas\")\n # print(resultadoTurmas)\n # resultadoTurmas = Turma.query.filter_by(idDisciplina=resultado.id).all()\n # resultado = Disciplina.query.filter_by(nome='ECOI14.1 - Banco de Dados').all()\n # resultado = (str(disciplina.nome) for disciplina in resultado)\n # return (str(disciplina.nome) for disciplina in resultado)\n return render_template('index.html', disciplinas=resultadoDisciplinas, turmas=resultadoTurmas)\n else:\n return render_template('index.html', disciplinas='0', turmas='')\n except:\n logging.warning(\"Pesquisa não rolou\")\n return render_template('index.html', disciplinas='1', turmas='')\n\n @APP.route('/', methods=[\"GET\"])\n def inicio():\n return render_template('index.html', disciplinas='', turmas='')\n\n @APP.route('/disciplinas')\n def visualiza_disciplinas_registradas():\n disciplinas = Disciplina.query.all()\n return render_template('lista_disciplinas.html', disciplinas=disciplinas)\n\n @APP.route('/registra_disciplinas', methods=['GET'])\n def formulario_registra_disciplinas():\n return render_template('registra_disciplinas.html')\n\n @APP.route('/registra_disciplinas', methods=['POST'])\n def registra_disciplinas():\n # siglaCurso = request.form.get('siglaCurso')\n cursos = ['EAM', 'EMO', 'ECO', 'ECA',\n 'EMT', 'EPR', 'ESS', 'EEL', 'EME']\n ano = request.form.get('ano')\n semestre = request.form.get('semestre')\n for siglaCurso in cursos:\n x, y = SIGAA.retorna_turmas(siglaCurso, ano, semestre)\n d = SIGAA.format(x, y)\n for item, info in d.items():\n disciplina = Disciplina(\n item.upper(), 'Campus Itabira', siglaCurso)\n DB.session.add(disciplina)\n DB.session.commit()\n DB.session.refresh(disciplina)\n for i in np.arange(0, len(info), 8):\n turma = Turma(disciplina.id, info[i], info[i + 1], info[i + 2], info[i + 3], info[i + 4],\n info[i + 5], info[i + 6], info[i + 7], siglaCurso)\n DB.session.add(turma)\n # DB.session.commit()\n # print(': '.join([str(i % 8), str(elemento)]))\n print(' '.join(['Curso processado:', siglaCurso]))\n DB.session.commit()\n time.sleep(1)\n # for item in d:\n # turma = Turma(item, 'Campus Itabira')\n # DB.session.add(disciplina)\n # DB.session.commit()\n # name = request.form.get('name')\n # email = request.form.get('email')\n\n # guest = Guest(name, email)\n # DB.session.add(guest)\n # DB.session.commit()\n\n # return render_template('guest_confirmation.html', name=name, email=email)\n return render_template('confirma_registro.html')\n\n if __name__ == '__main__':\n app.run(debug=True)\n\n\np = FlaskService()\np.do_function()\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"444892353","text":"# Homework 1\n# Problem 3 solution\n#\n# Do not distribute.\n#\n\nwhile True:\n amount = float(input('Enter amount:'))\n\n if amount < 0:\n print(\"Invalid input.\")\n else:\n # convert to pennies:\n amount_cents = int(amount * 100)\n\n coins_total_amount = 0\n coins_total_count = 0\n cents_left = amount_cents\n\n quarters = cents_left // 25\n cents_left -= quarters * 25\n coins_total_count += quarters\n coins_total_amount += quarters * 25\n\n dimes = cents_left // 10\n cents_left -= dimes * 10\n coins_total_count += dimes\n coins_total_amount += dimes * 10\n\n pennies = cents_left\n cents_left -= pennies\n coins_total_count += pennies\n coins_total_amount += pennies\n\n msg = \"$\" + str(amount) + \" makes \" + str(quarters) + \" quarters, \" + \\\n str(dimes) + \" dimes, and \" + str(pennies) + \" pennies (\" + \\\n str(coins_total_count) + \" coins), total amount in coins: $\" + \\\n str(coins_total_amount / 100) + \".\"\n print(msg)\n\n \n\n \n","sub_path":"Module 1/python-h1-solutions/p3-simple.py","file_name":"p3-simple.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"419189037","text":"#! usr/bin/python3\n#--encode is \"utf-8\"---\n\n\ndef sheel(arr, start, inter):\n i = start + inter\n while i < len(arr):\n temp = arr[i]\n j = i\n while j >= inter:\n if temp < arr[j - inter]:\n arr[j] = arr[j - inter]\n else : break\n j -= inter\n if i != j:\n arr[j] = temp\n i += inter\n\ndef main():\n a = [9,0,8,7,6,5,4,3,2,1]\n gap = 3 \n while gap > 2:\n j = 0\n while j < gap:\n sheel(a, j, gap)\n j += 1\n gap = int(gap/2)\n sheel(a,0,1)\n print(a)\n\nif __name__ == \"__main__\":\n main()","sub_path":"shellsort.py","file_name":"shellsort.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"61084721","text":"#!/usr/bin/python3\n\"\"\"Obtains info from json placeholder api and returns it in CSV format\"\"\"\nimport csv\nimport requests\nimport sys\n\n\ndef getInformation(employeeid):\n \"\"\"Returns information based on ID\"\"\"\n url = \"https://jsonplaceholder.typicode.com/\"\n endpoint = url + 'users/{}'.format(employeeid)\n employee = requests.get(endpoint).json()\n taskendpoint = url + 'TODOs?userId={}'.format(employee.get('id'))\n tasks = requests.get(taskendpoint).json()\n data = {\"employee\": employee, \"tasks\": tasks}\n with open('{}.csv'.format(sys.argv[1]), 'w') as f:\n w = csv.writer(f, quoting=csv.QUOTE_ALL)\n _username = data['employee']['username']\n _id = data['employee']['id']\n for task in data['tasks']:\n w.writerow([_id, _username, task['completed'], task['title']])\n\n\nif __name__ == '__main__':\n getInformation(sys.argv[1])\n","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"19448014","text":"\"\"\"Wrapper for using the Scikit-Learn API with Keras models.\n\"\"\"\nimport inspect\nimport os\nimport warnings\n\nfrom collections import defaultdict\nfrom typing import Any, Dict\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom sklearn.base import BaseEstimator\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.metrics import accuracy_score as sklearn_accuracy_score\nfrom sklearn.metrics import r2_score as sklearn_r2_score\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.utils.multiclass import type_of_target\nfrom sklearn.utils.validation import _check_sample_weight, check_array, check_X_y\nfrom tensorflow.keras import losses as losses_module\nfrom tensorflow.keras import metrics as metrics_module\nfrom tensorflow.keras import optimizers as optimizers_module\nfrom tensorflow.keras.models import Model\nfrom tensorflow.python.keras.losses import is_categorical_crossentropy\nfrom tensorflow.python.keras.utils.generic_utils import register_keras_serializable\n\nfrom ._utils import (\n LabelDimensionTransformer,\n TFRandomState,\n _class_from_strings,\n _windows_upcast_ints,\n accepts_kwargs,\n get_metric_full_name,\n has_param,\n make_model_picklable,\n route_params,\n unflatten_params,\n)\n\n\nclass BaseWrapper(BaseEstimator):\n \"\"\"Base class for the Keras scikit-learn wrapper.\n\n Warning: This class should not be used directly.\n Use descendant classes instead.\n\n Arguments:\n build_fn: callable function or class instance\n Used to build the Keras Model. When called,\n must return a compiled instance of a Keras Model\n to be used by `fit`, `predict`, etc.\n random_state : int, RandomState instance, default=None\n Set the Tensorflow random number generators to a\n reproducible deterministic state using this seed.\n Pass an int for reproducible results across multiple\n function calls.\n For all other parameters see tf.keras.Model documentation.\n \"\"\"\n\n is_fitted_ = False\n\n _tags = {\n \"poor_score\": True,\n \"multioutput\": True,\n }\n\n _fit_kwargs = {\n # parameters destined to keras.Model.fit\n \"callbacks\",\n \"batch_size\",\n \"epochs\",\n \"verbose\",\n \"callbacks\",\n \"validation_split\",\n \"shuffle\",\n \"class_weight\",\n \"sample_weight\",\n \"initial_epoch\",\n \"validation_steps\",\n \"validation_batch_size\",\n \"validation_freq\",\n }\n\n _predict_kwargs = {\n # parameters destined to keras.Model.predict\n \"batch_size\",\n \"verbose\",\n \"callbacks\",\n \"steps\",\n }\n\n _compile_kwargs = {\n # parameters destined to keras.Model.compile\n \"optimizer\",\n \"loss\",\n \"metrics\",\n \"loss_weights\",\n \"weighted_metrics\",\n \"run_eagerly\",\n }\n\n _wrapper_params = {\n # parameters consumed by the wrappers themselves\n \"warm_start\",\n \"random_state\",\n }\n\n _meta = {\n # parameters created by wrappers within `fit`\n \"_random_state\",\n \"n_features_in_\",\n \"X_dtype_\",\n \"y_dtype_\",\n \"X_shape_\",\n \"y_shape_\",\n \"model_\",\n \"history_\",\n \"is_fitted_\",\n \"n_outputs_\",\n \"model_n_outputs_\",\n \"_user_params\",\n }\n\n _routing_prefixes = {\n \"model\",\n \"fit\",\n \"compile\",\n \"predict\",\n \"optimizer\",\n \"loss\",\n \"metrics\",\n }\n\n def __init__(\n self,\n model=None,\n *,\n build_fn=None, # for backwards compatibility\n warm_start=False,\n random_state=None,\n optimizer=\"rmsprop\",\n loss=None,\n metrics=None,\n batch_size=None,\n verbose=1,\n callbacks=None,\n validation_split=0.0,\n shuffle=True,\n run_eagerly=False,\n epochs=1,\n **kwargs,\n ):\n\n # ensure prebuilt model can be serialized\n if isinstance(model, Model):\n make_model_picklable(model)\n if isinstance(build_fn, Model):\n make_model_picklable(build_fn)\n\n # Parse hardcoded params\n self.model = model\n self.build_fn = build_fn\n self.warm_start = warm_start\n self.random_state = random_state\n self.optimizer = optimizer\n self.loss = loss\n self.metrics = metrics\n self.batch_size = batch_size\n self.verbose = verbose\n self.callbacks = callbacks\n self.validation_split = validation_split\n self.shuffle = shuffle\n self.run_eagerly = run_eagerly\n self.epochs = epochs\n\n # Unpack kwargs\n vars(self).update(**kwargs)\n\n # Save names of kwargs into set\n if kwargs:\n self._user_params = set(kwargs)\n\n @property\n def __name__(self):\n return self.__class__.__name__\n\n @property\n def _model_params(self):\n return {\n k[len(\"model__\") :]\n for k in self.get_params()\n if \"model__\" == k[: len(\"model__\")]\n or k in getattr(self, \"_user_params\", set())\n }\n\n def _check_model_param(self):\n \"\"\"Checks `model` and returns model building\n function to use.\n\n Raises:\n ValueError: if `self.model` is not valid.\n \"\"\"\n model = self.model\n build_fn = self.build_fn\n if model is None and build_fn is not None:\n model = build_fn\n warnings.warn(\n \"`build_fn` will be renamed to `model` in a future release,\"\n \" at which point use of `build_fn` will raise an Error instead.\"\n )\n if model is None:\n # no model, use this class' _keras_build_fn\n if not hasattr(self, \"_keras_build_fn\"):\n raise ValueError(\n \"If not using the `build_fn` param, \"\n \"you must implement `_keras_build_fn`\"\n )\n final_build_fn = self._keras_build_fn\n elif isinstance(model, Model):\n # pre-built Keras Model\n def final_build_fn():\n return model\n\n elif inspect.isfunction(model):\n if hasattr(self, \"_keras_build_fn\"):\n raise ValueError(\n \"This class cannot implement `_keras_build_fn` if\"\n \" using the `model` parameter\"\n )\n # a callable method/function\n final_build_fn = model\n else:\n raise TypeError(\n \"`model` must be a callable, a Keras Model instance or None\"\n )\n\n return final_build_fn\n\n def _get_compile_kwargs(self):\n \"\"\"Convert all __init__ params destined to\n `compile` into valid kwargs for `Model.compile` by parsing\n routed parameters and compiling optimizers, losses and metrics\n as needed.\n\n Returns\n -------\n dict\n Dictionary of kwargs for `Model.compile`.\n \"\"\"\n init_params = self.get_params()\n compile_kwargs = route_params(\n init_params, destination=\"compile\", pass_filter=self._compile_kwargs,\n )\n compile_kwargs[\"optimizer\"] = _class_from_strings(\n compile_kwargs[\"optimizer\"], optimizers_module.get\n )\n compile_kwargs[\"optimizer\"] = unflatten_params(\n items=compile_kwargs[\"optimizer\"],\n params=route_params(\n init_params, destination=\"optimizer\", pass_filter=set(), strict=True,\n ),\n )\n compile_kwargs[\"loss\"] = _class_from_strings(\n compile_kwargs[\"loss\"], losses_module.get\n )\n compile_kwargs[\"loss\"] = unflatten_params(\n items=compile_kwargs[\"loss\"],\n params=route_params(\n init_params, destination=\"loss\", pass_filter=set(), strict=False,\n ),\n )\n compile_kwargs[\"metrics\"] = _class_from_strings(\n compile_kwargs[\"metrics\"], metrics_module.get\n )\n compile_kwargs[\"metrics\"] = unflatten_params(\n items=compile_kwargs[\"metrics\"],\n params=route_params(\n init_params, destination=\"metrics\", pass_filter=set(), strict=False,\n ),\n )\n return compile_kwargs\n\n def _build_keras_model(self):\n \"\"\"Build the Keras model.\n\n This method will process all arguments and call the model building\n function with appropriate arguments.\n\n Returns:\n model : tensorflow.keras.Model\n Instantiated and compiled keras Model.\n \"\"\"\n # dynamically build model, i.e. final_build_fn builds a Keras model\n\n # determine what type of build_fn to use\n final_build_fn = self._check_model_param()\n\n # collect parameters\n params = self.get_params()\n build_params = route_params(\n params,\n destination=\"model\",\n pass_filter=getattr(self, \"_user_params\", set()),\n )\n compile_kwargs = None\n if has_param(final_build_fn, \"meta\") or accepts_kwargs(final_build_fn):\n # build_fn accepts `meta`, add it\n meta = route_params(\n self.get_meta(), destination=None, pass_filter=self._meta,\n )\n build_params[\"meta\"] = meta\n if has_param(final_build_fn, \"compile_kwargs\") or accepts_kwargs(\n final_build_fn\n ):\n # build_fn accepts `compile_kwargs`, add it\n compile_kwargs = self._get_compile_kwargs()\n build_params[\"compile_kwargs\"] = compile_kwargs\n if has_param(final_build_fn, \"params\") or accepts_kwargs(final_build_fn):\n # build_fn accepts `params`, i.e. all of get_params()\n build_params[\"params\"] = self.get_params()\n\n # build model\n if self._random_state is not None:\n with TFRandomState(self._random_state):\n model = final_build_fn(**build_params)\n else:\n model = final_build_fn(**build_params)\n\n # make serializable\n make_model_picklable(model)\n\n # compile model if user gave us an un-compiled model\n if not (hasattr(model, \"loss\") and hasattr(model, \"optimizer\")):\n if compile_kwargs is None:\n compile_kwargs = self._get_compile_kwargs()\n model.compile(**compile_kwargs)\n\n if not getattr(model, \"loss\", None) or (\n isinstance(model.loss, list)\n and not any(callable(l) or isinstance(l, str) for l in model.loss)\n ):\n raise ValueError(\n \"No valid loss function found.\"\n \" You must provide a loss function to train.\"\n \"\\n\\nTo resolve this issue, do one of the following:\"\n \"\\n 1. Provide a loss function via the loss parameter.\"\n \"\\n 2. Compile your model with a loss function inside the\"\n \" model-building method.\"\n \"\\n\\nSee https://www.tensorflow.org/api_docs/python/tf/keras/losses\"\n \" for more information on Keras losses.\"\n )\n\n return model\n\n def _fit_keras_model(self, X, y, sample_weight, warm_start):\n \"\"\"Fits the Keras model.\n\n This method will process all arguments and call the Keras\n model's `fit` method with appropriate arguments.\n\n Arguments:\n X : array-like, shape `(n_samples, n_features)`\n Training samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`\n True labels for `X`.\n sample_weight : array-like of shape (n_samples,)\n Sample weights. The Keras Model must support this.\n warm_start : bool\n If ``warm_start`` is True, don't don't overwrite\n the ``history_`` attribute and append to it instead.\n Returns:\n self : object\n a reference to the instance that can be chain called\n (ex: instance.fit(X,y).transform(X) )\n Raises:\n ValueError : In case sample_weight != None and the Keras model's\n `fit` method does not support that parameter.\n \"\"\"\n if os.name == \"nt\":\n # see tensorflow/probability#886\n X = _windows_upcast_ints(X)\n y = _windows_upcast_ints(y)\n\n # collect parameters\n params = self.get_params()\n fit_args = route_params(params, destination=\"fit\", pass_filter=self._fit_kwargs)\n fit_args[\"sample_weight\"] = sample_weight\n\n if self._random_state is not None:\n with TFRandomState(self._random_state):\n hist = self.model_.fit(x=X, y=y, **fit_args)\n else:\n hist = self.model_.fit(x=X, y=y, **fit_args)\n\n if warm_start:\n if not hasattr(self, \"history_\"):\n self.history_ = defaultdict(list)\n self.history_ = {\n get_metric_full_name(k): self.history_[get_metric_full_name(k)]\n + hist.history[k]\n for k in hist.history.keys()\n }\n else:\n self.history_ = hist.history\n self.is_fitted_ = True\n\n # return self to allow fit_transform and such to work\n return self\n\n def _check_output_model_compatibility(self, y):\n \"\"\"Checks that the model output number and y shape match, reshape as needed.\n\n This is mainly in place to avoid cryptic TF errors.\n \"\"\"\n # check if this is a multi-output model\n if self.model_n_outputs_ != len(self.model_.outputs):\n raise RuntimeError(\n \"Detected an input of size \"\n \"{}, but {} has {} outputs\".format(\n (y[0].shape[0], len(y)), self.model_, len(self.model_.outputs),\n )\n )\n\n # tf v1 does not accept single item lists\n # tf v2 does\n # so go with what tf v1 accepts\n if len(y) == 1:\n y = y[0]\n else:\n y = tuple(np.squeeze(y_) for y_ in y)\n return y\n\n def _validate_data(self, X, y=None, reset=True):\n \"\"\"Validate input data and set or check the `n_features_in_` attribute.\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n The input samples.\n y : array-like of shape (n_samples,), default=None\n The targets. If None, `check_array` is called on `X` and\n `check_X_y` is called otherwise.\n reset : bool, default=True\n Whether to reset the `n_features_in_` attribute.\n If False, the input will be checked for consistency with data\n provided when reset was last True.\n\n Returns\n -------\n out : {ndarray, sparse matrix} or tuple of these\n The validated input. A tuple is returned if `y` is not None.\n \"\"\"\n\n def _check_array_dtype(arr):\n if not isinstance(arr, np.ndarray):\n return _check_array_dtype(np.asarray(arr))\n elif arr.dtype.kind != \"O\":\n return None # check_array won't do any casting with dtype=None\n else:\n # default to TFs backend float type\n # instead of float64 (sklearns default)\n return tf.keras.backend.floatx()\n\n if y is not None:\n X, y = check_X_y(\n X,\n y,\n allow_nd=True, # allow X to have more than 2 dimensions\n multi_output=True, # allow y to be 2D\n dtype=None,\n )\n y = check_array(\n y, ensure_2d=False, allow_nd=False, dtype=_check_array_dtype(y)\n )\n X = check_array(X, allow_nd=True, dtype=_check_array_dtype(X))\n\n n_features = X.shape[1]\n\n if reset:\n self.n_features_in_ = n_features\n else:\n if n_features != self.n_features_in_:\n raise ValueError(\n f\"X has {n_features} features, but this {self.__name__} \"\n f\"is expecting {self.n_features_in_} features as input.\"\n )\n if y is None:\n return X\n return X, y\n\n @staticmethod\n def preprocess_y(y):\n \"\"\"Handles manipulation of y inputs to fit or score.\n\n By default, this just makes sure y is 2D.\n\n Arguments:\n y : 1D or 2D numpy array\n\n Returns:\n y : numpy array of shape (n_samples, n_ouputs)\n extra_args : dictionary of output attributes, ex: n_outputs_\n \"\"\"\n\n extra_args = {\n \"y_dtype_\": y.dtype,\n \"y_shape_\": y.shape,\n }\n\n return y, extra_args\n\n @staticmethod\n def postprocess_y(y):\n \"\"\"Handles manipulation of predicted `y` values.\n\n By default, it joins lists of predictions for multi-ouput models\n into a single numpy array.\n Subclass and override this method to customize processing.\n\n Arguments:\n y : 2D numpy array or list of numpy arrays\n (the latter is for multi-ouput models)\n\n Returns:\n y : 2D numpy array with singular dimensions stripped\n or 1D numpy array\n extra_args : attributes of output `y`.\n \"\"\"\n y = np.column_stack(y)\n\n extra_args = dict()\n return np.squeeze(y), extra_args\n\n @staticmethod\n def preprocess_X(X):\n \"\"\"Handles manipulation of X before fitting.\n\n Subclass and override this method to process X, for example\n accommodate a multi-input model.\n\n Arguments:\n X : 2D numpy array\n\n Returns:\n X : unchanged 2D numpy array\n extra_args : attributes of output `y`.\n \"\"\"\n extra_args = {\n \"X_dtype_\": X.dtype,\n \"X_shape_\": X.shape,\n }\n return X, extra_args\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Constructs a new model with `build_fn` & fit the model to `(X, y)`.\n\n Arguments:\n X : array-like, shape `(n_samples, n_features)`\n Training samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`\n True labels for `X`.\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. The Keras Model must support this.\n Returns:\n self : object\n a reference to the instance that can be chain called\n (ex: instance.fit(X,y).transform(X) )\n Raises:\n ValueError : In case of invalid shape for `y` argument.\n \"\"\"\n return self._fit(\n X=X, y=y, sample_weight=sample_weight, warm_start=self.warm_start\n )\n\n def _fit(self, X, y, sample_weight=None, warm_start=False):\n \"\"\"Constructs a new model with `build_fn` & fit the model to `(X, y)`.\n\n Arguments:\n X : array-like, shape `(n_samples, n_features)`\n Training samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`\n True labels for `X`.\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. The Keras Model must support this.\n warm_start : bool, default False\n If ``warm_start`` is True, don't rebuild the model.\n Returns:\n self : object\n a reference to the instance that can be chain called\n (ex: instance.fit(X,y).transform(X) )\n Raises:\n ValueError : In case of invalid shape for `y` argument.\n \"\"\"\n # Handle random state\n if isinstance(self.random_state, np.random.RandomState):\n # Keras needs an integer\n # we sample an integer and use that as a seed\n # Given the same RandomState, the seed will always be\n # the same, thus giving reproducible results\n state = self.random_state.get_state()\n self._random_state = self.random_state.randint(low=1)\n self.random_state.set_state(state)\n else:\n # int or None\n self._random_state = self.random_state\n\n # Data checks\n if warm_start and not hasattr(self, \"n_features_in_\"):\n # Warm start requested but not fitted yet\n reset = True\n elif warm_start:\n # Already fitted and warm start requested\n reset = False\n else:\n # No warm start requested\n reset = True\n X, y = self._validate_data(X=X, y=y, reset=reset)\n\n # Save input dtype\n self.y_dtype_ = y.dtype\n\n if sample_weight is not None:\n sample_weight = _check_sample_weight(\n sample_weight, X, dtype=np.dtype(tf.keras.backend.floatx())\n )\n # Scikit-Learn expects a 0 in sample_weight to mean\n # \"ignore the sample\", but because of how Keras applies\n # sample_weight to the loss function, this doesn't\n # exactly work out (as in, sklearn estimator checks fail\n # because the predictions differ by a small margin).\n # To get around this, we manually delete these samples here\n zeros = sample_weight == 0\n if np.any(zeros):\n X = X[~zeros]\n y = y[~zeros]\n sample_weight = sample_weight[~zeros]\n if sample_weight.size == 0:\n # could check any of the arrays here, arbitrary choice\n # there will be no samples left! warn users\n raise RuntimeError(\n \"Cannot train because there are no samples\"\n \" left after deleting points with zero sample weight!\"\n )\n\n # pre process X, y\n X, extra_args = self.preprocess_X(X)\n # update self.X_dtype_, self.X_shape_\n for attr_name, attr_val in extra_args.items():\n setattr(self, attr_name, attr_val)\n y, extra_args = self.preprocess_y(y)\n # update self.classes_, self.n_outputs_, self.n_classes_ and\n # self.target_type_\n for attr_name, attr_val in extra_args.items():\n setattr(self, attr_name, attr_val)\n\n # build model\n if (not warm_start) or (not hasattr(self, \"model_\")):\n self.model_ = self._build_keras_model()\n\n y = self._check_output_model_compatibility(y)\n\n # fit model\n return self._fit_keras_model(\n X, y, sample_weight=sample_weight, warm_start=warm_start\n )\n\n def partial_fit(self, X, y, sample_weight=None):\n \"\"\"\n Partially fit a model.\n\n Arguments:\n X : array-like, shape `(n_samples, n_features)`\n Training samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`\n True labels for `X`.\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. The Keras Model must support this.\n\n Returns:\n self : object\n a reference to the instance that can be chain called\n (ex: instance.partial_fit(X, y).transform(X) )\n Raises:\n ValueError : In case of invalid shape for `y` argument.\n \"\"\"\n return self._fit(X, y, sample_weight=sample_weight, warm_start=True)\n\n def predict(self, X):\n \"\"\"Returns predictions for the given test data.\n\n Arguments:\n X: array-like, shape `(n_samples, n_features)`\n Test samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n\n Returns:\n preds: array-like, shape `(n_samples,)`\n Predictions.\n \"\"\"\n # check if fitted\n if not self.is_fitted_:\n raise NotFittedError(\n \"Estimator needs to be fit before `predict` \" \"can be called\"\n )\n\n # basic input checks\n X = self._validate_data(X=X, y=None, reset=False)\n\n # pre process X\n X, _ = self.preprocess_X(X)\n\n # filter kwargs and get attributes for predict\n params = self.get_params()\n pred_args = route_params(\n params, destination=\"predict\", pass_filter=self._predict_kwargs\n )\n\n # predict with Keras model\n y_pred = self.model_.predict(X, **pred_args)\n\n # post process y\n y, _ = self.postprocess_y(y_pred)\n return y\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Returns the mean accuracy on the given test data and labels.\n\n Arguments:\n X: array-like, shape `(n_samples, n_features)`\n Test samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y: array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`\n True labels for `X`.\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. The Keras Model must support this.\n\n Returns:\n score: float\n Mean accuracy of predictions on `X` wrt. `y`.\n \"\"\"\n # validate sample weights\n if sample_weight is not None:\n sample_weight = _check_sample_weight(sample_weight, X)\n\n # validate y\n y = check_array(y, ensure_2d=False)\n\n # compute Keras model score\n y_pred = self.predict(X)\n\n # filter kwargs and get attributes for score\n params = self.get_params()\n score_args = route_params(params, destination=\"score\", pass_filter=set())\n\n return self.scorer(y, y_pred, sample_weight=sample_weight, **score_args)\n\n def get_meta(self) -> Dict[str, Any]:\n \"\"\"Get meta parameters (parameters created by fit, like\n n_features_in_ or target_type_).\n\n Returns\n -------\n Dict[str, Any]\n Dictionary of meta parameters\n \"\"\"\n return {\n k: v\n for k, v in self.__dict__.items()\n if (\n k not in type(self)().__dict__\n and k not in self.get_params()\n and (k.startswith(\"_\") or k.endswith(\"_\"))\n )\n }\n\n def set_params(self, **params) -> \"BaseWrapper\":\n \"\"\"Override BaseEstimator.set_params to allow setting of routed params.\n \"\"\"\n passthrough = dict()\n for param, value in params.items():\n if any(\n param.startswith(prefix + \"__\") for prefix in self._routing_prefixes\n ):\n # routed param\n setattr(self, param, value)\n else:\n passthrough[param] = value\n return super().set_params(**passthrough)\n\n def _get_param_names(self):\n \"\"\"Get parameter names for the estimator\"\"\"\n return (\n k for k in self.__dict__ if not k.endswith(\"_\") and not k.startswith(\"_\")\n )\n\n def _more_tags(self):\n \"\"\"Get sklearn tags for the estimator\"\"\"\n tags = super()._more_tags()\n tags.update(self._tags)\n return tags\n\n def __repr__(self):\n repr_ = str(self.__name__)\n repr_ += \"(\"\n params = self.get_params()\n if params:\n repr_ += \"\\n\"\n for key, val in params.items():\n repr_ += \"\\t\" + key + \"=\" + str(val) + \"\\n\"\n repr_ += \")\"\n return repr_\n\n\nclass KerasClassifier(BaseWrapper):\n \"\"\"Implementation of the scikit-learn classifier API for Keras.\n \"\"\"\n\n _estimator_type = \"classifier\"\n _tags = {\n \"multilabel\": True,\n \"_xfail_checks\": {\n \"check_classifiers_classes\": \"can't meet \\\n performance target\",\n \"check_fit_idempotent\": \"tf does not use \\\n sparse tensors\",\n \"check_no_attributes_set_in_init\": \"can only \\\n pass if all params are hardcoded in __init__\",\n },\n **BaseWrapper._tags,\n }\n\n _meta = {\n \"n_classes_\",\n \"target_type_\",\n \"classes_\",\n \"encoders_\",\n \"n_outputs_\",\n \"model_n_outputs_\",\n *BaseWrapper._meta,\n }\n\n @staticmethod\n def scorer(y_true, y_pred, **kwargs) -> float:\n \"\"\"Accuracy score based on true and predicted target values.\n\n Parameters\n ----------\n y_true : array-like\n True labels.\n y_pred : array-like\n Predicted labels.\n\n Returns\n -------\n score\n float\n \"\"\"\n return sklearn_accuracy_score(y_true, y_pred, **kwargs)\n\n @staticmethod\n def preprocess_y(y):\n \"\"\"Handles manipulation of y inputs to fit or score.\n\n For KerasClassifier, this handles interpreting classes from `y`.\n\n Arguments:\n y : 1D or 2D numpy array\n\n Returns:\n y : modified 2D numpy array with 0 indexed integer class labels.\n extra_args : dictionary of output attributes, ex `n_outputs_`\n \"\"\"\n y, extra_args = super(KerasClassifier, KerasClassifier).preprocess_y(y)\n\n target_type_ = type_of_target(y)\n\n if len(y.shape) == 1:\n n_outputs_ = 1\n else:\n n_outputs_ = y.shape[1]\n\n if target_type_ == \"binary\":\n # y = array([1, 0, 1, 0])\n # single task, single label, binary classification\n model_n_outputs_ = 1 # single sigmoid output expected\n # encode\n encoder = LabelEncoder()\n # No need to reshape to 1D here,\n # binary targets are always 1D already\n y = encoder.fit_transform(y)\n classes_ = encoder.classes_\n # make lists\n encoders_ = [encoder]\n classes_ = [classes_]\n y = [y]\n elif target_type_ == \"multiclass\":\n # y = array([1, 5, 2])\n model_n_outputs_ = 1 # single softmax output expected\n # encode\n encoder = LabelEncoder()\n if len(y.shape) > 1 and y.shape[1] == 1:\n # Make 1D just so LabelEncoder is happy\n y = y.reshape(-1,)\n y = encoder.fit_transform(y)\n classes_ = encoder.classes_\n # make lists\n encoders_ = [encoder]\n classes_ = [classes_]\n y = [y]\n elif target_type_ == \"multilabel-indicator\":\n # y = array([1, 1, 1, 0], [0, 0, 1, 1])\n # split into lists for multi-output Keras\n # will be processed as multiple binary classifications\n classes_ = [np.array([0, 1])] * y.shape[1]\n y = np.split(y, y.shape[1], axis=1)\n model_n_outputs_ = len(y)\n # encode\n encoders_ = [LabelEncoder() for _ in range(len(y))]\n y = [\n encoder.fit_transform(y_.reshape(-1,) if y_.shape[1] == 1 else y_)\n for encoder, y_ in zip(encoders_, y)\n ]\n classes_ = [encoder.classes_ for encoder in encoders_]\n elif target_type_ == \"multiclass-multioutput\":\n # y = array([1, 0, 5], [2, 1, 3])\n # split into lists for multi-output Keras\n # each will be processesed as a seperate multiclass problem\n y = np.split(y, y.shape[1], axis=1)\n model_n_outputs_ = len(y)\n # encode\n encoders_ = [LabelEncoder() for _ in range(len(y))]\n y = [\n encoder.fit_transform(y_.reshape(-1,) if y_.shape[1] == 1 else y_)\n for encoder, y_ in zip(encoders_, y)\n ]\n classes_ = [encoder.classes_ for encoder in encoders_]\n else:\n raise ValueError(\"Unknown label type: {}\".format(target_type_))\n\n # self.classes_ is kept as an array when n_outputs>1 for compatibility\n # with ensembles and other meta estimators\n # which do not support multioutput\n if len(classes_) == 1:\n n_classes_ = classes_[0].size\n classes_ = classes_[0]\n n_outputs_ = 1\n else:\n n_classes_ = [class_.shape[0] for class_ in classes_]\n n_outputs_ = len(n_classes_)\n\n extra_args.update(\n {\n \"classes_\": classes_,\n \"encoders_\": encoders_,\n \"n_outputs_\": n_outputs_,\n \"model_n_outputs_\": model_n_outputs_,\n \"n_classes_\": n_classes_,\n \"target_type_\": target_type_,\n }\n )\n\n return y, extra_args\n\n def postprocess_y(self, y):\n \"\"\"Reverts _pre_process_inputs to return predicted probabilites\n in formats sklearn likes as well as retrieving the original\n classes.\n \"\"\"\n if not isinstance(y, list):\n # convert single-target y to a list for easier processing\n y = [y]\n\n target_type_ = self.target_type_\n\n class_predictions = []\n\n for i in range(self.n_outputs_):\n\n if target_type_ == \"binary\":\n # array([0.9, 0.1], [.2, .8]) -> array(['yes', 'no'])\n if (\n isinstance(self.encoders_[i], LabelEncoder)\n and len(self.encoders_[i].classes_) == 1\n ):\n # special case: single input label for sigmoid output\n # may give more predicted classes than inputs for\n # small sample sizes!\n # don't even bother inverse transforming, just fill.\n class_predictions.append(\n np.full(\n shape=(y[i].shape[0], 1),\n fill_value=self.encoders_[i].classes_[0],\n )\n )\n else:\n y_ = y[i].round().astype(int)\n if y_.shape[1] == 1:\n # Appease the demands of sklearn transformers\n y_ = np.squeeze(y_, axis=1)\n class_predictions.append(self.encoders_[i].inverse_transform(y_))\n if (\n len(y[i].shape) == 1\n or y[i].shape[1] == 1\n and len(self.encoders_[i].classes_) == 2\n ):\n # result from a single sigmoid output\n # reformat so that we have 2 columns\n y[i] = np.column_stack([1 - y[i], y[i]])\n elif target_type_ in (\"multiclass\", \"multiclass-multioutput\"):\n # array([0.8, 0.1, 0.1], [.1, .8, .1]) ->\n # array(['apple', 'orange'])\n idx = np.argmax(y[i], axis=-1)\n y_ = np.zeros(y[i].shape, dtype=int)\n y_[np.arange(y[i].shape[0]), idx] = 1\n if y_.shape[1] == 1:\n # Appease the demands of sklearn transformers\n y_ = np.squeeze(y_, axis=1)\n class_predictions.append(self.encoders_[i].inverse_transform(y_))\n elif target_type_ == \"multilabel-indicator\":\n class_predictions.append(\n self.encoders_[i].inverse_transform(np.argmax(y[i], axis=1))\n )\n\n class_probabilities = np.squeeze(np.column_stack(y))\n\n y = np.squeeze(np.column_stack(class_predictions))\n\n # type cast back to input dtype\n y = y.astype(self.y_dtype_, copy=False)\n\n extra_args = {\"class_probabilities\": class_probabilities}\n\n return y, extra_args\n\n def _check_output_model_compatibility(self, y):\n \"\"\"Checks that the model output number and loss functions match y.\n \"\"\"\n # check loss function to adjust the encoding of the input\n # we need to do this to mimick scikit-learn behavior\n if isinstance(self.model_.loss, list):\n losses = self.model_.loss\n else:\n losses = [self.model_.loss] * self.n_outputs_\n for i, loss in enumerate(losses):\n if is_categorical_crossentropy(loss) and (\n y[i].ndim == 1 or y[i].shape[1] == 1\n ):\n encoder = OneHotEncoder(sparse=False, dtype=np.uint8)\n tf1dto2d = LabelDimensionTransformer()\n y[i] = tf1dto2d.fit_transform(y[i])\n y[i] = encoder.fit_transform(y[i])\n self.encoders_[i] = make_pipeline(\n self.encoders_[i], tf1dto2d, encoder, \"passthrough\",\n )\n\n return super()._check_output_model_compatibility(y)\n\n def partial_fit(self, X, y, classes=None, sample_weight=None):\n \"\"\"\n Partially fit a model.\n\n Arguments:\n X : array-like, shape `(n_samples, n_features)`\n Training samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`\n True labels for `X`.\n classes: ndarray of shape (n_classes,), default=None\n Classes across all calls to partial_fit. Can be obtained by via\n np.unique(y_all), where y_all is the target vector of the entire dataset.\n This argument is required for the first call to partial_fit and can be\n omitted in the subsequent calls. Note that y doesn’t need to contain\n all labels in classes.\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. The Keras Model must support this.\n\n Returns:\n self : object\n a reference to the instance that can be chain called\n (ex: instance.partial_fit(X, y).transform(X) )\n Raises:\n ValueError : In case of invalid shape for `y` argument.\n \"\"\"\n self.classes_ = classes # TODO: don't swallow this param\n return super().partial_fit(X, y, sample_weight=sample_weight)\n\n def predict_proba(self, X):\n \"\"\"Returns class probability estimates for the given test data.\n\n Arguments:\n X: array-like, shape `(n_samples, n_features)`\n Test samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n\n Returns:\n proba: array-like, shape `(n_samples, n_outputs)`\n Class probability estimates.\n In the case of binary classification,\n to match the scikit-learn API,\n will return an array of shape `(n_samples, 2)`\n (instead of `(n_sample, 1)` as in Keras).\n \"\"\"\n # check if fitted\n if not self.is_fitted_:\n raise NotFittedError(\n \"Estimator needs to be fit before `predict` \" \"can be called\"\n )\n\n # basic input checks\n X = self._validate_data(X=X, y=None, reset=False)\n\n # pre process X\n X, _ = self.preprocess_X(X)\n\n # collect arguments\n predict_args = route_params(\n self.get_params(), destination=\"predict\", pass_filter=self._predict_kwargs,\n )\n\n # call the Keras model's predict\n outputs = self.model_.predict(X, **predict_args)\n\n # join list of outputs into single output array\n _, extra_args = self.postprocess_y(outputs)\n\n # get class probabilities from postprocess_y's output\n class_probabilities = extra_args[\"class_probabilities\"]\n\n return class_probabilities\n\n\nclass KerasRegressor(BaseWrapper):\n \"\"\"Implementation of the scikit-learn regressor API for Keras.\n \"\"\"\n\n _estimator_type = \"regressor\"\n _tags = {\n \"multilabel\": True,\n \"_xfail_checks\": {\n \"check_fit_idempotent\": \"tf does not use sparse tensors\",\n \"check_methods_subset_invariance\": \"can't meet tol\",\n \"check_no_attributes_set_in_init\": \"can only pass if all \\\n params are hardcoded in __init__\",\n },\n **BaseWrapper._tags,\n }\n\n @staticmethod\n def scorer(y_true, y_pred, **kwargs) -> float:\n \"\"\"R^2 score based on true and predicted target values.\n\n Parameters\n ----------\n y_true : array-like\n True labels.\n y_pred : array-like\n Predicted labels.\n\n Returns\n -------\n score\n float\n \"\"\"\n return sklearn_r2_score(y_true, y_pred, **kwargs)\n\n def postprocess_y(self, y):\n \"\"\"Ensures output is floatx and squeeze.\"\"\"\n if np.can_cast(self.y_dtype_, np.float32):\n return np.squeeze(y.astype(np.float32, copy=False)), dict()\n else:\n return np.squeeze(y.astype(np.float64, copy=False)), dict()\n\n def preprocess_y(self, y):\n \"\"\"Split y for multi-output tasks.\n \"\"\"\n y, extra_args = super().preprocess_y(y)\n\n if len(y.shape) == 1:\n n_outputs_ = 1\n else:\n n_outputs_ = y.shape[1]\n\n # for regression, multi-output is handled by single Keras output\n model_n_outputs_ = 1\n\n extra_args.update(\n {\"n_outputs_\": n_outputs_, \"model_n_outputs_\": model_n_outputs_,}\n )\n\n y = [y] # pack into single output list\n\n return y, extra_args\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Returns the mean loss on the given test data and labels.\n\n Arguments:\n X: array-like, shape `(n_samples, n_features)`\n Test samples where `n_samples` is the number of samples\n and `n_features` is the number of features.\n y: array-like, shape `(n_samples,)`\n True labels for `X`.\n\n Returns:\n score: float\n Mean accuracy of predictions on `X` wrt. `y`.\n \"\"\"\n # check loss function and warn if it is not the same as score function\n if self.model_.loss not in (\"mean_squared_error\", self.r_squared,):\n warnings.warn(\n \"Since ScikitLearn's `score` uses R^2 by default, it is \"\n \"advisable to use the same loss/metric when optimizing the \"\n \"model.This class provides an R^2 implementation in \"\n \"`KerasRegressor.r_squared`.\"\n )\n\n return super().score(X, y, sample_weight=sample_weight)\n\n @staticmethod\n @register_keras_serializable()\n def r_squared(y_true, y_pred):\n \"\"\"A simple Keras implementation of R^2 that can be used as a Keras\n loss function.\n\n Since ScikitLearn's `score` uses R^2 by default, it is\n advisable to use the same loss/metric when optimizing the model.\n \"\"\"\n # Ensure input dytpes match\n # y_pred will always be float32 so we cast y_true to float32\n y_true = tf.cast(y_true, dtype=y_pred.dtype)\n # Calculate R^2\n ss_res = tf.math.reduce_sum(tf.math.squared_difference(y_true, y_pred), axis=0)\n ss_tot = tf.math.reduce_sum(\n tf.math.squared_difference(y_true, tf.math.reduce_mean(y_true, axis=0)),\n axis=0,\n )\n return tf.math.reduce_mean(\n 1 - ss_res / (ss_tot + tf.keras.backend.epsilon()), axis=-1\n )\n","sub_path":"scikeras/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":43967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"220948342","text":"import json\nimport model.review\n\nclass Review:\n def __init__(self, id, user, topic, score, content, user_view, topic_view):\n self.id = id\n self.user = user\n self.topic = topic\n self.score = score\n self.content = content\n self.user_view = user_view\n self.topic_view = topic_view\n\n def forward(self, review):\n result = dict()\n result[self.id] = review.id \n result[self.user] = self.user_view.forward(review.user)\n result[self.topic] = self.topic_view.forward(review.topic)\n result[self.score] = review.score\n result[self.content] = review.content\n return result\n\n def forward_str(self, review):\n return json.dumps(self.forward(review))\n\n def backward(self, data, require_all=True):\n id = data.get(self.id, None)\n if require_all:\n user = data[self.user]\n topic = data[self.topic]\n score = data[self.score]\n content = data[self.content]\n else:\n user = data.get(self.user, None)\n topic = data.get(self.topic, None)\n score = data.get(self.score, None)\n content = data.get(self.content, None)\n return model.review.Review(id, user, topic, score, content)\n\n def backward_str(self, user, require_all=True):\n return self.backward(json.loads(user), require_all=require_all)","sub_path":"Tema2/views/json/review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"438014436","text":"import matplotlib.pyplot as plt\nimport numpy as np\nplt.rcParams['font.sans-serif'] = ['FangSong'] # 指定操作系统由的字体\nplt.rcParams['axes.unicode_minus'] = False\n# y=2*x+3\n# 线性函数\n# def get_data(x):\n# return 2*x+3\n# sigmoid函数\ndef get_data(x):\n return 1/(1+np.exp(-x))\n# sin 正弦函数\n# def get_data(x):\n# return np.sin(x)\nx=np.arange(-10,10,0.1)\ny=get_data(x)\nplt.title('sigmoid函数')\n# plt.text(10,0.3,'测试') # 在任意位置填充字符串 x,y是坐标\n# plt.bar(['我是1','我是2','我是3','我是4'],[2,4,6,8])\n# plt.plot(x,y,'r') # 传入x,y 格式化字符串 传三个单词或者字母(可以只传一个),顺序无所谓 用来规定线的颜色,点的形状,线的形状\nplt.show() # 将画布上所有图表进行显示\n# nd=np.array([1,2,3])\n# print(-nd)\n","sub_path":"ai/day8/matplotlib初次使用.py","file_name":"matplotlib初次使用.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"88653365","text":"import json\nimport numpy as np\nfrom s2clientprotocol import ui_pb2 as sc_ui\nfrom s2clientprotocol import spatial_pb2 as sc_spatial\n\n\nclass Config:\n # TODO extract embed_dim_fn to config\n def __init__(self, sz, map, run_id, embed_dim_fn=lambda x: max(1, round(np.log2(x)))):\n self.run_id = run_id\n self.sz, self.map = sz, map\n self.embed_dim_fn = embed_dim_fn\n self.feats = self.acts = self.act_args = self.arg_idx = self.ns_idx = None\n\n def build(self, cfg_path):\n feats, acts, act_args = self._load(cfg_path)\n if 'screen' not in feats:\n feats['screen'] = features.SCREEN_FEATURES._fields\n if 'minimap' not in feats:\n feats['minimap'] = features.MINIMAP_FEATURES._fields\n if 'non_spatial' not in feats:\n feats['non_spatial'] = NON_SPATIAL_FEATURES.keys()\n self.feats = feats\n # TODO not connected to anything atm\n if acts is None:\n acts = FUNCTIONS\n self.acts = acts\n\n if act_args is None:\n act_args = TYPES._fields\n self.act_args = act_args\n\n self.arg_idx = {arg: i for i, arg in enumerate(self.act_args)}\n self.ns_idx = {f: i for i, f in enumerate(self.feats['non_spatial'])}\n #print(self.feats)\n #print(self.acts)\n #print(self.act_args)\n #print(self.arg_idx)\n #print(self.ns_idx)\n\n def map_id(self):\n return self.map + str(self.sz)\n\n def full_id(self):\n if self.run_id == -1:\n return self.map_id()\n return self.map_id() + \"/\" + str(self.run_id)\n\n def policy_dims(self):\n return [(len(self.acts), 0)] + [(getattr(TYPES, arg).sizes[0], is_spatial(arg)) for arg in self.act_args]\n\n def screen_dims(self):\n return self._dims('screen')\n\n def minimap_dims(self):\n return self._dims('minimap')\n\n def non_spatial_dims(self):\n return [NON_SPATIAL_FEATURES[f] for f in self.feats['non_spatial']]\n\n # TODO maybe move preprocessing code into separate class?\n def preprocess(self, obs):\n #types ['screen', 'minimap', 'units', \"player\", \"available_actions\"]\n #return [self._preprocess(obs, _type) for _type in ['screen', 'minimap', 'units'] + self.feats['non_spatial']]\n return [self._preprocess(obs, _type) for _type in ['units'] + self.feats['non_spatial']]\n\n def _dims(self, _type):\n return [f.scale**(f.type == CAT) for f in self._feats(_type)]\n\n def _feats(self, _type):\n feats = getattr(features, _type.upper() + '_FEATURES')\n return [getattr(feats, f_name) for f_name in self.feats[_type]]\n\n def _preprocess(self, obs, _type):\n if _type in self.feats['non_spatial']:\n return np.array([self._preprocess_non_spatial(ob, _type) for ob in obs])\n #_type could be \"minimap\" or \"screen\"\n if _type == \"units\":\n # we can choose return more, \"float\",\"int\", \"bool\"\n out = []\n units_all_info = []\n for ob in obs:\n units_info =[]\n good_units = []\n bad_units = []\n for i in range(len(ob[_type])):\n units_info+=list(ob[_type][i][\"float\"])\n if ob[_type][i][\"int\"] and ob[_type][i][\"int\"].alliance == 1:\n #ob[_type][i][\"float\"] is a numpy class which we can call arribute by names, pos_x etc\n good_units.append(ob[_type][i][\"float\"])\n if ob[_type][i][\"int\"] and ob[_type][i][\"int\"].alliance !=1:\n bad_units.append(ob[_type][i][\"float\"])\n #hack here, 10 means defendroaches, we have 10 units; 4 means we have 4 enemy units\n while len(good_units)<10:\n good_units.append(np.zeros(13))\n while len(bad_units)<10:\n bad_units.append(np.zeros(13))\n out.append([good_units, bad_units])\n units_all_info.append(units_info)\n #print(len(units_all_info[0])) #169\n #exit()\n return np.array(units_all_info)\n #return np.array(out)\n spatial = [[ob[_type][f.index] for f in self._feats(_type)] for ob in obs]\n return np.array(spatial).transpose((0, 2, 3, 1))\n\n def _preprocess_non_spatial(self, ob, _type):\n if _type == 'available_actions':\n acts = np.zeros(len(self.acts))\n acts[ob['available_actions']] = 1\n return acts\n return ob[_type]\n\n def save(self, cfg_path):\n with open(cfg_path, 'w') as fl:\n json.dump({'feats': self.feats, 'act_args': self.act_args}, fl)\n\n def _load(self, cfg_path):\n with open(cfg_path, 'r') as fl:\n data = json.load(fl)\n return data.get('feats'), data.get('acts'), data.get('act_args')\n\n\ndef is_spatial(arg):\n return arg in ['screen', 'screen2', 'minimap']\n","sub_path":"hw3/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"491196936","text":"import sys\n# Pelo terminal da 0.0, e pelo console dá certo, PQ????\ndef serie():\n n = int(sys.argv[1])\n #n = 6\n listaN = list(range(1, n + 1))\n listaM = []\n total = 0\n for n in listaN:\n listaM.append(n+2)\n i = 0\n while (i < len(listaN)):\n total += float(listaN[i]/listaM[i])\n i += 1\n return total\n\ndef main():\n print(serie())\n\nif __name__ == '__main__':\n main()","sub_path":"topicos-especiais/L2/Ex2.py","file_name":"Ex2.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"291038261","text":"import serial\nimport json\nimport numpy as np\n\n\nclass Potentiostat(serial.Serial):\n\n MAX_ABS_VOLTAGE = 1.65\n ALLOWED_CURRENT_RANGE = ('1uA', '10uA', '100uA', '1000uA')\n ALLOWED_TEST_NAMES = ['cyclic']\n\n def __init__(self, port):\n port_param = {'port': port, 'baudrate': 115200, 'timeout': 0.1}\n super().__init__(**port_param)\n self.num_throw_away = 10\n self.max_error_count = 10\n self.throw_away_lines()\n\n\n def throw_away_lines(self):\n \"\"\" \n Throw away first few lines. Deals with case where user has updated the firmware\n which writes a bunch text to the serial port. \n \"\"\"\n for i in range(self.num_throw_away):\n line = self.readline()\n\n\n def get_values(self):\n \"\"\"\n Get current devices values ... connection status, current reading, output voltage,\n reference voltage, current range. \n \"\"\"\n msg_dict = {'':''}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n return rsp\n\n\n def averaging(self, num_average):\n \"\"\"\n Set number of averages used for each measure current value. \n \"\"\"\n if num_average <= 0:\n raise ValueError('averaging must be int > 0')\n msg_dict = {'averaging': int(num_average)}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n return rsp\n\n\n def range(self,range_value):\n \"\"\"\n Set the output current range (uA). Value must be in ALLOW_CURRENT_RANGE list.\n \"\"\"\n if not range_value in self.ALLOWED_CURRENT_RANGE:\n raise ValueError('range must be in {}'.format(self.ALLOWED_CURRENT_RANGE)) \n msg_dict = {'range': range_value}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n return rsp\n\n\n def voltage(self,voltage_value):\n \"\"\"\n Set the output voltage value directly\n \"\"\"\n if abs(voltage_value) > self.MAX_ABS_VOLTAGE:\n raise ValueError('abs(voltage) must be < {}'.format(self.MAX_ABS_VOLTAGE))\n msg_dict = {'voltage': float(voltage_value)}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n return rsp\n\n\n def connected(self, value):\n \"\"\"\n Connect/disconnect counter electrode. value=True connects, value=False disconnects.\n \"\"\"\n msg_dict = {'connected': bool(value)}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n return rsp\n\n\n def offset(self, offset_value):\n \"\"\"\n Set analog output voltage offset. Used for correcting \n \"\"\"\n if abs(offset_value) > self.MAX_ABS_VOLTAGE:\n raise ValueError('abs(offset) must be < {}'.format(self.MAX_ABS_VOLTAGE))\n msg_dict = {'offset': offset_value}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n return rsp\n\n\n def run_test(self, test_name, test_param):\n \"\"\"\n Run voltametric test. \n \n test_name = name of test\n test_param = dictionary of test parameters. \n\n Currently only cyclic voltammetry is implemented.\n\n run_test('cyclic', test_param)\n \n Example params:\n test_param = {\n 'max_voltage' : 1.5,\n 'min_voltage' : -1.5,\n 'scan_rate' : 0.20,\n 'start_voltage' : 'min_voltage',\n 'sample_rate' : 15.0,\n 'cycles' : 2,\n }\n\n \"\"\"\n\n if not test_name in self.ALLOWED_TEST_NAMES:\n raise ValueError('unknown test name {}'.format(test_name))\n\n msg_dict = {'test': {'name': test_name, 'param': test_param}}\n rsp = self.send_and_receive(msg_dict)\n self.error_check_rsp(rsp)\n tval, volt, curr = self.receive_until_done()\n return tval, volt, curr\n\n def send_and_receive(self,msg_dict):\n \"\"\"\n Send and receive message from the device.\n \"\"\"\n msg_json = json.dumps(msg_dict) + '\\n'\n self.write(msg_json.encode())\n rsp_json = self.readline()\n rsp_json = rsp_json.strip()\n done = False\n error_count = 0\n while not done:\n try:\n rsp_dict = json.loads(rsp_json.decode('utf-8'))\n done = True\n except json.decoder.JSONDecodeError:\n line = self.readline()\n if line:\n print('error: {}'.format(line))\n print()\n error_count += 1\n if error_count >= self.max_error_count:\n exit(0)\n return rsp_dict\n\n\n def receive_until_done(self):\n data_list = []\n while True:\n msg_json = self.readline()\n msg_json = msg_json.strip()\n msg_dict = json.loads(msg_json.decode('utf-8'))\n if 'data' in msg_dict:\n data = msg_dict['data']\n data_list.append(data)\n data_tuple = float(data['t']), float(data['v']), float(data['i'])\n print('t: {:e}, v: {:e}, i: {:e}'.format(*data_tuple))\n if 'error' in msg_dict:\n print(msg_dict['error'])\n break\n if 'done' in msg_dict:\n break\n tsec = np.array([item['t'] for item in data_list])\n volt = np.array([item['v'] for item in data_list])\n curr = np.array([item['i'] for item in data_list])\n return tsec, volt, curr # sec, V, A\n\n\n def error_check_rsp(self,rsp):\n if 'error' in rsp:\n raise PotentiostatError(rsp['error'])\n\n\n# Utility\n# --------------------------------------------------------------------------------\n\nclass PotentiostatError(Exception):\n pass\n\ndef convert_A_to_uA(value):\n return 1.0e6*value\n\n","sub_path":"host/potentiostat.py","file_name":"potentiostat.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"329646650","text":"import os\nimport sys\nimport glob\nfrom collections import defaultdict\n\n\ndef get_files(path_raw):\n print(f\"Start reading from {path_raw}\")\n beta_value_files = glob.glob(f\"{path_raw}/*.beta_value.txt\")\n return beta_value_files\n\n\ndef merge_beta_value(beta_value_files):\n total_samples = []\n each_sample_beta_value = defaultdict(dict)\n for each_file in beta_value_files:\n print(f\"Start parsing {each_file}\")\n this_sample_name = os.path.basename(each_file).split(\".\")[0]\n total_samples.append(this_sample_name)\n with open(each_file) as f:\n for line in f:\n if line.startswith(\"pos\"):\n continue\n line_list = line.strip().split(\"\\t\")\n each_sample_beta_value[line_list[0]][this_sample_name] = line_list[1]\n return each_sample_beta_value, total_samples\n\n\ndef write(each_sample_beta_value, total_samples, path_out):\n print(f\"Start writing to {path_out}\")\n with open(path_out, \"w+\") as out:\n out.write(\"pos\\t\" + \"\\t\".join(total_samples) + \"\\n\")\n for each_pos in each_sample_beta_value:\n this_pos_values = each_sample_beta_value[each_pos]\n this_pos_out = []\n for each_sample in total_samples:\n if each_sample in this_pos_values:\n this_pos_out.append(this_pos_values[each_sample])\n else:\n this_pos_out.append(\"NA\")\n if \"NA\" not in this_pos_out:\n out.write(each_pos + \"\\t\" + \"\\t\".join(this_pos_out) + \"\\n\")\n\n\ndef main():\n if len(sys.argv) != 3:\n print(\"USage: python merge_beta_li_13.py [path_to_raw_beta] [bioproject_beta_value.txt]\")\n exit(-1)\n path_raw = sys.argv[1]\n path_out = sys.argv[2]\n beta_value_files = get_files(path_raw)\n each_sample_beta_value, total_samples = merge_beta_value(beta_value_files)\n write(each_sample_beta_value, total_samples, path_out)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"liquid_13/merge_beta_li_13.py","file_name":"merge_beta_li_13.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"160255585","text":"#-*-coding:utf-8 -*-\n\n''' Whole Body Motion: Head orientation control '''\n\nimport config\nimport time\nimport math\n\ndef headcheck(pitch,yaw):\n ''' Example of a whole body head orientation control\n Warning: Needs a PoseInit before executing\n Whole body balancer must be inactivated at the end of the script\n '''\n\n motionProxy = config.loadProxy(\"ALMotion\")\n\n # Set NAO in Stiffness On\n config.StiffnessOn(motionProxy)\n\n # Send NAO to Pose Init\n config.PoseInit(motionProxy)\n\n effectorName = \"Head\"\n\n # Active Head tracking\n isEnabled = True\n motionProxy.wbEnableEffectorControl(effectorName, isEnabled)\n\n # Example showing how to set orientation target for Head tracking\n # The 3 coordinates are absolute head orientation in NAO_SPACE\n # Rotation in RAD in x, y and z axis\n\n # X Axis Head Orientation feasible movement = [-20.0, +20.0] degree\n # Y Axis Head Orientation feasible movement = [-75.0, +70.0] degree\n # Z Axis Head Orientation feasible movement = [-30.0, +30.0] degree\n\n targetCoordinate=[0,pitch,yaw]\n \n # wbSetEffectorControl is a non blocking function\n # time.sleep allow head go to his target\n # The minimum period advised between two successives set commands is 0.2 s\n targetCoordinate = [target*math.pi/180.0 for target in targetCoordinate]\n motionProxy.wbSetEffectorControl(effectorName, targetCoordinate)\n time.sleep(3.0)\n\n # Deactivate Head tracking\n isEnabled = False\n motionProxy.wbEnableEffectorControl(effectorName, isEnabled)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"headmove.py","file_name":"headmove.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"593055187","text":"# -*- coding: utf-8 -*-}\nfrom flask import g as flask_g\nfrom flask import request\nfrom flask_babel import gettext\nfrom flask_restful import Resource\n\nfrom .app_auth import requires_auth\nfrom .schema import *\n\n_ = gettext\n\n\nclass StorageListApi(Resource):\n \"\"\" REST API for listing class Storage \"\"\"\n\n @staticmethod\n @requires_auth\n def get():\n only = ('id', 'name') \\\n if request.args.get('simple', 'false') == 'true' else None\n storages = Storage.query.filter(Storage.enabled).order_by('name')\n user = getattr(flask_g, 'user')\n\n # Administrative have access to URL\n exclude = tuple() if user.id in (0, 1) else tuple(['url'])\n\n return StorageListResponseSchema(many=True, only=only,\n exclude=exclude).dump(storages).data\n\n\nclass StorageDetailApi(Resource):\n \"\"\" REST API for a single instance of class Storage \"\"\"\n\n @staticmethod\n @requires_auth\n def get(storage_id):\n user = getattr(flask_g, 'user')\n exclude = tuple() if user.id in (0, 1) else tuple(['url'])\n\n storage = Storage.query.filter(Storage.enabled,\n Storage.id == storage_id).first()\n if storage is not None:\n return StorageItemResponseSchema(exclude=exclude).dump(storage).data\n else:\n return dict(status=\"ERROR\",\n message=_(\"%(type)s not found.\",\n type=_('Storage'))), 404\n","sub_path":"limonero/storage_api.py","file_name":"storage_api.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"132222184","text":"from cement.core.controller import expose\nfrom cfoundation import Controller\n\nclass Base(Controller):\n class Meta:\n label = 'base'\n description = 'manage dotfiles with stow'\n arguments = [\n (['packages'], {\n 'action': 'store',\n 'help': 'dotfile package names',\n 'nargs': '*'\n })\n ]\n\n @expose()\n def default(self):\n pargs = self.app.pargs\n s = self.app.services\n spinner = self.app.spinner\n if pargs.debug:\n self.app.conf.debug = True\n if not pargs.packages or len(pargs.packages) <= 0:\n spinner.fail('dotfile packages not specified')\n exit(0)\n s.stow.stow(pargs.packages)\n spinner.succeed('stowed ' + ' '.join(pargs.packages))\n","sub_path":"dotstow/controllers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"61251546","text":"from tkinter import *\nimport math\n\n\nHEIGHT = 500\nWIDTH = 500\n\n\nclass Figure:\n def __init__(self, canvas, **coords):\n self.__dict__.update(coords)\n self.canvas = canvas\n self.rectangles = []\n self.triangles = []\n self.hexagons = []\n self.ovals = []\n self.rectangles_generated = False\n self.triangles_generated = False\n self.hexagons_generated = False\n self.ovals_generated = False\n\n def create_rectangles(self):\n while not self.rectangles_generated:\n for i in range(1000):\n self.rectangles.append(self.canvas.create_rectangle(\n self.x1 + (i*40), self.y1, self.x2 + (i*40), self.y2, fill='black'))\n self.rectangles.append(self.canvas.create_rectangle(\n self.x1 - (i*40), self.y1, self.x2 - (i*40), self.y2, fill='black'))\n self.rectangles_generated = True\n for each in self.rectangles:\n self.canvas.move(each, -1, 0)\n self.canvas.after(10, self.create_rectangles)\n\n\n def create_triangles(self):\n while not self.triangles_generated:\n for i in range(1000):\n self.triangles.append(self.canvas.create_polygon(\n self.x1 + (i*40), self.y1, self.x2 + (i*40), self.y2, self.x3 + (i*40), self.y3\n ))\n self.triangles.append(self.canvas.create_polygon(\n self.x1 - (i*40), self.y1, self.x2 - (i*40), self.y2, self.x3 - (i*40), self.y3\n ))\n self.triangles_generated = True\n for each in self.triangles:\n self.canvas.move(each, 1, 0)\n self.canvas.after(10, self.create_triangles)\n\n\n def create_hexagons(self):\n while not self.hexagons_generated:\n all_hexs = self.canvas.find_all()\n #print(self.canvas.itemcget(all_hexs[0], 'offset'))\n for i in range(1000):\n self.hexagons.append(self.canvas.create_polygon(\n self.x4 + (i*80), self.y4, self.x5 + (i*80), self.y5, self.x6 + (i*80), self.y6,\n self.x1 + (i*80), self.y1, self.x2 + (i*80), self.y2, self.x3 + (i*80), self.y3,\n ))\n self.hexagons.append(self.canvas.create_polygon(\n self.x1 - (i*80), self.y1, self.x2 - (i*80), self.y2, self.x3 - (i*80), self.y3,\n self.x4 - (i*80), self.y4, self.x5 - (i*80), self.y5, self.x6 - (i*80), self.y6,\n ))\n self.hexagons_generated = True\n for each in self.hexagons:\n #if self.hexagons.index(each) // 3 :\n # self.canvas.itemconfigure(each, fill='blue')\n self.canvas.move(each, 10, 0)\n #self.canvas.move(each, -10, 3)\n self.canvas.after(10, self.create_hexagons)\n\n def create_ovals(self):\n while not self.ovals_generated:\n for i in range(1000):\n self.ovals.append(self.canvas.create_polygon(\n self.get_oval_coords(self.x1 + (i*60), self.y1, self.x2 + (i*60), self.y2)\n ))\n self.ovals.append(self.canvas.create_polygon(\n self.get_oval_coords(self.x1 - (i*60), self.y1, self.x2 - (i*60), self.y2)\n ))\n self.ovals_generated = True\n\n\n def get_oval_coords(self, x1, y1, x2, y2):\n steps = 20\n rotation = 30\n rotation = rotation * math.pi / 180.0\n\n # major and minor axes\n a = (x2 - x1) / 2.0\n b = (y2 - y1) / 2.0\n\n # center\n xc = x1 + a\n yc = y1 + b\n\n point_list = []\n for i in range(steps):\n theta = (math.pi * 2) * (float(i) / steps)\n\n x1 = a * math.cos(theta)\n y1 = b * math.sin(theta)\n\n # rotate x, y\n x = (x1 * math.cos(rotation)) + (y1 * math.sin(rotation))\n y = (y1 * math.cos(rotation)) - (x1 * math.sin(rotation))\n\n point_list.append(round(x + xc))\n point_list.append(round(y + yc))\n\n return point_list\n\n\nclass Objects(Frame):\n def __init__(self, parent):\n Frame.__init__(self, parent, background='white')\n self.parent = parent\n self.parent.title('Манипуляции с фигурами')\n self.pack(fill=BOTH, expand=1)\n self.centerWindow()\n self.initUI()\n self.angle = 0\n\n def initUI(self):\n self.canvas_area = Button(\n self, text='Поле', width=10, command=self.make_canvas)\n self.rectangles = Button(\n self, text='gen_rectangle()',\n command=self.gen_rectangle, width=16)\n self.rectangles.grid(row=0, column=1)\n self.canvas_area.grid(row=0, column=0)\n triangles = Button(self, text='gen_triangles()', command=self.gen_triangle, width=16)\n hexagons = Button(self, text='gen_hexagons()', command=self.gen_hexagon, width=16)\n ovals = Button(self, text='gen_ovals()', command=self.gen_oval, width=16)\n rotating = Button(self, text='rotate()', command=self.rotate, width=16)\n self.rotating_angle = Entry(self, width=16)\n moving = Button(self, text='move()', command=self.move, width=16)\n self.deltaxy = Entry(self, width=16)\n triangles.grid(row=0, column=2)\n hexagons.grid(row=0, column=3)\n rotating.grid(row=1, column=0)\n moving.grid(row=1, column=1)\n ovals.grid(row=0, column=4)\n self.rotating_angle.grid(row=2, column=0)\n self.deltaxy.grid(row=2, column=1)\n\n def make_canvas(self):\n self.canvas_window = Toplevel(self)\n self.canvas = Canvas(self.canvas_window, width=500, height=500)\n self.canvas.grid(row=0, column=0)\n # TODO: frontend\n self.canvas.create_line(0, 250, 500, 250, width=2)\n self.canvas.create_line(250, 500, 250, 0, width=2)\n self.canvas.focus()\n\n def gen_rectangle(self):\n self.all_rects = Figure(self.canvas, x1=250, y1=250, x2=275, y2=275)\n self.all_rects.create_rectangles()\n\n def gen_triangle(self):\n self.all_triangles = Figure(self.canvas, x1=300, y1=250, x2=285, y2=330, x3=265, y3=250)\n self.all_triangles.create_triangles()\n\n def gen_hexagon(self):\n self.all_hexagons = Figure(self.canvas, x1=235, y1=224, x2=265, y2=224, x3=280, y3=250,\n x4=265, y4=276, x5=235, y5=276, x6=220, y6=250)\n self.all_hexagons.create_hexagons()\n\n def gen_oval(self):\n self.all_ovals = Figure(self.canvas, x1=250, y1=250, x2=290, y2=290)\n self.all_ovals.create_ovals()\n\n def move(self):\n \"\"\"Параллельный перенос\"\"\"\n all_figures = self.canvas.find_all()\n deltax, deltay = self.deltaxy.get().split(',')\n for each in all_figures:\n self.canvas.move(each, deltax, deltay)\n self.canvas.after(100, self.move)\n\n def rotate(self):\n all_figures = self.canvas.find_all()\n all_bboxes\n self.angle += int(self.rotating_angle.get())\n #for each in all_figures\n self.canvas.after(500, self.rotate)\n\n\n def centerWindow(self):\n w = 880\n h = 96\n sw = self.parent.winfo_screenwidth()\n sh = self.parent.winfo_screenheight()\n x = (sw - w) / 2\n y = (sh - h) / 2\n self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))\n\n\ndef main():\n root = Tk()\n ex = Objects(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Manipulations_flat_objects/tkinter_objects.py","file_name":"tkinter_objects.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"140446867","text":"from django.conf.urls import patterns, url\n\nfrom mooc import views\n\nurlpatterns = patterns('',\n# top related views\n url(r'^$', views.index, name='index'),\n url(r'^signup/$', views.signup), #Only Takes care of Loading the Sign Up HTML Page.\n url(r'^add_user/$', views.add_user), # Handles User Sign Up Form.\n url(r'^login/$', views.login_user, name='signin'),\n url(r'^home/$', views.home),\n\n# user related views\n url(r'^profile/$', views.profile),\n url(r'^update_user/$', views.update_user),\n url(r'^logout/$', views.logout_user),\n\n# category related views\n url(r'^list_category/$', views.list_category),\n url(r'^category/$', views.category),\n url(r'^add_category/$', views.add_category),\n url(r'^remove_category/$', views.remove_category),\n\n# course related views\n url(r'^list_course/$', views.list_course),\n url(r'^course/$', views.course),\n url(r'^add_course/$', views.add_course),\n url(r'^remove_course/$', views.remove_course),\n url(r'^get_course/$', views.get_course),\n\n# course and user related activity \n url(r'^enroll_course/$', views.enroll_course),\n url(r'^drop_course/$', views.drop_course),\n\n# announcement related activity\n url(r'^list_announcement/$', views.list_announcement), \n url(r'^announcement/$', views.announcement),\n url(r'^add_announcement/$', views.add_announcement),\n url(r'^edit_announcement/$', views.edit_announcement),\n url(r'^update_announcement/$', views.update_announcement),\n url(r'^remove_announcement/$', views.remove_announcement),\n url(r'^get_announcement/$', views.get_announcement),\n \n# discussion related activity\n url(r'^discussion/$', views.discussion),\n url(r'^add_discussion/$', views.add_discussion),\n url(r'^get_discussion/$', views.get_discussion),\n url(r'^edit_discussion/$', views.edit_discussion),\n url(r'^list_discussion/$', views.list_discussion),\n url(r'^update_discussion/$', views.update_discussion),\n url(r'^remove_discussion/$', views.remove_discussion),\n url(r'^message/$', views.message),\n url(r'^add_message/$', views.add_message),\n url(r'^remove_message/$', views.remove_message),\n url(r'^edit_message/$', views.edit_message),\n url(r'^update_message/$', views.update_message),\n# quiz related activity\n url(r'^quiz/$', views.quiz),\n url(r'^add_quiz/$', views.add_quiz),\n url(r'^add_questionhtml/$', views.show_addquestionhtml),\n url(r'^add_question/$', views.add_question),\n url(r'^list_quiz/$', views.list_quiz),\n url(r'^update_quiz/$', views.update_quiz),\n url(r'^get_quiz/$', views.get_quiz),\n url(r'^remove_quiz/$', views.remove_quiz),\n url(r'^edit_quiz/$', views.edit_quiz),\n url(r'^evaluate_quiz/$', views.evaluate_quiz),\n)\n","sub_path":"MOOC/cmpe275p2_ui-master/mooc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"332052894","text":"\"\"\"\nAuthor: Sandeep Shenoy sandeepjshenoy@gmail.com\n\"\"\"\nfrom rcviz import callgraph, viz\n\n@viz\ndef subsets(a, i, t):\n if i == len(a):\n print(\">>%s\" %t)\n return t\n #print(\"%d %s\" %(i, t))\n subsets(a, i + 1, t)\n t.append(a[i])\n subsets(a, i + 1, t)\n t.pop()\n\na = [1,2,3]\nt = []\nsubsets(a, 0, t)\n# callgraph.render(\"subsets.png\")\n","sub_path":"IK/Recursion/subsets.py","file_name":"subsets.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"263442313","text":"# -*- coding: utf-8 -*-\nimport json, re, requests\nfrom knp_utils import knp_job,models, KnpSubProcess\nfrom pyknp import KNP\nfrom bs4 import BeautifulSoup\nfrom AccesDB import AccessToDataBase\n\nclass my_knp_utils:\n def __init__(self):\n self.knp = KNP()\n #self.IDsetter = counter()\n self.__counter__ = 0\n\n def counter(self):\n self.__counter__ += 1\n return self.__counter__\n\n\n\n # about input\n def get_knp_result(self, sentence, id = 0):\n # print('before: ' + sentence)\n sentence = sentence.replace(' ', '')\n sentence = sentence.replace(' ', '')\n sentence = sentence.replace(' ', '')\n # print('after: ' + sentence)\n g = input_str=knp_job.main([{\"text-id\":self.counter(), \"text\":sentence}], juman_command=\"jumanpp\", knp_options=\"-tab -anaphora\").seq_document_obj[0].parsed_result\n #print('after2: ' + g)\n r = self.knp.result(g)\n for t in r.tag_list():\n pass\n #print(t.repname)\n return r\n\n def get_knp_results(self, sentences, id = 0):\n return [self.knp.result(input_str=x.parsed_result) for x in knp_job.main([{\"text-id\":self.counter(), \"text\":x} for x in sentences], juman_command=\"jumanpp\", knp_options=\"-tab -anaphora\").seq_document_obj]\n\n def get_nodes_from_terminal(self, knp_tag):\n tags = []\n for t in knp_tag.children:\n tags += self.get_nodes_from_terminal(t)\n return tags + [knp_tag]\n\n def get_kframe(self, tag, kFrameName):\n \"\"\"\n 引数:\n \"ガ\",\"デ\" .... \"時間\", \"外の関係\", \"修飾\", \"トスル\", \"二ツク\", .....\n 述語の品詞によって異なる? 単語によっても異なるかも\n 返値: (単語, tag-id)\n 述語でない場合 : None\n 指定した格フレームは取り得ない場合 : ''\n 指定した格フレームは取っていなかった場合 : '-'\n 指定した各フレームを持つ場合 : 'word'\n \"\"\"\n if \"格解析結果\" not in tag.features:\n return (None, None)\n r = re.search(\"%s/[^/]+/([^/]+)/([^/]+)/[^/]+/[^/]+;\" % kFrameName, tag.features[\"格解析結果\"])\n if r is None:\n return (\"\", None)\n else:\n return (r.group(1), None if r.group(2) == \"-\" else int(r.group(2)))\n\n def get_modify_type(self, tag):\n \"\"\"\n 返値:\n 文節内 / ノ格 / 〇〇格 / (副詞とかもあるかも)\n \"\"\"\n if \"係\" in tag.features:\n return tag.features[\"係\"]\n else:\n return None\n\n\nclass preprocessor:\n\n def __init__(self):\n self.knp = KNP()\n self.util = my_knp_utils()\n self.db = AccessToDataBase()\n self.uniques = []\n self.topicDict = {}\n self.incompleteSentence =\"\"\n\n self.GTPP = [None]*4\n\n # 属性データベース\n self.propertyDicts = {\n \"work\" : {},\n \"other\" : {\"髪\": \"all\",\"目\":\"all\",\"仕事\":\"all\"}\n }\n \"\"\"\n {\n \"work\": {B: 種類, ....},\n Aの種類 : {B: 種類, ....},\n ...\n }\n 今は other だけ\n \"\"\"\n\n\n # 述語データベース\n self.predicateDict = {\n \"短い\": \"all\",\n \"長い\": \"all\",\n \"黄色\": \"all\",\n \"青色\": \"all\",\n \"黄\": \"all\",\n \"青\": \"all\",\n \"頑張っている\":\"all\"\n }\n \"\"\"\n {\n ”C”: 種類,\n ...\n }\n 今は all だけ\n \"\"\"\n\n # webページキャッシュ\n self.cashe = {}\n\n def checkUnique(self, text):\n for u in self.uniques:\n if len(text) > 1:\n if text in u:\n return u\n return False\n\n\n def setGenre(self, genre):\n result = self.db.getData(genre)\n # print(result.val().items())\n for topic, pp in result.val().items():\n self.uniques.append(topic.replace(\" \",\"\"))\n for k, v in pp.items():\n if type(k) is list:\n for i in k:\n self.propertyDicts[\"other\"][i] = \"all\"\n else:\n self.propertyDicts[\"other\"][k] = \"all\"\n\n if type(v) is list:\n for i in v:\n self.predicateDict[i] = \"all\"\n else:\n self.predicateDict[v] = \"all\"\n #del self.propertyDicts[\"other\"][\"青葉\"]\n #del self.predicateDict[\"キャラ\"]\n print(self.propertyDicts, self.predicateDict)\n\n # about result\n def search_topic_candidate(self, tagList):\n cand_list = []\n\n '''\n # ガ格, ガ格を修飾する名詞全てを候補\n for t in tagList[::-1]:\n kframe, index = self.util.get_kframe(t, \"ガ\")\n if kframe is None:\n continue\n elif index is None:\n continue\n else:\n cand_list += [t]\n for t in self.util.get_nodes_from_terminal(tagList[index])[:-1]:\n mType = self.util.get_modify_type(t)\n if mType == \"ノ格\":\n # 固有名詞があれば検索の優先度をあげる\n if \"固有\" in t.spec():\n cand_list = [t] + cand_list\n else:\n cand_list += [t]\n elif mType == \"文節内\":\n pass\n else:\n return cand_list\n return cand_list\n\n for t in tagList:\n if \"固有\" in t.spec():\n return [t]\n\n return []\n\n '''\n\n rList = []\n\n for t in tagList:\n #print(t)\n text = t.repname.split(\"/\")[0]\n for u in self.uniques:\n if len(text) > 1:\n if text in u:\n rList.append((t, u))\n continue\n \"\"\"\n if \"固有\" in t.spec():\n rList.append((t, t.repname.split(\"/\")[0]))\n \"\"\"\n return rList\n\n def search_topic(self, tagList):\n lst = self.search_topic_candidate(tagList)\n # print(\"candidate\", lst)\n for word in lst:\n #print(word)\n if self.isTopic(word[1]):\n return (word[1], word[0])\n return (None, None)\n\n def search_topic_by_sentence(self,tagList,sentence):\n lst = self.search_topic_candidate(tagList)\n charactor = ''\n for i in self.uniques:\n c = i.replace(' ','')\n if c in sentence:\n charactor = i\n #print(charactor)\n for j in lst:\n #print(j)\n if j[1] == charactor:\n return (j[1], j[0])\n #if self.isTopic(j[1]):\n # return (j[1], j[0])\n return (None, None)\n\n def isTopic(self, word):\n if self.GTPP[1] is not None:\n if word in self.propertyDicts[self.GTPP[1][1]]:\n return False\n else:\n for dicts in self.propertyDicts:\n if word in dicts:\n return False\n\n if word in self.predicateDict:\n return False\n\n return True\n\n\n\n def isTopicWithTag(self, tag):\n # dict check\n if self.GTPP[1] is not None:\n if tag.repname.split(\"/\")[0] in self.propertyDicts[self.GTPP[1][1]]:\n return False\n else:\n for dicts in self.propertyDicts:\n if tag.repname.split(\"/\")[0] in dicts:\n return False\n\n if tag.repname.split(\"/\")[0] in self.predicateDict:\n return False\n\n\n # use genre_page / pixiv only?\n for page in self.genrePages:\n soup = BeautifulSoup(page, 'lxml')\n aTags = soup.find_all(\"a\", text=re.compile(tag.repname.split(\"/\")[0]))\n for _a in aTags:\n # pixiv only\n r = None\n if _a.get(\"href\") in self.cashe:\n r = self.cashe[_a.get(\"href\")]\n else:\n _r = requests.get(_a.get(\"href\"))\n if _r.status_code == 200:\n r = _r.text\n self.cashe[_a.get(\"href\")] = r\n else:\n continue\n soup = BeautifulSoup(r, 'lxml')\n cl = soup.find(id=\"breadcrumbs\").find_all(\"a\")\n for c in cl[::-1]:\n if self.GTPP[0][0] in c.text:\n return True\n else:\n pass\n\n # search page\n r = None\n url = \"https://dic.pixiv.net/a/\" + tag.repname.split(\"/\")[0]\n # print(\"url\", url)\n if url in self.cashe:\n r = self.cashe[url]\n else:\n _r = requests.get(url)\n #print(\"respond\", _r.status_code, _r.text)\n if _r.status_code == 200:\n r = _r.text\n self.cashe[url] = r\n else:\n return False\n soup = BeautifulSoup(r, 'lxml')\n cl = soup.find(id=\"breadcrumbs\").find_all(\"a\")\n for c in cl[::-1]:\n if self.GTPP[0][0] in c.text:\n return True\n return False\n\n def searchProperty(self, tagList):\n for tag in tagList:\n p, g = self.isProperty(tag)\n if p:\n return (tag, p, g)\n return (None, None, None)\n\n def isProperty(self, tag):\n if self.GTPP[1] is not None:\n if tag.repname.split(\"/\")[0] in self.propertyDicts[self.GTPP[1][1]]:\n return (self.propertyDicts[self.GTPP[1][1]][tag.repname.split(\"/\")[0]], self.GTPP[1][1])\n else:\n if tag.repname.split(\"/\")[0] in self.propertyDicts[\"work\"]:\n return (self.propertyDicts[\"work\"][tag.repname.split(\"/\")[0]], \"work\")\n return (False, None)\n\n\n\n def searchPredicate(self, tagList):\n for tag in tagList:\n p = self.isPredicate(tag)\n if p:\n return (tag, p)\n return (None, None)\n\n def isPredicate(self, tag):\n if tag.repname.split(\"/\")[0] in self.predicateDict:\n if self.GTPP[2] is None:\n return self.predicateDict[tag.repname.split(\"/\")[0]]\n elif self.GTPP[2][1] == self.predicateDict[tag.repname.split(\"/\")[0]]:\n return self.predicateDict[tag.repname.split(\"/\")[0]]\n return False\n\n\n\n def getInputType(self, result):\n text = result\n string = \"\"\n #print(result)\n if type(result) is list:\n pass\n else:\n for tag in result.tag_list():\n string += tag.get_surface()\n for pt in [\"よね\", \"でしょ\", \"もんね\", \"かね\", \"かな\", \"じゃない\"]: # イントネーションで100か1000か変わるから微妙...\n if pt in string:\n return 1000 # あえて100の同意を求める場合はカットで.\n for pt in [\"なに\",\"なぜ\",\"どれ\" \"どこ\", \"なんで\", \"どうして\",\"だれ\",\"誰\",\"何の\",\"なんの\"]:\n if pt in string:\n return 200\n for pt in [\"なの\",\"ですか\"]:\n if pt in text:\n return 300\n return 1000\n","sub_path":"myknputils.py","file_name":"myknputils.py","file_ext":"py","file_size_in_byte":11537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"539205931","text":"# author: mofhu@github\n# A. Second Hands\n\nncase = int(input())\n\nfor t in range(1, ncase + 1):\n n, k = [int(s) for s in input().split(' ')]\n s = [int(s) for s in input().split(' ')]\n s.sort()\n d = {}\n ans = 'YES'\n for i in s:\n if i in d:\n if d[i] >= 2:\n ans = 'NO'\n break\n d[i] += 1\n else:\n d[i] = 1\n if 2 * k < n:\n ans = 'NO'\n print('Case #{}: {}'.format(t, ans))\n","sub_path":"metahackercup/QR2022/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"506501723","text":"from distutils.core import setup, Extension\nfrom os import environ\nfrom os.path import dirname, join\nimport sys\nimport subprocess\n\ndef line_prepender(filename, line):\n with open(filename,'r+') as f:\n platform_defined = f.readline().split('=', 1)[0].strip() == 'dev_platform'\n if not platform_defined:\n f.seek(0, 0)\n content = f.read()\n f.seek(0, 0)\n f.write(line.rstrip('\\r\\n') + '\\n' + content)\n\ndev_platform = sys.platform\nkivy_ios_root = environ.get('KIVYIOSROOT', None)\nif kivy_ios_root is not None:\n dev_platform = 'ios'\n\n# OSX\nif dev_platform == 'darwin':\n try:\n from Cython.Distutils import build_ext\n except ImportError:\n raise\n files = ['pyobjus.pyx']\n# iOS\nelif dev_platform == 'ios':\n from distutils.command.build_ext import build_ext\n files = ['pyobjus.c']\n\n# append info about platform on first line of pyobjus.pyx\nline_prepender('pyobjus/pyobjus.pyx', 'dev_platform = \"{0}\"'.format(dev_platform))\n\nif dev_platform == 'ios':\n subprocess.call(['find', '.', '-name', '*.pyx', '-exec', 'cython', '{}', ';'])\n\nlibraries = ['ffi']\nlibrary_dirs = []\nextra_compile_args = []\nextra_link_args = []\ninclude_dirs = []\n\n# create the extension\nsetup(name='pyobjus',\n version='1.0',\n cmdclass={'build_ext': build_ext},\n packages=['pyobjus'],\n ext_package='pyobjus',\n ext_modules=[\n Extension(\n 'pyobjus', [join('pyobjus', x) for x in files],\n libraries=libraries,\n library_dirs=library_dirs,\n include_dirs=include_dirs,\n extra_link_args=extra_link_args)\n ]\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"446238469","text":"string = 'abcd'\r\n#substring in continous fashion\r\nsubstrings = [string[i:j] for i in range(len(string)) for j in range(i+1,len(string)+1)]\r\n # +1 because slicing excludes last index\r\nprint(substrings)\r\n\r\n#powerset\r\n\r\nlist = [1,2,3]\r\n\r\npower = []\r\n\r\nfor i in list:\r\n power += [i + num for num in list]\r\n\r\n\r\nprint(power)","sub_path":"List_and_string/string9.py","file_name":"string9.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"484689629","text":"import datetime\nimport flask\nimport hashlib\nimport modules.authentication as authentication\nimport modules.public.logic as public_logic\nimport modules.publisher.api as api\nfrom dateutil import relativedelta\nfrom json import dumps, loads\nfrom operator import itemgetter\nfrom modules.exceptions import (\n ApiError,\n ApiTimeoutError,\n ApiResponseDecodeError,\n ApiResponseError,\n ApiResponseErrorList,\n MacaroonRefreshRequired\n)\n\n\ndef refresh_redirect(path):\n macaroon_discharge = authentication.get_refreshed_discharge(\n flask.session['macaroon_discharge']\n )\n flask.session['macaroon_discharge'] = macaroon_discharge\n\n return flask.redirect(path)\n\n\ndef get_account():\n try:\n account = api.get_account(flask.session)\n\n error_list = []\n if 'error_list' in account:\n for error in account['error_list']:\n if error['code'] == 'user-not-ready':\n if 'has not signed agreement' in error['message']:\n return flask.redirect('/account/agreement')\n elif 'missing namespace' in error['message']:\n return flask.redirect('/account/username')\n else:\n error_list.append(error)\n\n context = {\n 'error_list': error_list\n }\n else:\n user_snaps = []\n if '16' in account['snaps']:\n user_snaps = account['snaps']['16']\n\n flask_user = flask.session['openid']\n\n context = {\n 'image': flask_user['image'],\n 'username': flask_user['nickname'],\n 'displayname': flask_user['fullname'],\n 'email': account['email'],\n 'snaps': user_snaps,\n 'error_list': error_list\n }\n\n return flask.render_template(\n 'account.html',\n **context\n )\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n\ndef get_agreement():\n return flask.render_template('developer_programme_agreement.html')\n\n\ndef post_agreement():\n agreed = flask.request.form.get('i_agree')\n\n if agreed == 'on':\n try:\n api.post_agreement(flask.session, True)\n except MacaroonRefreshRequired:\n return refresh_redirect(\n '/account/agreement'\n )\n return flask.redirect('/account')\n else:\n return flask.redirect('/account/agreement')\n\n\ndef get_account_name():\n return flask.render_template('username.html')\n\n\ndef post_account_name():\n username = flask.request.form.get('username')\n\n if username:\n try:\n response = api.post_username(flask.session, username)\n except MacaroonRefreshRequired:\n return refresh_redirect(\n '/account/username'\n )\n\n if 'error_list' in response:\n return flask.render_template(\n 'username.html',\n username=username,\n error_list=response['error_list']\n )\n else:\n return flask.redirect('/account')\n else:\n return flask.redirect('/account/username')\n\n\ndef publisher_snap_measure(snap_name):\n \"\"\"\n A view to display the snap measure page for specific snaps.\n\n This queries the snapcraft API (api.snapcraft.io) and passes\n some of the data through to the publisher/measure.html template,\n with appropriate sanitation.\n \"\"\"\n try:\n details = api.get_snap_info(snap_name, flask.session)\n except ApiTimeoutError as api_timeout_error:\n flask.abort(504, str(api_timeout_error))\n except ApiResponseDecodeError as api_response_decode_error:\n flask.abort(502, str(api_response_decode_error))\n except ApiResponseErrorList as api_response_error_list:\n if api_response_error_list.status_code == 404:\n flask.abort(404, 'No snap named {}'.format(snap_name))\n else:\n codes = [error['code'] for error in api_response_error_list.errors]\n error_messages = ', '.join(codes)\n flask.abort(502, error_messages)\n except ApiResponseError as api_response_error:\n flask.abort(502, str(api_response_error))\n except ApiError as api_error:\n flask.abort(502, str(api_error))\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n metric_period = flask.request.args.get('period', default='30d', type=str)\n metric_bucket = ''.join([i for i in metric_period if not i.isdigit()])\n metric_period_int = int(metric_period[:-1])\n\n installed_base_metric = flask.request.args.get(\n 'active-devices',\n default='version',\n type=str\n )\n\n today = datetime.datetime.utcnow().date()\n end = today - relativedelta.relativedelta(days=1)\n start = None\n if metric_bucket == 'd':\n start = end - relativedelta.relativedelta(days=metric_period_int)\n elif metric_bucket == 'm':\n start = end - relativedelta.relativedelta(months=metric_period_int)\n\n if installed_base_metric == 'version':\n installed_base = \"weekly_installed_base_by_version\"\n elif installed_base_metric == 'os':\n installed_base = \"weekly_installed_base_by_operating_system\"\n metrics_query_json = {\n \"filters\": [\n {\n \"metric_name\": installed_base,\n \"snap_id\": details['snap_id'],\n \"start\": start.strftime('%Y-%m-%d'),\n \"end\": end.strftime('%Y-%m-%d')\n },\n {\n \"metric_name\": \"weekly_installed_base_by_country\",\n \"snap_id\": details['snap_id'],\n \"start\": end.strftime('%Y-%m-%d'),\n \"end\": end.strftime('%Y-%m-%d')\n }\n ]\n }\n\n try:\n metrics_response_json = api.get_publisher_metrics(\n flask.session,\n json=metrics_query_json\n )\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n nodata = True\n\n for metric in metrics_response_json['metrics']:\n if metric['status'] == 'OK':\n nodata = False\n\n active_devices = metrics_response_json['metrics'][0]\n active_devices['series'] = sorted(\n active_devices['series'],\n key=itemgetter('name')\n )\n latest_active_devices = 0\n\n for series_index, series in enumerate(active_devices['series']):\n for index, value in enumerate(series['values']):\n if value is None:\n active_devices['series'][series_index]['values'][index] = 0\n values = series['values']\n if len(values) == len(active_devices['buckets']):\n latest_active_devices += values[len(values)-1]\n\n active_devices = {\n 'series': active_devices['series'],\n 'buckets': active_devices['buckets']\n }\n\n users_by_country = public_logic.calculate_metrics_countries(\n metrics_response_json['metrics'][1]['series']\n )\n\n country_data = public_logic.build_country_info(\n users_by_country,\n True\n )\n territories_total = 0\n for data in country_data.values():\n if data['number_of_users'] > 0:\n territories_total += 1\n\n context = {\n # Data direct from details API\n 'snap_name': snap_name,\n 'snap_title': details['title'],\n 'metric_period': metric_period,\n 'active_device_metric': installed_base_metric,\n\n # Metrics data\n 'nodata': nodata,\n 'latest_active_devices': \"{:,}\".format(latest_active_devices),\n 'active_devices': active_devices,\n 'territories_total': territories_total,\n 'territories': country_data,\n\n # Context info\n 'is_linux': 'Linux' in flask.request.headers['User-Agent']\n }\n\n return flask.render_template(\n 'publisher/measure.html',\n **context\n )\n\n\ndef get_market_snap(snap_name):\n try:\n snap_details = api.get_snap_info(snap_name, flask.session)\n except ApiTimeoutError as api_timeout_error:\n flask.abort(504, str(api_timeout_error))\n except ApiResponseDecodeError as api_response_decode_error:\n flask.abort(502, str(api_response_decode_error))\n except ApiResponseErrorList as api_response_error_list:\n if api_response_error_list.status_code == 404:\n flask.abort(404, 'No snap named {}'.format(snap_name))\n else:\n codes = [error['code'] for error in api_response_error_list.errors]\n error_messages = ', '.join(codes)\n flask.abort(502, error_messages)\n except ApiResponseError as api_response_error:\n flask.abort(502, str(api_response_error))\n except ApiError as api_error:\n flask.abort(502, str(api_error))\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n # Filter icon & screenshot urls from the media set.\n icon_urls = [\n m['url'] for m in snap_details['media']\n if m['type'] == 'icon']\n screenshot_urls = [\n m['url'] for m in snap_details['media']\n if m['type'] == 'screenshot']\n\n context = {\n \"snap_id\": snap_details['snap_id'],\n \"snap_name\": snap_details['snap_name'],\n \"snap_title\": snap_details['title'],\n \"summary\": snap_details['summary'],\n \"description\": snap_details['description'],\n \"license\": snap_details['license'],\n \"icon_url\": icon_urls[0] if icon_urls else None,\n \"publisher_name\": snap_details['publisher']['display-name'],\n \"screenshot_urls\": screenshot_urls,\n \"contact\": snap_details['contact'],\n \"website\": snap_details['website'] or '',\n \"public_metrics_enabled\": snap_details['public_metrics_enabled'],\n \"public_metrics_blacklist\": snap_details['public_metrics_blacklist'],\n }\n\n return flask.render_template(\n 'publisher/market.html',\n **context\n )\n\n\ndef snap_release(snap_name):\n try:\n snap_id = api.get_snap_id(snap_name, flask.session)\n except ApiTimeoutError as api_timeout_error:\n flask.abort(504, str(api_timeout_error))\n except ApiResponseDecodeError as api_response_decode_error:\n flask.abort(502, str(api_response_decode_error))\n except ApiResponseErrorList as api_response_error_list:\n if api_response_error_list.status_code == 404:\n flask.abort(404, 'No snap named {}'.format(snap_name))\n else:\n codes = [error['code'] for error in api_response_error_list.errors]\n error_messages = ', '.join(codes)\n flask.abort(502, error_messages)\n except ApiResponseError as api_response_error:\n flask.abort(502, str(api_response_error))\n except ApiError as api_error:\n flask.abort(502, str(api_error))\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n try:\n status_json = api.get_snap_status(snap_id, flask.session)\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n return flask.render_template(\n 'publisher/release.html',\n snap_name=snap_name,\n status=status_json,\n )\n\n\ndef build_image_info(image, image_type):\n \"\"\"\n Build info json structure for image upload\n Return json oject with useful informations for the api\n \"\"\"\n hasher = hashlib.sha256(image.read())\n hash_final = hasher.hexdigest()\n image.seek(0)\n\n return {\n \"key\": image.filename,\n \"type\": image_type,\n \"filename\": image.filename,\n \"hash\": hash_final\n }\n\n\ndef post_market_snap(snap_name):\n changes = None\n changed_fields = flask.request.form['changes']\n\n if changed_fields:\n changes = loads(changed_fields)\n\n if changes:\n snap_id = flask.request.form['snap_id']\n error_list = []\n info = []\n images_files = []\n images_json = None\n\n if 'images' in changes:\n # Add existing screenshots\n try:\n current_screenshots = api.snap_screenshots(\n snap_id,\n flask.session\n )\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n changed_screenshots = changes['images']\n\n for changed_screenshot in changed_screenshots:\n for current_screenshot in current_screenshots:\n if changed_screenshot['url'] == current_screenshot['url']:\n info.append(current_screenshot)\n\n # Add new icon\n icon = flask.request.files.get('icon')\n if icon is not None:\n info.append(build_image_info(icon, 'icon'))\n images_files.append(icon)\n\n # Add new screenshots\n new_screenshots = flask.request.files.getlist('screenshots')\n for new_screenshot in new_screenshots:\n for changed_screenshot in changed_screenshots:\n is_same = (\n changed_screenshot['status'] == 'new' and\n changed_screenshot['name'] == new_screenshot.filename\n )\n\n if is_same:\n info.append(\n build_image_info(new_screenshot, 'screenshot')\n )\n images_files.append(new_screenshot)\n\n images_json = {'info': dumps(info)}\n try:\n screenshots_response = api.snap_screenshots(\n snap_id,\n flask.session,\n images_json,\n images_files\n )\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n if 'error_list' in screenshots_response:\n error_list = error_list + screenshots_response['error_list']\n\n whitelist = [\n 'title',\n 'summary',\n 'description',\n 'contact',\n 'website',\n 'keywords',\n 'license',\n 'price',\n 'blacklist_countries',\n 'whitelist_countries',\n 'public_metrics_enabled',\n 'public_metrics_blacklist'\n ]\n\n body_json = {\n key: changes[key]\n for key in whitelist if key in changes\n }\n\n if body_json:\n if 'public_metrics_blacklist' in body_json:\n # if metrics blacklist was changed, split it into array\n metrics_blacklist = body_json['public_metrics_blacklist']\n\n if len(metrics_blacklist) > 0:\n metrics_blacklist = metrics_blacklist.split(',')\n else:\n metrics_blacklist = []\n\n body_json['public_metrics_blacklist'] = metrics_blacklist\n\n if 'description' in body_json:\n # remove invalid characters from description\n body_json['description'] = (\n body_json['description'].replace('\\r\\n', '\\n')\n )\n\n try:\n metadata = api.snap_metadata(\n flask.request.form['snap_id'],\n flask.session,\n body_json\n )\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n if 'error_list' in metadata:\n error_list = error_list + metadata['error_list']\n\n if error_list:\n try:\n snap_details = api.get_snap_info(snap_name, flask.session)\n except ApiTimeoutError as api_timeout_error:\n flask.abort(504, str(api_timeout_error))\n except ApiResponseDecodeError as api_response_decode_error:\n flask.abort(502, str(api_response_decode_error))\n except ApiResponseErrorList as api_response_error_list:\n if api_response_error_list.status_code == 404:\n flask.abort(404, 'No snap named {}'.format(snap_name))\n else:\n errors = api_response_error_list.errors\n codes = [error['code'] for error in errors]\n error_messages = ', '.join(codes)\n flask.abort(502, error_messages)\n except ApiResponseError as api_response_error:\n flask.abort(502, str(api_response_error))\n except ApiError as api_error:\n flask.abort(502, str(api_error))\n except MacaroonRefreshRequired:\n return refresh_redirect(\n flask.request.path\n )\n\n details_metrics_enabled = snap_details['public_metrics_enabled']\n details_blacklist = snap_details['public_metrics_blacklist']\n\n field_errors = {}\n other_errors = []\n\n for error in error_list:\n if (error['code'] == 'invalid-field' or\n error['code'] == 'required'):\n field_errors[error['extra']['name']] = error['message']\n else:\n other_errors.append(error)\n\n website = (\n changes['website'] if 'website' in changes\n else snap_details['website']\n )\n\n # Filter icon & screenshot urls from the media set.\n icon_urls = [\n m['url'] for m in snap_details['media']\n if m['type'] == 'icon']\n screenshot_urls = [\n m['url'] for m in snap_details['media']\n if m['type'] == 'screenshot']\n\n context = {\n # read-only values from details API\n \"snap_id\": snap_details['snap_id'],\n \"snap_name\": snap_details['snap_name'],\n \"license\": snap_details['license'],\n \"icon_url\": icon_urls[0] if icon_urls else None,\n \"publisher_name\": snap_details['publisher']['display-name'],\n \"screenshot_urls\": screenshot_urls,\n \"public_metrics_enabled\": details_metrics_enabled,\n \"public_metrics_blacklist\": details_blacklist,\n \"display_title\": snap_details['title'],\n # values posted by user\n \"snap_title\": (\n changes['title'] if 'title' in changes\n else snap_details['title']\n ),\n \"summary\": (\n changes['summary'] if 'summary' in changes\n else snap_details['summary']\n ),\n \"description\": (\n changes['description'] if 'description' in changes\n else snap_details['description']\n ),\n \"contact\": (\n changes['contact'] if 'contact' in changes\n else snap_details['contact']\n ),\n \"website\": website or '',\n # errors\n \"error_list\": error_list,\n \"field_errors\": field_errors,\n \"other_errors\": other_errors\n }\n\n return flask.render_template(\n 'publisher/market.html',\n **context\n )\n\n flask.flash(\"Changes applied successfully.\", 'positive')\n else:\n flask.flash(\"No changes to save.\", 'information')\n\n return flask.redirect(\n \"/account/snaps/{snap_name}/market\".format(\n snap_name=snap_name\n )\n )\n","sub_path":"modules/publisher/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"443346201","text":"import socket\n\nserver_ip = '127.0.0.1'\nserver_port = 5000\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \n\nserver.bind((server_ip, server_port)) \n\nwhile(True):\n data, address = server.recvfrom(4096)\n\n if(data.decode()[1:] == \"exit()\"):\n break\n\n equation = eval(data.decode()[0:])\n\n print( str(address) + \">> \" + data.decode()[0:] + \" = \" + str(equation))\n\n server.sendto(str(equation).encode(), address)\n \nserver.close()\n\n\n\n","sub_path":"Giavelli/calcolatriceServer.py","file_name":"calcolatriceServer.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"67171486","text":"#/usr/local/bin/python3\n# -*- coding: utf-8 -*-\nimport os\n\ndef load_data(path, file):\n file_name = path+\"/input/\"+file\n with open(file_name, \"r\") as fp :\n temp = list()\n while True:\n line = fp.readline()\n line = line[:-1]\n if not line : break\n temp.append(line.split(','))\n \n field = temp[0]\n del temp[0]\n print (\"============================\")\n print (\"Loading Data... DONE :)\")\n print (\"Field in Data : {}\".format(field))\n print (\"Example in Data : {}\".format(temp[0]))\n\n return temp, field\n\n","sub_path":"algorithm/Assignment-1/src/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134837813","text":"#!/usr/bin/env python\n# vim:fileencoding=utf-8\n\nfrom colorsys import rgb_to_hsv, hsv_to_rgb\nfrom math import ceil\n\n__all__ = ['hex2rgb',\n 'rgb2hex',\n 'light',\n 'dark',\n ]\n\ndef hex2rgb(hexcolor):\n rgb = [(hexcolor >> 16) & 0xff,\n (hexcolor >> 8) & 0xff,\n hexcolor & 0xff\n ]\n return rgb\n\ndef rgb2hex(rgbcolor):\n #return '0x%02x%02x%02x' % rgbcolor\n r, g, b = rgbcolor\n # notice '<<' has lower precedence than '+'\n return (r << 16) + (g << 8) + b\n\ndef light(color):\n color = map(lambda x: x/float(255), color)\n hsv = list(rgb_to_hsv(*color))\n hsv[2] *= 1.5\n color = hsv_to_rgb(*hsv)\n return map(lambda x:\n 255 if int(ceil(x*255)) >= 255 else int(ceil(x*255)), color)\n\ndef dark(color):\n color = map(lambda x: x/float(255), color)\n hsv = list(rgb_to_hsv(*color))\n hsv[2] *= 2\n color = hsv_to_rgb(*hsv)\n return map(lambda x:\n 255 if int(ceil(x*255)) >= 255 else int(ceil(x*255)), color)","sub_path":"public/assets/Templates/RGB2hex.py","file_name":"RGB2hex.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"146670302","text":"from flask import Flask, render_template, request, redirect, url_for, flash, session, make_response,Response,jsonify\nfrom app import app,db,appbuilder\nfrom datetime import datetime,date\nimport random\nimport string\nfrom dateutil.relativedelta import relativedelta\n\nfrom app.users.models import MyUser\nfrom app.plan_usua.models import PlanUsua\nfrom app.lotes.models import Lote\nfrom app.partediarioriego.models import Partediarioriego\nfrom app.plantaequipos.models import Plantaequipo\nfrom app.superequipos.models import Superequipo\nfrom app.tipoequipos.models import Tipoequipo\nfrom app.numturno.models import Numturno\nfrom app.partediariolote.models import Partediariolote\nfrom app.partediariotractor.models import Partediariotractor\n\n\n\nimport pytz\ntz = pytz.timezone('America/Argentina/Buenos_Aires')\n\n\n@app.route('/partediarioriegoview/add')\ndef Partediario_riego_add():\n usuario_session=str(session['user_id'])\n idplanta_session=str(session['idPlanta'])\n usuarios=db.session.query(MyUser.id,MyUser.first_name,MyUser.last_name,MyUser.numerodniUser).join(PlanUsua,PlanUsua.idUsuario==MyUser.id).filter(PlanUsua.idPlanta==idplanta_session).filter(PlanUsua.activoPlan_usua==1).all()\n lotes=db.session.query(Lote).filter(Lote.idPlanta==idplanta_session).all()\n tractores=db.session.query(Plantaequipo.idPlantaequipo,Plantaequipo.idSuperequipo,Plantaequipo.nombrePlantaequipo).join(Superequipo,Superequipo.idSuperequipo==Plantaequipo.idSuperequipo).join(Tipoequipo,Tipoequipo.idTipoequipo==Superequipo.idTipoequipo).filter(Superequipo.idTipoequipo==4).filter(Plantaequipo.idPlanta==idplanta_session).all()\n turnos=db.session.query(Numturno).all()\n print(\"LISTA DE TRACTORES ================>\",tractores)\n return render_template('partediarioriego.html',usuarios=usuarios,lotes=lotes,tractores=tractores,turnos=turnos,base_template=appbuilder.base_template, appbuilder=appbuilder)\n\n@app.route('/guardarParteDiarioRiego',methods=['POST'])\ndef Partediario_riego_guardar():\n if request.method=='POST':\n usuario_session=str(session['user_id'])\n idplanta_session=str(session['idPlanta'])\n usuarios=db.session.query(MyUser.id,MyUser.first_name,MyUser.last_name,MyUser.numerodniUser).join(PlanUsua,PlanUsua.idUsuario==MyUser.id).filter(PlanUsua.idPlanta==idplanta_session).filter(PlanUsua.activoPlan_usua==1).all()\n lotes=db.session.query(Lote).filter(Lote.idPlanta==idplanta_session).all()\n tractores=db.session.query(Plantaequipo.idPlantaequipo,Plantaequipo.idSuperequipo,Plantaequipo.nombrePlantaequipo).join(Superequipo,Superequipo.idSuperequipo==Plantaequipo.idSuperequipo).join(Tipoequipo,Tipoequipo.idTipoequipo==Superequipo.idTipoequipo).filter(Superequipo.idTipoequipo==4).filter(Plantaequipo.idPlanta==idplanta_session).all()\n turnos=db.session.query(Numturno).all()\n fecha=request.form['fecha']\n print(fecha)\n turno=request.form['idNumturno']\n print(turno)\n usuario=request.form['idUsuarioOP']\n print(usuario)\n observaciones=request.form['Observaciones']\n print(observaciones)\n fechacarga=datetime.now(tz)\n \n #VERIFICO QUE NO EXISTA PARTE EN LA FECHA SELECCIONADA\n partediario_turno=db.session.query(Partediarioriego).filter(Partediarioriego.idPlanta==idplanta_session).filter(Partediarioriego.fechaPartediarioriego==fecha).filter(Partediarioriego.idNumturno==turno).all()\n \n if partediario_turno:\n flash(\"Ya existe un parte para dicha fecha y turno\",\"danger\")\n return redirect(url_for('Partediario_riego_add'))\n\n\n #CREO LA SUPERCLASE Partediarioriego\n new_parteriego=(Partediarioriego(idplanta_session,fecha,observaciones,usuario,usuario_session,fechacarga,turno))\n db.session.add(new_parteriego)\n db.session.commit()\n #OBTENGO EL ID \n ultimoparteriego_id=db.session.query(Partediarioriego).filter(Partediarioriego.idPlanta==idplanta_session).order_by(Partediarioriego.idPartediarioriego.desc()).first()\n print (ultimoparteriego_id.idPartediarioriego)\n ultimoid=ultimoparteriego_id.idPartediarioriego\n\n for lote in lotes:\n solidoLote=request.form[f'solido_{lote.idLote}']\n liquidoLote=request.form[f'liquido_{lote.idLote}']\n new_partelote=(Partediariolote(lote.idLote,solidoLote,liquidoLote,ultimoid))\n db.session.add(new_partelote)\n db.session.commit()\n\n for tractor in tractores:\n horasTractor=request.form[f'horas_{tractor.idPlantaequipo}']\n litrosTractor=request.form[f'litros_{tractor.idPlantaequipo}']\n print(horasTractor,litrosTractor)\n return render_template('partediarioriego.html',usuarios=usuarios,lotes=lotes,tractores=tractores,turnos=turnos,base_template=appbuilder.base_template, appbuilder=appbuilder)\n\n\n\n\n@app.route('/partediarioriegoview/show')\ndef listado_parte_riego():\n print(\"ENTRO\")\n return render_template('listadoriegolote.html', base_template=appbuilder.base_template, appbuilder=appbuilder) ","sub_path":"app/partediarioriego/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":5083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"497604045","text":"# In[94]:\n\nfrom sage.all_cmdline import *\n\nimport pandas as pd\nimport numpy as np\nload(\"conjecturing.py\")\n\n\ndef run_conjecturing(my_timelimit=5, num_samples=10, data_fname=\"/home/jpbrooks/craig/learning/2021_04_aif/Feynman_with_units/I.10.7\", invariant_names=[\"m0\", \"v\", \"c\", \"m\"], use_pi=False, out_fname=\"I.10.7\", operators=['+','-'], noise = 0):\n\n print(out_fname)\n print(operators)\n print(noise)\n my_data = pd.read_csv(data_fname,\n sep=\"\\\\s+\",\n header=None)\n\n #my_data.loc[:,len(my_data.columns)-1] = my_data.loc[:,len(my_data.columns)-1] + rg.normal(0, noise, len(my_data.index))\n my_data.loc[:,len(my_data.columns)-1] = my_data.loc[:,len(my_data.columns)-1] + np.random.normal(0, noise, len(my_data.index))\n \n my_data.rename(columns={i:invariant_names[i] for i in range(len(invariant_names))}, inplace=True)\n my_data\n \n class Example():\n def __init__(self, row):\n self.name = row.name\n \n def build_inv(i):\n def inv(self):\n return my_data.loc[self.name,i]\n inv.__name__ = i\n return inv\n \n for i in invariant_names:\n inv = build_inv(i)\n setattr(Example, inv.__name__, inv)\n \n my_examples = (\n my_data\n .iloc[range(Integer(num_samples)),]\n .apply(func=Example, axis='columns')\n )\n \n my_examples_list = my_examples.tolist()\n \n test_examples = (\n my_data\n .iloc[num_samples:(num_samples+100),]\n .apply(func=Example, axis='columns')\n )\n test_examples_list = test_examples.tolist()\n \n \n invariants = []\n for i in invariant_names:\n invariants.append(Example.__dict__[i])\n target_invariant = Example.__dict__[invariant_names[len(invariant_names)-1]]\n \n if use_pi == True:\n _sage_const_pi = pi\n \n def my_pi(dist):\n R = RealField(20)\n return R(_sage_const_pi)\n invariants.append(my_pi)\n \n _sage_const_p0 = RealNumber('.00000001')\n def my_const(example):\n return _sage_const_p0\n invariants.append(my_const)\n \n set_random_seed(12345)\n #use_operators = {'+', '*', '-', '/', '+1', '-1', 'sqrt', 'exp', \n # 'ln', '1/', 'cos', 'abs', 'asin', 'atan', 'sin',\n # '^2'}\n use_operators = operators\n \n out_file = open(out_fname, \"a\")\n \n inv_of_interest = invariants.index(target_invariant)\n conjs = conjecture(my_examples,\n invariants,\n inv_of_interest,\n operators=use_operators,\n upperBound=True,\n debug=True,\n time=my_timelimit,\n verbose=True)\n convert_conjecture_names(conjs)\n for c in conjs:\n try:\n error = sum([abs(example.m() - c.evaluate(example, returnBoundValue=True)) for example in test_examples_list])/len(test_examples_list)\n out_file.write(\"%s,%s,%d,%d,%d,%f,%f\\n\" % (out_fname, c, my_timelimit, len(my_examples), len(operators), noise, error))\n except:\n print(c)\n out_file.write(\"%s,%s,%d,%d,%d,%f\\n\" % (out_fname, c, my_timelimit, len(my_examples), len(operators), noise))\n \n conjs = conjecture(my_examples,\n invariants,\n inv_of_interest,\n operators=use_operators,\n upperBound=False,\n debug=True,\n time=my_timelimit,\n verbose=True)\n convert_conjecture_names(conjs)\n for c in conjs:\n try:\n error = sum([abs(example.m() - c.evaluate(example, returnBoundValue=True)) for example in test_examples_list])/len(test_examples_list)\n out_file.write(\"%s,%s,%d,%d,%d,%f,%f\\n\" % (out_fname, c, my_timelimit, len(my_examples), len(operators), noise, error))\n except:\n print(c)\n out_file.write(\"%s,%s,%d,%d,%d,%f\\n\" % (out_fname, c, my_timelimit, len(my_examples), len(operators), noise))\n out_file.flush()\n out_file.close()\n \ninstances = [\"I.6.2a\", \"I.6.2\", \"I.6.2b\", \"I.8.14\", \"I.9.18\", \"I.10.7\", \"I.11.19\", \"I.12.1\", \"I.12.2\", \"I.12.4\"]\ninvariant_dict = {\"I.6.2a\": [\"theta\", \"f\"],\n\"I.6.2\": [\"sigma\", \"theta\", \"f\"],\n\"I.6.2b\": [\"sigma\", \"theta\", \"theta1\", \"f\"],\n\"I.8.14\": [\"x1\", \"x2\", \"y1\", \"y2\", \"d\"],\n\"I.9.18\": [\"m1\", \"m2\", \"G\", \"x1\", \"x2\", \"y1\", \"y2\", \"z1\", \"z2\", \"F\"],\n\"I.10.7\": [\"m0\", \"v\", \"c\", \"m\"],\n\"I.11.19\": [\"x1\", \"x2\", \"x3\", \"y1\", \"y2\", \"y3\", \"dot\"],\n\"I.12.1\": [\"mu\", \"Nn\", \"F\"],\n\"I.12.2\": [\"q1\", \"q2\", \"epsilon\", \"r\", \"F\"],\n\"I.12.4\": [\"q1\", \"epsilon\", \"r\", \"F\"]}\npi_dict = {\"I.6.2a\": True,\n\"I.6.2\": True,\n\"I.6.2b\": True,\n\"I.8.14\": False,\n\"I.9.18\": False,\n\"I.10.7\": False,\n\"I.11.19\": False,\n\"I.12.1\": False,\n\"I.12.2\": True,\n\"I.12.4\": True}\naif_time = {\"I.6.2a\": 16,\n\"I.6.2\": 2992,\n\"I.6.2b\": 4792,\n\"I.8.14\": 544,\n\"I.9.18\": 5975,\n\"I.10.7\": 14,\n\"I.11.19\": 184,\n\"I.12.1\": 12,\n\"I.12.2\": 17,\n\"I.12.4\": 12}\naif_points = {\"I.6.2a\": 10,\n\"I.6.2\": 100,\n\"I.6.2b\": 1000,\n\"I.8.14\": 100,\n\"I.9.18\": 1000,\n\"I.10.7\": 10,\n\"I.11.19\": 100,\n\"I.12.1\": 10,\n\"I.12.2\": 10,\n\"I.12.4\": 10}\naif_noise = {\"I.6.2a\": 0.01,\n\"I.6.2\": 0.0001,\n\"I.6.2b\": 0.0001,\n\"I.8.14\": 0.0001,\n\"I.9.18\": 0.00001,\n\"I.10.7\": 0.0001,\n\"I.11.19\": 0.001,\n\"I.12.1\": 0.001,\n\"I.12.2\": 0.01,\n\"I.12.4\": 0.01}\nloc = \"/home/jpbrooks/craig/learning/2021_04_aif\"\n\noperator_lists = [ \n['+', '-', '*', '/', '+1', '-1', '^2', 'sqrt'],\n['+', '-', '*', '/', '+1', '-1', 'sin', 'ln', '1/', 'cos', 'exp', 'sqrt', '^2'],\n['+', '-', '*', '/', '+1', '-1', 'sqrt', 'exp', 'ln', '1/', 'cos', 'abs', 'asin', 'atan', 'sin', '^2']]\n\n\nnp.random.seed(12345)\n\nfor instance in instances:\n for operator_list in operator_lists:\n for noise in [0,0.1]:\n run_conjecturing(my_timelimit=5, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list, noise=noise)\n run_conjecturing(my_timelimit=aif_time[instance], num_samples=aif_points[instance], data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list)\n run_conjecturing(my_timelimit=100, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list, noise=noise)\n run_conjecturing(my_timelimit=1000, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list, noise=noise)\n \nfor instance in instances:\n for operator_list in operator_lists:\n run_conjecturing(my_timelimit=5, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list, noise=aif_noise[instance])\n run_conjecturing(my_timelimit=aif_time[instance], num_samples=aif_points[instance], data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list, noise=aif_noise[instance])\n run_conjecturing(my_timelimit=100, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+instance, operators=operator_list, noise=aif_noise[instance])\n\n\nfor instance in instances:\n for operator_list in operator_lists:\n for noise in [0,0.1]:\n print(instance)\n print(operator_list)\n print(noise)\n run_conjecturing(my_timelimit=10000, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+\"/\"+instance, operators=operator_list, noise=noise)\n run_conjecturing(my_timelimit=100000, num_samples=10, data_fname=loc +\"/Feynman_with_units/\" + instance, invariant_names=invariant_dict[instance], use_pi=pi_dict[instance], out_fname=loc+\"/\"+instance, operators=operator_list, noise=noise)\n \n\n","sub_path":"examples/AI-Feynman/run_conjecturing_serial.py","file_name":"run_conjecturing_serial.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"8888827","text":"#regression project\nfrom torch.utils.data.dataset import Dataset\nimport torch\nfrom Deeplearning.Cnn_project.Paint.bri057 import Regression_model\nfrom Deeplearning.Cnn_project.Paint.bri053 import NKDataSet\nfrom tensorboardX import SummaryWriter\nimport os\n\ndef save_checkpoint(state,filename='checkpoint.pth.bar'):\n torch.save(state,filename)\n\ndef accuracy(output, target, topk=(1, )):\n maxk = max(topk)\n batch_size = target.size(0)\n\n _,pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1,-1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n\n return res\nclass AverageMeter(object):\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self,val,n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef train(my_dataset_loader,model,criterion,optimizer,epoch,writer):\n model.train()\n losses = AverageMeter()\n for i, data in enumerate(my_dataset_loader, 0):\n\n images, label = data\n images = torch.autograd.Variable(images)\n label = torch.autograd.Variable(label).float()\n y_pred = model(images)\n loss = criterion(y_pred,label)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n loss = loss.float()\n losses.update(loss.item(), images.size(0))\n\n losses = AverageMeter()\n\n for i, data in enumerate(my_dataset_loader, 0):\n\n images, label = data\n\n images = torch.autograd.Variable(images)\n label = torch.autograd.Variable(label).float()\n\n y_pred = model(images)\n\n loss = criterion(y_pred,label)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n loss = loss.float()\n\n\n\n losses.update(loss.item(), images.size(0))\n writer.add_scalar('Train/loss',losses.avg, epoch)\n\n\ndef test(my_dataset_loader, model, criterion, epoch, test_writer):\n\n losses = AverageMeter()\n\n model.eval()\n for i, data in enumerate(my_dataset_loader, 0):\n\n images, label = data\n y_pred = model(images)\n label = label.float()\n loss = criterion(y_pred, label)\n loss = loss.float()\n losses.update(loss.item(), images.size(0))\n\n\n print(' *, epoch : {epoch:.2f} Prec@1 {losses .avg:.3f}'\n .format(epoch = epoch,losses=losses))\n\n test_writer.add_scalar('Test/loss', losses.avg, epoch)\n\ncsv_path = './data_load/train.csv'\ncustom_dataset = NKDataSet(csv_path)\n\ncsv_path = './data_load/data_load.csv'\n\ncustom_dataset = NKDataSet(csv_path)\n\nmy_dataset_loader = torch.utils.data.DataLoader(dataset=custom_dataset,\n batch_size=2,\n shuffle=True,\n num_workers=1)\ncsv_path = './data_load/test.csv'\ncustom_dataset = NKDataSet(csv_path)\ntest_dataset_loader = torch.utils.data.DataLoader(dataset=custom_dataset,\n batch_size=2,\n shuffle=True,\n num_workers=1)\nmodel = Regression_model()\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(),lr=1e-1)\n\nwriter = SummaryWriter('./log_2')\ntest_writer = SummaryWriter('.log_2/test')\nfor epoch in range(500):\n train(my_dataset_loader,model,criterion,optimizer,epoch,writer)\n test(test_dataset_loader,model,criterion,epoch,test_writer)\n\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model.state_dict()\n }, filename=os.path.join(\"./save_dir\", 'checkpoint_{}.tar'.format(epoch)))\n\n# 84199e+4(841,990,000)\n# 10575e+5(1,057,500,000)\n\nmodel = Regression_model()\n\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(),lr=1e-2)\n\nwriter = SummaryWriter('./log')\ntest_writer = SummaryWriter('.log/test')\nfor epoch in range(500):\n train(my_dataset_loader,model,criterion,optimizer,epoch,writer)\n test(my_dataset_loader,model,criterion,epoch,test_writer)\n","sub_path":"Deeplearning/regression_project/regression_project.py","file_name":"regression_project.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"394710434","text":"\"\"\"\n (c) 2020 Rodney Maniego Jr.\n graphby\n\"\"\"\nimport sys\n\nclass Bar:\n def __init__(self, categories, values, bar=None, limit=10):\n \"\"\"\n Read and prepare the JSON/Dictionary object.\n ...\n Parameters\n ---\n categories: list\n any list of string to label each corresponding values\n values: list\n any list numeric values (positive)\n bar: string\n any character to use in the bar graph for each increment\n limit: int\n max scale of the bar graph\n \"\"\"\n self.categories = categories\n self.limit = get_int(limit)\n self.values = values\n self.normalized = normalize(self.values, self.limit)\n if len(self.categories) != len(self.values):\n print(\"Labels and values doesn't match in size.\")\n sys.exit(0)\n self.bar = bar\n if self.bar == None or len(bar) != 1:\n self.bar = \"*\"\n\n def plot(self):\n fvalues = []\n for value in self.values:\n fvalues.append(str(value))\n max_numbers = longest(fvalues)\n max_letters = longest(self.categories)\n for label, reduced, value in zip(self.categories, self.normalized, fvalues):\n # padd labels\n limit = max_letters - len(label)\n for count in range(0, limit):\n label = f\"{label} \"\n # increment bars\n bar = \"\"\n for count in range(0, reduced):\n bar = f\"{bar}{self.bar}\"\n limit = self.limit - len(bar)\n for count in range(0, limit):\n bar = f\"{bar} \"\n # pad values\n limit = max_numbers - len(value)\n for count in range(0, limit):\n value = f\" {value}\"\n print(f\"{label}: {bar} {value}\")\n \n\ndef normalize(values, limit=10):\n rates = []\n limit = get_int(limit)\n if limit <= 0: limit = 5 # minimum scale\n max = maximum(values)\n min = minimum(values)\n if min < 0:\n add = abs((0 - min))\n max += add\n for num in values:\n num = get_float(num)\n if min < 0:\n num += add\n rate = (num / max) * 100\n rates.append(rate)\n # normalize\n normalized = []\n sum_of_rates = maximum(rates)\n for rate in rates:\n num = round((rate / sum_of_rates) * limit)\n normalized.append(num)\n return normalized\n\ndef longest(strings):\n length = 0\n for word in strings:\n temp = len(str(word))\n if length < temp:\n length = temp\n return length\n \ndef maximum(numbers):\n temp = 0\n try:\n for num in numbers:\n num = get_float(num)\n if temp == 0: temp = num\n if temp < num: temp = num\n except:\n pass\n return temp\n\ndef minimum(numbers):\n temp = 0\n try:\n for num in numbers:\n num = get_float(num)\n if temp == 0: temp = num\n if temp > num: temp = num\n except:\n pass\n return temp\n\ndef get_int(string):\n try:\n return int(string)\n except:\n return 0\n\ndef get_float(string):\n try:\n return float(string)\n except:\n return 0","sub_path":"build/lib/graphby/graphby.py","file_name":"graphby.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"559596145","text":"import cv2\nimport numpy as np\nfrom scipy import ndimage\nimport math\n\ndef on_EVENT_LBUTTONDOWN(event, x, y,flags, param):\n # 点击三次,获得三个位置的坐标,销毁窗口\n if event == cv2.EVENT_LBUTTONDOWN:\n xy = \"%d,%d\" % (x, y)\n a.append(x)\n b.append(y)\n cv2.circle(img, (x, y), 1, (255, 0, 0), thickness=-1)\n # cv2.putText(img, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,1.0, (0, 0, 0), thickness=1)\n cv2.imshow(\"image\", img)\n\n# 获取每次点击的坐标\ndef get_three_position():\n cv2.namedWindow(\"image\")\n cv2.setMouseCallback(\"image\", on_EVENT_LBUTTONDOWN)\n cv2.imshow(\"image\", img)\n cv2.waitKey(0)\n\n print(a)\n print(b)\n\n# 旋转图片\ndef spin_img():\n # 找到眼睛倾斜角度和两眼的距离\n # 左眼坐标\n p1 = np.array([b[0],a[0]])\n # 右眼坐标\n p2 = np.array([b[1],a[1]])\n # 嘴中心坐标\n p3 = np.array([b[2],a[2]])\n\n # 根据公式计算成角度\n dp = p1 - p2\n angle = np.arctan(dp[0] / dp[1])\n\n # 旋转图片\n # 旋转图片\n rot_img = ndimage.rotate(img, angle=+angle * 180 / np.pi)\n # 旋转后图像的中点\n rot_image_center = np.array((np.array(rot_img.shape[:2]) - 1) / 2,\n dtype=np.int)\n # cv2.imshow('旋转图片',rot_img)\n # cv2.waitKey(0)\n\n # 在旋转后的图片中找到眼睛的坐标\n # 原两眼距离的中点\n org_eye_center = np.array((p1 + p2) / 2, dtype=np.int)\n # 原图像的中点\n org_image_center = np.array((np.array(img.shape[:2]) - 1) / 2, dtype=np.int)\n # 以图片中心进行旋转,在旋转后的图片中找到眼睛的中点\n R = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]])\n rot_eye_center = np.dot(R, org_eye_center[::-1]- org_image_center[::-1])[::-1] + rot_image_center\n rot_eye_center = np.array(rot_eye_center, dtype=int)\n\n print(rot_eye_center)\n # 模仿者100 * 100 裁剪图像\n\n # 两眼的距离\n l_dis = int(math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2))\n\n # 嘴巴距离眼睛中心的距离一半\n l_e_m = int(math.sqrt((p3[0]-org_eye_center[0])**2+(p3[1]-org_eye_center[1])**2)/2)\n\n # 裁剪图像\n deal_with_img = rot_img[int(rot_eye_center[0]-l_e_m):int(rot_eye_center[0]+3*l_e_m),int(rot_eye_center[1]-l_dis):int(rot_eye_center[1]+l_dis)]\n # cv2.imshow('裁剪完成图片', deal_with_img)\n # cv2.waitKey(0)\n\n # 双线性\n pc1 = cv2.resize(deal_with_img,(100, 100), interpolation=cv2.INTER_LINEAR)\n # 双三次插值\n pc2 = cv2.resize(deal_with_img,(100, 100), interpolation=cv2.INTER_CUBIC)\n\n imghstack = np.hstack((pc1,pc2))\n\n cv2.imshow('左 双线性插值 右 双三次插值',imghstack)\n cv2.waitKey(0)\n cv2.imwrite('pc1.png',pc1)\n cv2.imwrite('pc2.png', pc2)\n\ndef main():\n get_three_position()\n spin_img()\n pass\n\nif __name__ == '__main__':\n x, y = [], []\n # 使用的图像\n img = cv2.imread(r'T:\\imgs\\XL3\\hb.jpg')\n main()","sub_path":"视觉/XLwork/XL3/XL3.py","file_name":"XL3.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"492586188","text":"#!/usr/bin/env python3\n# -*-coding: utf-8-*-\n# Author : Christopher L\n# Blog : http://blog.chriscabin.com\n# GitHub : https://www.github.com/chrisleegit\n# File : 16.py\n# Date : 2016/08/12 18:16\n# Version: 0.1\n# Description: nothing here\n\nimport os\nimport sys\nfrom threading import Thread\nfrom time import sleep\n\n\"\"\"\n@Description: 序列化 Python 对象:`pickle` 模块\n\"\"\"\n\n\"\"\"\n问题:有时候需要将 Python 对象序列化成字节流,这样可以保存到文件、存储到数据库或者通过网络传输\n\n1. 最常见的序列化方法就是使用 `pickle` 模块\n1. `load`, `dump`, `loads`, `dumps`\n1. 可以对函数、类以及实例进行 pickle 处理,但由此产生的数据只会对代码对象所关联的名称进行编码\n1. 当对数据反序列化时,会假设所有需要的源文件都是可用的,共享时自然需要使用同样的源码\n1. 有些类型的对象无法 pickle,这些对象通常来说都涉及到某种外部系统状态,如打开的文件、打开的网络连接、线程、进程、帧栈等\n1. 用户自定义的类可以通过实现 `__getstate__()` 和 `__setstate__()` 方法避免限制\n1. 对于大型的数据结构,如 array/numpy 创建的二进制数组,pickle 就不是特别高效。如果需要移动大量的数组类型数据,最好简单地将数据安快保存在文件中或者使用更加标准的编码,如 HDF5\n\"\"\"\n\n\nclass CountDown(object):\n def __init__(self, start):\n self._start = start\n self._thr = Thread(target=self._run, daemon=False)\n self._thr.start()\n\n def _run(self):\n while self._start > 0:\n print('Count down: {}'.format(self._start))\n self._start -= 1\n sleep(1)\n\n def __getstate__(self):\n # for pickle support\n return self._start\n\n def __setstate__(self, start):\n # for pickle support\n self.__init__(start)\n\n\ndef main():\n import pickle\n import math\n\n print(pickle.dumps(math.sin))\n\n # 支持 pickle 操作的线程\n # c = CountDown(30)\n #\n # sleep(5)\n # f = open('state.pk', 'wb')\n # pickle.dump(c, f)\n\n f = open('state.pk', 'rb')\n\n # 你会发现,计时器会从停止的地方继续倒数\n c = pickle.load(f)\n print(c)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"chapter05/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"96986378","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfeatures = pd.read_csv('../data/dengue_features_train.csv', parse_dates=[3])\n# print(features)\n\nfeatures_iq = features[features['city'] == 'iq']\nfeatures_sj = features[features['city'] == 'sj']\n\n# print(features_sj)\n# print(features_iq)\n\nfig, ax = plt.subplots(figsize=(10,6))\nsns.heatmap(features_iq.isnull().reset_index(drop=True),ax=ax, cbar = False, yticklabels = 50)\n\nplt.ylabel(\"Row number\", size = 22)\nplt.xlabel(\"Feature name\", size = 22)\nplt.title(\"Iquitos Missing Data\", size = 32)\n# plt.show()\n\nfig, ax = plt.subplots(figsize=(10,6))\nsns.heatmap(features_sj.isnull(),ax=ax, cbar = False, yticklabels = 50)\n\nplt.ylabel(\"Row number\", size = 22)\nplt.xlabel(\"Feature name\", size = 22)\nplt.title(\"San Juan Missing Data\", size = 32)\n# plt.show()\n\nfeatures_iq_mean = features_iq.mean()\nfeatures_sj_mean = features_sj.mean()\n\n# Cleaning the data\nfeatures_sj = features_sj.fillna(features_sj_mean)\nfeatures_iq = features_iq.fillna(features_iq_mean)\n\n# print(features_sj)\n# print(features_iq)\n\n# drop non-numerical values\nfeatures_sj.drop(['city', 'year'], axis = 1, inplace = True)\nfeatures_iq.drop(['city', 'year'], axis = 1, inplace = True)\n\n# Saving the cleaned data\nfeatures_sj.to_csv(\"../data/features_sj.csv\")\nfeatures_iq.to_csv(\"../data/features_iq.csv\")\n\n","sub_path":"Code/1_data_cleaning.py","file_name":"1_data_cleaning.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"351882410","text":"from flask import jsonify, abort, request, current_app\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app.main import main\nfrom app.models import db, Project, AuditEvent\nfrom app.utils import (\n get_json_from_request, json_has_required_keys, get_int_or_400,\n pagination_links, get_valid_page_or_1, url_for,\n get_positive_int_or_400, validate_and_return_updater_request\n)\n\nfrom app.service_utils import validate_and_return_supplier\n\nfrom dmapiclient.audit import AuditTypes\n\n\ndef get_project_json():\n json_payload = get_json_from_request()\n json_has_required_keys(json_payload, ['project'])\n return json_payload['project']\n\n\ndef save_project(project):\n db.session.add(project)\n db.session.commit()\n\n\n@main.route('/projects', methods=['POST'])\ndef create_project():\n project_json = get_project_json()\n\n project = Project(\n data=project_json\n )\n save_project(project)\n\n return jsonify(project=project.serialize()), 201\n\n\n@main.route('/projects/', methods=['PATCH'])\ndef update_project(project_id):\n project_json = get_project_json()\n\n project = Project.query.get(project_id)\n if project is None:\n abort(404, \"Project '{}' does not exist\".format(project_id))\n\n project.update_from_json(project_json)\n save_project(project)\n\n return jsonify(project=project.serialize()), 200\n\n\n@main.route('/projects/', methods=['GET'])\ndef get_project(project_id):\n project = Project.query.filter(\n Project.id == project_id\n ).first_or_404()\n\n return jsonify(project=project.serialize())\n\n\n@main.route('/projects', methods=['GET'])\ndef list_projects():\n page = get_valid_page_or_1()\n\n projects = Project.query\n\n results_per_page = get_positive_int_or_400(\n request.args,\n 'per_page',\n current_app.config['DM_API_PAGE_SIZE']\n )\n\n projects = projects.paginate(\n page=page,\n per_page=results_per_page\n )\n\n return jsonify(\n projects=[project.serialize() for project in projects.items],\n links=pagination_links(\n projects,\n '.list_projects',\n request.args\n )\n )\n","sub_path":"app/main/views/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"188029613","text":"# -*- coding: utf-8 -*-\n\"\"\"Software update plist plugin.\"\"\"\n\nfrom dfdatetime import posix_time as dfdatetime_posix_time\n\nfrom plaso.containers import plist_event\nfrom plaso.containers import time_events\nfrom plaso.lib import definitions\nfrom plaso.lib import timelib\nfrom plaso.parsers import plist\nfrom plaso.parsers.plist_plugins import interface\n\n\n__author__ = 'Joaquin Moreno Garijo (Joaquin.MorenoGarijo.2013@live.rhul.ac.uk)'\n\n\nclass SoftwareUpdatePlugin(interface.PlistPlugin):\n \"\"\"Basic plugin to extract the Mac OS X update status.\n\n Further details about the extracted fields:\n LastFullSuccessfulDate:\n timestamp when Mac OS X was full update.\n LastSuccessfulDate:\n timestamp when Mac OS X was partially update.\n \"\"\"\n\n NAME = u'maxos_software_update'\n DESCRIPTION = u'Parser for Mac OS X software update plist files.'\n\n PLIST_PATH = u'com.apple.SoftwareUpdate.plist'\n PLIST_KEYS = frozenset([\n u'LastFullSuccessfulDate', u'LastSuccessfulDate',\n u'LastAttemptSystemVersion', u'LastUpdatesAvailable',\n u'LastRecommendedUpdatesAvailable', u'RecommendedUpdates'])\n\n def GetEntries(self, parser_mediator, match=None, **unused_kwargs):\n \"\"\"Extracts relevant Mac OS X update entries.\n\n Args:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.\n \"\"\"\n version = match.get(u'LastAttemptSystemVersion', u'N/A')\n pending = match.get(u'LastUpdatesAvailable', None)\n\n event_data = plist_event.PlistTimeEventData()\n event_data.desc = u'Last Mac OS X {0:s} full update.'.format(version)\n event_data.key = u''\n event_data.root = u'/'\n\n datetime_value = match.get(u'LastFullSuccessfulDate', None)\n if datetime_value:\n timestamp = timelib.Timestamp.FromPythonDatetime(datetime_value)\n date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n datetime_value = match.get(u'LastSuccessfulDate', None)\n if datetime_value and pending:\n software = []\n for update in match.get(u'RecommendedUpdates', []):\n identifier = update.get(u'Identifier', u'')\n product_key = update.get(u'Product Key', u'')\n\n software.append(u'{0:s}({1:s})'.format(identifier, product_key))\n\n if not software:\n return\n\n software = u','.join(software)\n event_data.desc = (\n u'Last Mac OS {0!s} partially update, pending {1!s}: '\n u'{2:s}.').format(version, pending, software)\n\n timestamp = timelib.Timestamp.FromPythonDatetime(datetime_value)\n date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n\nplist.PlistParser.RegisterPlugin(SoftwareUpdatePlugin)\n","sub_path":"plaso/parsers/plist_plugins/softwareupdate.py","file_name":"softwareupdate.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"549106168","text":"import requests\nimport urllib.parse\nimport datetime\nimport csv\nimport threading\nfrom dateutil.relativedelta import relativedelta\n\n\n# 获取某一天的某个排名区间\ndef get_rank_list(connection, date, token, rankRange):\n headers = {\n 'X-BEE-COUNTRY': '0',\n 'X-CSRF-TOKEN': token,\n }\n postData = {\n # 1:免费榜 2:付费榜 3:畅销榜\n 'listCat': 2,\n 'listType': 0,\n 'rankRange': rankRange,\n 'listDate': date,\n }\n\n response = connection.post(\"http://fsight.qq.com/GameListAjax\", data=postData, headers=headers)\n return response.json().get('ret').get('ranks')\n\n\n# 存储csv文件\ndef save_csv(file_name, data):\n with open(file_name + \".csv\", \"w\", newline=\"\", encoding='utf-8') as w:\n writer = csv.writer(w)\n for row in data:\n writer.writerow(row)\n\n\n# 获取某段时间每天排名前300的APP信息\ndef get_top_100(dateStart, dateEnd):\n connection = requests.session()\n connection.get(\"http://fsight.qq.com/GameList?type=hotRank\")\n token = urllib.parse.unquote(connection.cookies.get('wetest_token'))\n\n # dateStart, dateEnd = datetime.date(2016, 4, 27), datetime.date(2018, 4, 27)\n date = dateStart\n res_sum = []\n id_name_dic = {}\n while date < dateEnd:\n print(date)\n\n rank_1_30 = get_rank_list(connection, date, token, 1)\n rank_31_200 = get_rank_list(connection, date, token, 2)\n\n res = list(rank_1_30) + list(rank_31_200)\n date += datetime.timedelta(days=1)\n res = res[0:100]\n\n for i in range(0, 100):\n id_name_dic[res[i].get('game_id')] = res[i].get('game_name')\n res[i] = res[i].get('game_id')\n res_sum.append(res)\n\n id_name = []\n for key, value in id_name_dic.items():\n id_name.append([key, value])\n save_csv(\"../data/rank_list_\" + str(dateStart)+\"_pay\"+str(100), res_sum)\n save_csv(\"../data/id_name_\" + str(dateStart)+\"_pay\"+str(100), id_name)\n print('finish=' + str(dateStart) + ':' + str(dateEnd))\n\n\n# 使用线程提高爬取数据的速度:每个月开一线程\ndate = datetime.date(2017, 5, 1)\nth_arr = []\nwhile date < datetime.date(2018, 5, 1):\n next_month = date.month + 1\n next_year = date.year\n if next_month > 12:\n next_month = 1\n next_year += 1\n\n date_start = datetime.date(date.year, date.month, 1)\n date_end = datetime.date(next_year, next_month, 1)\n\n th_arr.append(threading.Thread(target=get_top_100, args=(date_start, date_end)))\n date += relativedelta(months=+1)\n\nfor th in th_arr:\n th.start()\n\n# 等待所有子线程返回\nfor th in th_arr:\n th.join()\n\nprint('ok')\n","sub_path":"tmp/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"72764252","text":"#Example 1\nclass MyClass:\n x = 5\n\np1 = MyClass()\nprint(p1.x)\n########################################\n#Example 2\nclass Person:\n # __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod\n #having the first non-optional argument (self) that holds reference to a newly created instance.\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\np1 = Person(\"John\", 36)\nprint(p1.name)\nprint(p1.age)\n########################################\n#Example 3\nclass Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def myfunc(self):\n print(\"Hello my name is \" + self.name)\n\np1 = Person(\"John\", 36)\np1.myfunc()\nprint(\"My age is:\", p1.age)\np1.age = 40\nprint(\"My age is now:\", p1.age)\n#########################################\n#Example 4\n","sub_path":"Martin/OOP/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"240338399","text":"from Tree import Node\nimport math\nimport random\n\ndef ID3(Attributes, X, Y):\n \"\"\"\n Implementaion of the ID3 Algorithm\n\n :param Attributes: List of attributes to test\n :param X: set of training instances\n :param Y: set of training labels\n :return: decision tree build from the training data\n \"\"\"\n # Handle base cases\n num_positive, num_negative = Calculate_Counts(Y)\n # All labels are positive\n if num_positive == len(Y):\n return Node(label='e')\n # All labels are negative\n elif num_negative == len(Y):\n return Node(label='-')\n # No attributes left to test (Choose the most common label amongst the remaining examples)\n if len(Attributes) == 0:\n if num_positive > num_negative:\n return Node(label='e')\n elif num_positive < num_negative:\n return Node(label='-')\n else:\n return Node(label=random.choice(['e','-']))\n\n # Determine the best attribute\n max_gain = None\n max_attribute = 0\n max_indices = []\n positive_splits = []\n negative_splits = []\n gains = []\n for i in range(len(Attributes)):\n gain, positive_split, negative_split = Gain(Attributes[i], X, Y)\n gains.append(gain)\n positive_splits.append(positive_split)\n negative_splits.append(negative_split)\n # Keep track of max gain(s)\n if max_gain == None:\n max_gain = gain\n max_indices.append(i)\n elif gain > max_gain:\n max_gain = gain\n max_indices = [i]\n elif gain == max_gain:\n max_indices.append(i)\n \n\n max_index = random.choice(max_indices)\n max_attribute = Attributes[max_index]\n max_positive_split = positive_splits[max_index]\n max_negative_split = negative_splits[max_index]\n\n # Remove the attribute from the list of attributes (Attrubutes - {A})\n Attributes = Attributes[:max_index] + Attributes[max_index+1:]\n\n # Set Attribute of the decision node to the one with the max gain\n current_node = Node(attribute=max_attribute)\n\n # Build positive child node\n if len(max_positive_split[0]) > 0:\n current_node.Positive_Branch = ID3(Attributes, max_positive_split[0], max_positive_split[1])\n else:\n if num_positive > num_negative:\n current_node.Positive_Branch = Node(label='e')\n elif num_positive < num_negative:\n current_node.Positive_Branch = Node(label='-')\n else:\n current_node.Positive_Branch = Node(label=random.choice(['e','-']))\n\n # Build negative child node\n if len(max_negative_split[0]) > 0:\n current_node.Negative_Branch = ID3(Attributes, max_negative_split[0], max_negative_split[1])\n else:\n if num_positive > num_negative:\n current_node.Negative_Branch = Node(label='e')\n elif num_positive < num_negative:\n current_node.Negative_Branch = Node(label='-')\n else:\n current_node.Negative_Branch = Node(label=random.choice(['e','-']))\n return current_node\n\ndef H(proportion_pos):\n \"\"\"\n Calculates entropy based on the given proportions\n\n :param proportion_pos: Proportion of positive training examples\n :return: Returns the entropy based on the given proportion\n \"\"\"\n if proportion_pos == 0 or proportion_pos == 1:\n return 0\n return -(proportion_pos*math.log(proportion_pos, 2)) - ((1-proportion_pos)*math.log((1-proportion_pos), 2))\n\ndef Attribute_Split(Attribute, X, Y):\n \"\"\"\n Splits the data on the given attribute and calculates the proportion \n of positive lables in the total set and both of the splits which is \n used later for calculating the entropy and information gain of these sets\n\n :param Attribute: Attribute to perform split on\n :param X: List of training instances\n :param Y: List of training labels\n :return: Two splits based on the given attribute along with proportions of positive examples\n ((pos_X, pos_Y, proportion_pos), (neg_X, neg_Y, proportion_pos), total_proportion_pos)\n \"\"\"\n # Initialize variables\n positive_X = []\n negative_X = []\n positive_Y = []\n negative_Y = []\n split1_num_pos = 0\n split1_num_total = 0\n split2_num_pos = 0\n split2_num_total = 0\n\n for i in range(len(X)):\n # The attribute is positive so place it in the positive split\n if X[i][Attribute] == 1:\n positive_X.append(X[i])\n positive_Y.append(Y[i])\n # Calculating the proportion positive in the positive attribute split\n if Y[i] == 'e':\n split1_num_pos += 1\n split1_num_total += 1\n # The attribute is negative so place it in the negative split\n else:\n negative_X.append(X[i])\n negative_Y.append(Y[i])\n # Calculating the proportion positive in the negative attribute split\n if Y[i] == 'e':\n split2_num_pos += 1\n split2_num_total += 1\n\n # Calculate the proportions\n split1_proportion_pos = 0\n split2_proportion_pos = 0\n total_proportion_pos = 0\n denom = 0\n\n # Proportion positive for each of the splits\n if split1_num_total > 0:\n split1_proportion_pos = split1_num_pos/float(split1_num_total)\n denom += split1_num_total\n if split2_num_total > 0:\n split2_proportion_pos = split2_num_pos/float(split2_num_total)\n denom += split2_num_total\n # Proportion positive for all of the instances\n if denom > 0:\n total_proportion_pos = (split1_num_pos + split2_num_pos)/float(denom)\n \n return (positive_X, positive_Y, split1_proportion_pos), (negative_X, negative_Y, split2_proportion_pos), total_proportion_pos\n\ndef Gain(Attribute, X, Y):\n \"\"\"\n Calculates the information gain for the given attribute\n\n :param Attribute: Attribute to test\n :param X: List of training instances\n :param Y: List of training labels\n :return: Information gain for the given attribute\n \"\"\"\n # Get splits and proportions\n pos_split, neg_split, proportion_pos = Attribute_Split(Attribute, X, Y)\n\n # Calculate weights based on split proportions\n num_pos_examples = len(pos_split[0])\n num_neg_examples = len(neg_split[0])\n num_total_examples = float(num_pos_examples + num_neg_examples)\n pos_split_weight = num_pos_examples/num_total_examples\n neg_split_weight = num_neg_examples/num_total_examples\n\n # Finally calculate the gain\n gain = H(proportion_pos) - (pos_split_weight*H(pos_split[2]) + neg_split_weight*H(neg_split[2]))\n \n return gain, pos_split, neg_split\n\ndef Calculate_Counts(Y):\n \"\"\"\n Calculate the number of positive and negative labels\n\n :param Y: List of labels\n :return: Counts of positive and negative labels\n \"\"\"\n num_positive = 0\n num_negative = 0\n for label in Y:\n if label == \"e\":\n num_positive += 1\n else:\n num_negative += 1\n return num_positive, num_negative\n\ndef Serialize_Tree(T, file_name=\"Tree.model\"):\n Q = []\n Q.append((0,T))\n node_id = 0\n with open(file_name, \"w\") as output_file:\n output_file.write(\"{},{},{},{},{}\\n\".format(0,T.Attribute,T.Label,0,\"+\"))\n while len(Q) > 0:\n parent_id, current_node = Q.pop()\n if current_node.Attribute is not None:\n positive_child_id = node_id + 1\n negative_child_id = node_id + 2\n Q.append((positive_child_id,current_node.Positive_Branch))\n Q.append((negative_child_id,current_node.Negative_Branch))\n output_file.write(\"{},{},{},{},{}\\n\".format(positive_child_id,current_node.Positive_Branch.Attribute,current_node.Positive_Branch.Label,parent_id,\"+\"))\n output_file.write(\"{},{},{},{},{}\\n\".format(negative_child_id,current_node.Negative_Branch.Attribute,current_node.Negative_Branch.Label,parent_id,\"-\"))\n node_id += 2\n\ndef Deserialize_Tree(file_name=\"Tree.model\"):\n nodes = {}\n num_nodes = 0\n with open(file_name, \"r\") as input_file:\n for line in input_file:\n line = line.strip().split(\",\")\n node_id, attribute, label, parent_id, parity = line\n node_id = int(node_id)\n parent_id = int(parent_id)\n if attribute != \"None\":\n attribute = int(attribute)\n else:\n attribute = None\n if label == \"None\":\n label = None\n nodes[node_id] = [Node(attribute,label),parent_id,parity]\n num_nodes += 1\n for i in range(1,num_nodes):\n if nodes[i][2] is \"+\":\n nodes[nodes[i][1]][0].Positive_Branch = nodes[i][0]\n else:\n nodes[nodes[i][1]][0].Negative_Branch = nodes[i][0]\n return nodes[0][0]\n","sub_path":"Project2/ID3.py","file_name":"ID3.py","file_ext":"py","file_size_in_byte":8793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"564869130","text":"import time\n\nTIMES = 1000\n\n\ndef time_exec(func):\n def wrapper(plaintext, key, show):\n if not show:\n start = time.time()\n for i in range(TIMES):\n func(plaintext=plaintext, key=key, show=show)\n end = time.time()\n print(f'{func.__name__}: {TIMES} times works {end - start}s')\n func(plaintext, key, show)\n\n return wrapper\n","sub_path":"tools/time_execution.py","file_name":"time_execution.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"32324589","text":"import string\nimport numpy as np\nimport tensorflow as tf\nimport random\n\n# Open file\nwith open('data/training/training-data.1m') as f:\n train_data = [x.strip('\\n') for x in f.readlines()]\nprint('Data loaded.')\n\n# remove punctuation and lower case all words\ndef prep(data):\n return [x.translate(None, string.punctuation).lower() for x in data]\n\ntrain_data = prep(train_data)\nprint('Data preprocessed.')\n\n# Create dictionary\ndef create_dict(data):\n dictionary = {}\n for line in data:\n for word in line.split():\n if word in dictionary:\n dictionary[word] += 1\n else:\n dictionary[word] = 1\n return dictionary\n\ndictionary_counts = create_dict(train_data)\nprint('Dictionary created with len',len(dictionary_counts))\ntotal_counts = sum(dictionary_counts[word] for word in dictionary_counts)\n\n# Option 1: Dictionary prune only\ndef prune_dict(dictionary, threshold):\n pruned_dict = {'UNK':0, '':1, '':2}\n count = 3\n for word in dictionary:\n if dictionary[word] > threshold:\n pruned_dict[word] = count\n count +=1\n return pruned_dict\n\ndef get_avg_count(dictionary):\n return sum(dictionary[word] for word in dictionary) / float(len(dictionary))\n\n# Option 2: Dictionary prune and subsampling\n# returns true p percent of the time\ndef should_remove(p):\n return True if random.random() < p else False\n\n# Remove words based on probablility determined by frequency\n# The dictionary returned will hold an index/ sequence of the words\ndef prune_and_subsample_dict(dictionary, total_counts, prune_threshold, t = 1e-5):\n new_dict = {'UNK':0, '':1, '':2}\n count = 3\n for word in dictionary:\n if dictionary[word] > prune_threshold:\n f = dictionary[word]/float(total_counts) # the word's fequency\n #p = ((f-t)/f) - np.sqrt(t/f) # probability that word will get removed.\n p = 1 - np.sqrt(t/f)\n if not should_remove(p):\n new_dict[word] = count # set it = dictionary[word] to store counts instead of indexes\n count +=1\n return new_dict\n\n# Pick based on the parameters\nsub_sampling_threshold = 0\nprune_threshold = 10\nif sub_sampling_threshold == 0:\n word_pruned_dictionary = prune_dict(dictionary_counts, prune_threshold)\n print(\"Dictionary pruned with threshold:\", prune_threshold)\nelse:\n word_pruned_dictionary = prune_and_subsample_dict(dictionary_counts, total_counts, prune_threshold, sub_sampling_threshold)\n print(\"Dictionary pruned and subsampled with threshold:\", prune_threshold, ' and ',sub_sampling_threshold)\n\ndel dictionary_counts\n\n# Replace the word in the training sentences with the dictionary IDs.\ndata_words_coded = []\ncount_zeros = 0\nfor sentence in train_data:\n # Split sentence into words\n words = sentence.split()\n data_words = []\n for word in words:\n if word in word_pruned_dictionary:\n data_words.append(word_pruned_dictionary[word])\n else:\n data_words.append(0)\n count_zeros += 1\n data_words_coded.append(data_words)\nprint(\"Dataset words replaced with IDs\")\n\n# Create the batch,label pairs as (context, word).\n# We pad the sentences using the special words : 1 and : 2\nskip_window_size = 5\ntrain_data_words = []\ntrain_data_context = []\nfor sentence in data_words_coded:\n for pos,word in enumerate(sentence):\n context = sentence[max(pos-skip_window_size,0):pos] + sentence[pos+1:min(pos+skip_window_size+1, len(sentence))]\n context += [1] * (pos+skip_window_size+1 - len(sentence)) # Manually padding with for the beginning of sentence\n context += [2] * (-pos+skip_window_size) # Manually padding with for the end of sentence\n train_data_context.append(context)\n train_data_words.append(word)\nprint(\"Batch and labels created\")\n\ndel data_words_coded\ndel train_data\n\n# We are not introducing any positioning in the context. Therefore, both words\n# and context dictionaries are the same.\ncontext_pruned_dictionary = word_pruned_dictionary.copy()\n\n# Convert the data structures to use in the NN\ntrain_data_context = np.array(train_data_context) #It's a vector containing lists to use as batch\ntrain_data_words = np.matrix(train_data_words).T #It's a matrix transpose to use as label\n\n# Shuffle the input\nidx = np.random.permutation(train_data_context.shape[0])\ntrain_data_context = train_data_context[idx]\ntrain_data_words = train_data_words[idx,:]\nprint(\"Data shuffled\")\n\n##### Define TensorFlow graph #####\n# Dimensions of the embedding\nembedding_size = 500\n\n# Size of the batch to be processed in each step\nbatch_size = 128\n\n# Number of iterations\nnum_steps = 300001\n\n# Number of \"sample\" classes to pick randomly.\nsampled_size = 30\n\n# Length of the context dictionary\nnum_labels = len(word_pruned_dictionary)\n\n# Length of the words dictionary\nnum_features = len(context_pruned_dictionary)\n\ngraph = tf.Graph()\nwith graph.as_default():\n # Input data. For the training data, we use a placeholder that will be fed\n # at run time with a training minibatch.\n tf_train_dataset = tf.placeholder(tf.int32, shape=[batch_size, skip_window_size * 2])\n tf_train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n # tf_valid_dataset = tf.constant(valid_dataset[50:60])\n # tf_test_dataset = tf.constant(test_dataset)\n\n # TODO: Generate values with a -1 to 1 range\n tf_embedding = tf.Variable(tf.truncated_normal([num_features, embedding_size]))\n tf.Variable(tf.random_uniform([num_features, embedding_size], -1.0, 1.0))\n tf_weights_softmax = tf.Variable(tf.truncated_normal([num_labels, embedding_size]))\n tf_bias_softmax = tf.Variable(tf.zeros([num_labels]))\n\n # We are going to compute a one hot encoding vector of a very large dataset. We save time of\n # unnecesary computation of the product of the vector with almost all zeros and a matrix and\n # just get the matrix value. For CBOW, we sum the embedding of the context of each word\n embed = tf.zeros([batch_size, embedding_size])\n for j in range(skip_window_size * 2):\n embed += tf.nn.embedding_lookup(tf_embedding, tf_train_dataset[:, j])\n\n # With the Sample Softmax, we are applying the Negative Sampling technique to the optimization\n # equation. Therefore, the optimization takes into account pairs that never occured in the\n # dataset and the convergence is going to be faster. We provide a number of samples from each\n # batch that are going to be randomly reassigned to another class.\n loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(weights=tf_weights_softmax, biases=tf_bias_softmax,\n labels=tf_train_labels, inputs=embed, num_sampled=sampled_size,\n num_classes=num_labels))\n\n # TODO: Use the Noisy\n # loss = tf.nn.nce_loss(weights, biases, labels, inputs, num_sampled)\n\n\n #optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)\n optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)\n #optimizer = tf.train.AdagradOptimizer(learning_rate).minimize(loss, global_step=global_step)\n\n # Normalize the embeddings.\n norm = tf.sqrt(tf.reduce_sum(tf.square(tf_embedding), 1, keep_dims=True))\n normalized_embeddings = tf_embedding / norm\n\n##### Define TensorFlow session #####\nwith tf.Session(graph=graph) as session:\n tf.global_variables_initializer().run()\n average_loss = 0\n print(\"Initialized\")\n for step in range(num_steps):\n # Pick an offset within the training data, which has been randomized.\n # Note: we could use better randomization across epochs.\n offset = (step * batch_size) % (train_data_context.shape[0] - batch_size)\n # Generate a minibatch.\n batch_data = train_data_context[offset:(offset + batch_size)]\n batch_labels = train_data_words[offset:(offset + batch_size)]\n # Prepare a dictionary telling the session where to feed the minibatch.\n # The key of the dictionary is the placeholder node of the graph to be fed,\n # and the value is the numpy array to feed to it.\n feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n _, l = session.run(\n [optimizer, loss], feed_dict=feed_dict)\n average_loss += l\n if step % 2000 == 0:\n if step > 0:\n average_loss = average_loss / 2000\n # The average loss is an estimate of the loss over the last 2000 batches.\n print('Average loss at step %d: %f' % (step, average_loss))\n average_loss = 0\n output_embeddings = normalized_embeddings.eval()\n\n# Create the reverse dictionary to generate the output file.\nreverse_dictionary = dict(zip(word_pruned_dictionary.values(), word_pruned_dictionary.keys()))\n\nf = open('output.txt','w')\nfor i in range(len(word_pruned_dictionary)):\n f.write(reverse_dictionary[i] + \" \" + \" \".join(str(x) for x in output_embeddings[i]) + \"\\n\")\nf.close()\n","sub_path":"cbow.py","file_name":"cbow.py","file_ext":"py","file_size_in_byte":9013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"536029273","text":"import sys\nimport collections\n\ninput = sys.stdin.readline\n\ndef main():\n ans = 0\n n = int(input())\n s = [input().rstrip('\\n') for _ in range(n)]\n m = int(input())\n t = [input().rstrip('\\n') for _ in range(m)]\n cs = collections.Counter(s)\n ct = collections.Counter(t)\n for k,v in cs.items():\n ans = max(v-ct[k], ans)\n print(ans)\n\nif __name__ == '__main__':\n main()","sub_path":"Python_codes/p03408/s076273965.py","file_name":"s076273965.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"358341206","text":"# coding:utf8\n\"\"\"\n访问权限仅针对电影和标签的管理做限制\n操作日志记录也仅针对标签的相关操作做了记录\n\"\"\"\nfrom flask import render_template, url_for, redirect, flash, session, request, abort\nfrom functools import wraps\nfrom werkzeug.utils import secure_filename\n\nfrom app import db, app\nfrom app.models import Admin, Tag, Movie, MoviePreview, User, Comment, \\\n MovieCollection, OperateLog, UserLog, AdminLog, Auth, Role\nfrom .forms import LoginForm, TagForm, MovieForm, MoviePreviewForm, PWDResetForm, AuthForm, RoleForm, AdminForm\nfrom . import admin\nimport os, uuid, datetime, stat\n\n\n@admin.context_processor\ndef tpl_extra():\n \"\"\"\n 上下文应用处理器,使变量能够被模板访问\n \"\"\"\n data = dict(\n # 当前时间\n online_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n )\n return data\n\n\ndef admin_login_req(f):\n \"\"\"\n 登陆访问装饰器\n \"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n # 未登陆的话重定向到登陆页面\n if 'admin' not in session:\n print(url_for('admin.login', next=request.url))\n return redirect(url_for('admin.login', next=request.url))\n return f(*args, **kwargs)\n return decorated_function\n\n\ndef admin_auth(f):\n \"\"\"\n 权限控制装饰器\n \"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n # 关联角色查询管理员\n admin = Admin.query.join(Role).filter(\n Role.id == Admin.role_id,\n Admin.id == session['admin_id']\n ).first()\n # 管理员所属角色���权限ID字符串,格式('1,2,3')\n auths = admin.role.auths\n # 将权限ID字符串转化成int类型的列表,[1, 2, 3]\n auths = [int(auth) for auth in auths.split(',')]\n # 所有的权限对象\n all_auth = Auth.query.all()\n # 根据auths找出所有的权限对象的url组成列表\n urls = [v.url for v in all_auth for val in auths if val == v.id]\n # 当前访问页面url\n rule = str(request.url_rule)\n # 如果当前访问页面url不再该管理员所属角色的权限里,则禁止访问\n if rule not in urls:\n abort(404)\n return f(*args, **kwargs)\n\n return decorated_function\n\n\ndef change_filename(filename):\n \"\"\"\n 生成一个唯一的文件名\n \"\"\"\n # 将文件名和后缀分离\n file_info = os.path.splitext(filename)\n # 文件名为:添加时间+uuid生成的唯一字符串+文件后缀\n filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(uuid.uuid4().hex) + file_info[1]\n return filename\n\n\n@admin.route('/')\n@admin_login_req\n@admin_auth\ndef index():\n \"\"\"\n 后台首页\n \"\"\"\n return render_template('admin/index.html')\n\n\n@admin.route('/login/', methods=['GET', 'POST'])\ndef login():\n \"\"\"\n 后台登录\n \"\"\"\n form = LoginForm()\n if form.validate_on_submit():\n data = form.data\n admin = Admin.query.filter_by(name=data['account']).first()\n if not admin.check_pwd(data['pwd']):\n # 错误消息闪现\n flash('密码错误', 'error')\n return redirect(url_for('admin.login'))\n # 检测通过,则在session中保存admin的名称和ID\n session['admin'] = data['account']\n session['admin_id'] = admin.id\n\n # 记录登陆操作\n admin_log = AdminLog(\n admin_id=admin.id,\n ip=request.remote_addr\n )\n db.session.add(admin_log)\n db.session.commit()\n return redirect(request.args.get('next') or url_for('admin.index'))\n return render_template('admin/login.html', form=form)\n\n\n@admin.route('/logout/')\n@admin_login_req\ndef logout():\n \"\"\"\n 后台登出\n \"\"\"\n session.pop('admin', None)\n session.pop('admin_id', None)\n return redirect(url_for('admin.login'))\n\n\n@admin.route('/pwd_reset/', methods=['GET', 'POST'])\n@admin_login_req\ndef pwd_reset():\n \"\"\"\n 后台密码重置\n \"\"\"\n form = PWDResetForm()\n if form.validate_on_submit():\n data = form.data\n admin = Admin.query.filter_by(name=session['admin']).first()\n from werkzeug.security import generate_password_hash\n admin.pwd = generate_password_hash(data['new_pwd'])\n db.session.add(admin)\n db.session.commit()\n flash('修改密码成功,请重新登陆', 'success')\n redirect(url_for('admin.logout'))\n return render_template('admin/pwd_reset.html', form=form)\n\n\n@admin.route('/tag/add/', methods=['GET', 'POST'])\n@admin_login_req\n@admin_auth\ndef tag_add():\n \"\"\"\n 添加标签\n \"\"\"\n form = TagForm()\n if form.validate_on_submit():\n data = form.data\n tag_count = Tag.query.filter_by(name=data['name']).count()\n # 标签是否已经存在\n if tag_count == 1:\n flash('名称已经存在', 'error')\n return redirect(url_for('admin.tag_add'))\n # 将新标签加入数据库\n tag = Tag(\n name=data['name']\n )\n db.session.add(tag)\n db.session.commit()\n flash('添加标签成功', 'success')\n\n # 记录该操作\n oplog = OperateLog(\n admin_id=session['admin_id'],\n ip=request.remote_addr,\n reason='添加标签:{}'.format(data['name'])\n )\n db.session.add(oplog)\n db.session.commit()\n return redirect(url_for('admin.tag_add'))\n return render_template('admin/tag_add.html', form=form)\n\n\n@admin.route('/tag/edit//', methods=['GET', 'POST'])\n@admin_login_req\n@admin_auth\ndef tag_edit(id=None):\n \"\"\"\n 修改标签\n \"\"\"\n form = TagForm()\n tag = Tag.query.get_or_404(id)\n if form.validate_on_submit():\n data = form.data\n tag_count = Tag.query.filter_by(name=data['name']).count()\n # 如果根据名字查到标签对象而且该名字不等于正在修改的标签的名字,则标签重复\n if tag_count == 1 and tag.name != data['name']:\n flash('名称已经存在', 'error')\n return redirect(url_for('admin.tag_edit', id=id))\n # 将修改标签更新到数据库\n tag.name = data['name']\n db.session.add(tag)\n db.session.commit()\n flash('修改标签成功', 'success')\n return redirect(url_for('admin.tag_edit', id=id))\n return render_template('admin/tag_edit.html', form=form, tag=tag)\n\n\n@admin.route('/tag/delete//', methods=['GET'])\n@admin_login_req\n@admin_auth\ndef tag_del(id=None):\n \"\"\"\n 标签删除\n \"\"\"\n tag = Tag.query.filter_by(id=id).first_or_404()\n db.session.delete(tag)\n db.session.commit()\n flash('删除标签成功', 'success')\n return redirect(url_for('admin.tag_list', page=1))\n\n\n@admin.route('/tag/list//', methods=['GET'])\n@admin_login_req\n@admin_auth\ndef tag_list(page=None):\n \"\"\"\n 标签列表\n \"\"\"\n if page is None:\n page = 1\n data = Tag.query.order_by(\n Tag.add_time.desc()\n ).paginate(page=page, per_page=10)\n return render_template('admin/tag_list.html', data=data)\n\n\n@admin.route('/movie/add/', methods=['GET', 'POST'])\n@admin_login_req\n@admin_auth\ndef movie_add():\n \"\"\"\n 添加电影\n \"\"\"\n form = MovieForm()\n form.tag_id.choices = [(v.id, v.name) for v in Tag.query.all()]\n if form.validate_on_submit():\n\n data = form.data\n file_url = secure_filename(form.url.data.filename)\n file_logo = secure_filename(form.logo.data.filename)\n\n # 保存路径是否存在\n if not os.path.exists(app.config['UP_DIR']):\n os.makedirs(app.config['UP_DIR'])\n os.chmod(app.config['UP_DIR'], stat.S_IRWXU)\n\n # 生成唯一文件名\n url = change_filename(file_url)\n logo = change_filename(file_logo)\n\n # 保存文件\n form.url.data.save(app.config['UP_DIR'] + url)\n form.logo.data.save(app.config['UP_DIR'] + logo)\n\n # 构造电影实体,存入数据库\n movie = Movie(\n title=data['title'],\n url=url,\n info=data['info'],\n logo=logo,\n star=int(data['star']),\n play_num=0,\n comment_num=0,\n tag_id=int(data['tag_id']),\n area=data['area'],\n release_time=data['release_time'],\n length=data['length']\n )\n db.session.add(movie)\n db.session.commit()\n flash('添加电影成功', 'success')\n return redirect(url_for('admin.movie_add'))\n return render_template('admin/movie_add.html', form=form)\n\n\n@admin.route('/movie/list//', methods=['GET'])\n@admin_login_req\n@admin_auth\ndef movie_list(page=None):\n \"\"\"\n 电影列表\n \"\"\"\n if page is None:\n page = 1\n # 使用join联合查询Tag和movie表\n data = Movie.query.join(Tag).filter(\n Tag.id == Movie.tag_id\n ).order_by(\n Movie.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/movie_list.html', data=data)\n\n\n@admin.route('/movie/edit//', methods=['GET', 'POST'])\n@admin_login_req\n@admin_auth\ndef movie_edit(id=None):\n \"\"\"\n 编辑电影\n \"\"\"\n form = MovieForm()\n # 电影的logo和url已经存在,不用进行验证\n form.url.validators = []\n form.logo.validators = []\n movie = Movie.query.get_or_404(int(id))\n\n # 赋初值(因为部分字段在html里不容易获取值)\n if request.method == 'GET':\n form.info.data = movie.info\n form.tag_id.data = movie.tag_id\n form.star.data = movie.star\n\n if form.validate_on_submit():\n data = form.data\n print(form.logo.data)\n\n # 片名不能重复\n movie_count = Movie.query.filter_by(title=data['title']).count()\n if movie_count == 1 and movie.title != data['title']:\n flash('片名不能重复', 'error')\n return redirect(url_for('admin.movie_edit', id=id))\n\n # 保存路径是否存在\n if not os.path.exists(app.config['UP_DIR']):\n os.makedirs(app.config['UP_DIR'])\n os.chmod(app.config['UP_DIR'], stat.S_IRWXU)\n\n # 生成唯一文件名并保存\n if form.url.data.filename != '':\n file_url = secure_filename(form.url.data.filename)\n movie.url = change_filename(file_url)\n form.url.data.save(app.config['UP_DIR'] + movie.url)\n if form.logo.data.filename != '':\n file_logo = secure_filename(form.logo.data.filename)\n movie.logo = change_filename(file_logo)\n form.logo.data.save(app.config['UP_DIR'] + movie.logo)\n\n # 获取其他修改的信息并保存到数据库\n movie.star = data['star']\n movie.tag_id = data['tag_id']\n movie.info = data['info']\n movie.title = data['title']\n movie.area = data['area']\n movie.length = data['length']\n movie.release_time = data['release_time']\n db.session.add(movie)\n db.session.commit()\n flash('编辑电影成功', 'success')\n return redirect(url_for('admin.movie_edit', id=id))\n return render_template('admin/movie_edit.html', form=form, movie=movie)\n\n\n@admin.route('/movie/del//', methods=['GET'])\n@admin_login_req\n@admin_auth\ndef movie_del(id=None):\n \"\"\"\n 删除电影\n \"\"\"\n movie = Movie.query.get_or_404(int(id))\n db.session.delete(movie)\n db.session.commit()\n flash('删除电影成功', 'success')\n return redirect(url_for('admin.movie_list', page=1))\n\n\n@admin.route('/movie_pre/add/', methods=['GET', 'POST'])\n@admin_login_req\ndef movie_pre_add():\n \"\"\"\n 添加电影预告\n \"\"\"\n form = MoviePreviewForm()\n if form.validate_on_submit():\n data = form.data\n\n file_logo = secure_filename(form.logo.data.filename)\n\n # 保存路径是否存在\n if not os.path.exists(app.config['UP_DIR']):\n os.makedirs(app.config['UP_DIR'])\n os.chmod(app.config['UP_DIR'], stat.S_IRWXU)\n # 生成唯一文件名\n logo = change_filename(file_logo)\n # 保存文件\n form.logo.data.save(app.config['UP_DIR'] + logo)\n movie_pre = MoviePreview(\n title=data['title'],\n logo=logo\n )\n db.session.add(movie_pre)\n db.session.commit()\n flash('添加预告成功', 'success')\n return redirect(url_for('admin.movie_pre_add'))\n return render_template('admin/movie_pre_add.html', form=form)\n\n\n@admin.route('/movie_pre/edit//', methods=['GET', 'POST'])\n@admin_login_req\ndef movie_pre_edit(id=None):\n \"\"\"\n 编辑电影预告\n \"\"\"\n form = MoviePreviewForm()\n # 电影的logo和url已经存在,不用进行验证\n form.logo.validators = []\n movie_pre = MoviePreview.query.get_or_404(int(id))\n\n if form.validate_on_submit():\n data = form.data\n\n print(form.logo.data)\n\n # 片名不能重复\n movie_pre_count = MoviePreview.query.filter_by(title=data['title']).count()\n if movie_pre_count == 1 and movie_pre.title != data['title']:\n flash('预告片名不能重复', 'error')\n return redirect(url_for('admin.movie_pre_edit', id=id))\n\n # 保存路径是否存在\n if not os.path.exists(app.config['UP_DIR']):\n os.makedirs(app.config['UP_DIR'])\n os.chmod(app.config['UP_DIR'], stat.S_IRWXU)\n\n # 生成唯一文件名并保存\n if form.logo.data.filename != '':\n file_logo = secure_filename(form.logo.data.filename)\n movie_pre.logo = change_filename(file_logo)\n form.logo.data.save(app.config['UP_DIR'] + movie_pre.logo)\n\n # 获取其他修改的信息并保存到数据库\n movie_pre.title = data['title']\n db.session.add(movie_pre)\n db.session.commit()\n flash('编辑电影预告成功', 'success')\n return redirect(url_for('admin.movie_pre_edit', id=id))\n return render_template('admin/movie_pre_edit.html', form=form, movie_pre=movie_pre)\n\n\n@admin.route('/movie_pre/list//', methods=['GET'])\n@admin_login_req\ndef movie_pre_list(page=None):\n \"\"\"\n 电影预告列表\n \"\"\"\n if page is None:\n page = 1\n data = MoviePreview.query.order_by(\n MoviePreview.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/movie_pre_list.html', data=data)\n\n\n@admin.route('/movie_pre/del//', methods=['GET'])\n@admin_login_req\ndef movie_pre_del(id=None):\n \"\"\"\n 删除电影预告\n \"\"\"\n movie_pre = MoviePreview.query.get_or_404(int(id))\n db.session.delete(movie_pre)\n db.session.commit()\n flash('删除电影预告成功', 'success')\n return redirect(url_for('admin.movie_pre_list', page=1))\n\n\n@admin.route('/user/list//', methods=['GET'])\n@admin_login_req\ndef user_list(page=None):\n \"\"\"\n 会员列表\n \"\"\"\n if page is None:\n page = 1\n data = User.query.order_by(\n User.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/user_list.html', data=data)\n\n\n@admin.route('/user/detail//', methods=['GET'])\n@admin_login_req\ndef user_detail(id=None):\n \"\"\"\n 会员详细信息\n \"\"\"\n user = User.query.get_or_404(int(id))\n return render_template('admin/user_detail.html', user=user)\n\n\n@admin.route('/user/del//', methods=['GET'])\n@admin_login_req\ndef user_del(id=None):\n \"\"\"\n 删除会员\n \"\"\"\n user = User.query.get_or_404(int(id))\n db.session.delete(user)\n db.session.commit()\n flash('删除会员成功', 'success')\n return redirect(url_for('admin.user_list', page=1))\n\n\n@admin.route('/comment/list//', methods=['GET'])\n@admin_login_req\ndef comment_list(page=None):\n \"\"\"\n 评论列表\n \"\"\"\n if page is None:\n page = 1\n # 关联Movie和User表\n data = Comment.query.join(Movie).join(User).filter(\n Movie.id == Comment.movie_id,\n User.id == Comment.user_id,\n ).order_by(\n Comment.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/comment_list.html', data=data)\n\n\n@admin.route('/comment/del//', methods=['GET'])\n@admin_login_req\ndef comment_del(id=None):\n \"\"\"\n 删除评论\n \"\"\"\n comment = Comment.query.get_or_404(int(id))\n db.session.delete(comment)\n db.session.commit()\n flash('删除评论成功', 'success')\n return redirect(url_for('admin.comment_list', page=1))\n\n\n@admin.route('/movie/collist//', methods=['GET'])\n@admin_login_req\ndef movie_collist(page=None):\n \"\"\"\n 电影收藏\n \"\"\"\n if page is None:\n page = 1\n # 关联Movie和User表\n data = MovieCollection.query.join(Movie).join(User).filter(\n Movie.id == MovieCollection.movie_id,\n User.id == MovieCollection.user_id,\n ).order_by(\n MovieCollection.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/movie_collist.html', data=data)\n\n\n@admin.route('/movie/collist/del//', methods=['GET'])\n@admin_login_req\ndef movie_col_del(id=None):\n \"\"\"\n 删除收藏\n \"\"\"\n movie_col = MovieCollection.query.get_or_404(int(id))\n db.session.delete(movie_col)\n db.session.commit()\n flash('删除收藏成功', 'success')\n return redirect(url_for('admin.movie_collist', page=1))\n\n\n@admin.route('/oplog/list//', methods=['GET'])\n@admin_login_req\ndef oplog_list(page=None):\n \"\"\"\n 操作日志列表\n \"\"\"\n if page is None:\n page = 1\n # 关联Admin表\n data = OperateLog.query.join(Admin).filter(\n OperateLog.admin_id == Admin.id\n ).order_by(\n OperateLog.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/oplog_list.html', data=data)\n\n\n@admin.route('/adminloginlog/list//', methods=['GET'])\n@admin_login_req\ndef adminloginlog_list(page=None):\n \"\"\"\n 管理员登陆日志列表\n \"\"\"\n if page is None:\n page = 1\n # 关联Admin表\n data = AdminLog.query.join(Admin).filter(\n AdminLog.admin_id == Admin.id\n ).order_by(\n AdminLog.add_time.desc()\n ).paginate(page=page, per_page=2)\n return render_template('admin/adminloginlog_list.html', data=data)\n\n\n@admin.route('/userloginlog/list//', methods=['GET'])\n@admin_login_req\ndef userloginlog_list(page=None):\n \"\"\"\n 用户登陆日志列表\n \"\"\"\n if page is None:\n page = 1\n # 关联User表\n data = UserLog.query.join(User).filter(\n UserLog.user_id == User.id\n ).order_by(\n UserLog.login_time.desc()\n ).paginate(page=page, per_page=2)\n print(list(data.iter_pages()))\n return render_template('admin/userloginlog_list.html', data=data)\n\n\n@admin.route('/role/add/', methods=['GET', 'POST'])\n@admin_login_req\ndef role_add():\n \"\"\"\n 添加角色\n \"\"\"\n form = RoleForm()\n form.auths.choices = [(v.id, v.name) for v in Auth.query.all()]\n if form.validate_on_submit():\n data = form.data\n role = Role(\n name=data['name'],\n # 使用join拼接权限数组,先转化为字符串,因为权限ID是int\n auths=','.join([str(auth) for auth in data['auths']])\n )\n db.session.add(role)\n db.session.commit()\n flash('角色添加成功', 'success')\n return render_template('admin/role_add.html', form=form)\n\n\n@admin.route('/role/edit//', methods=['GET', 'POST'])\n@admin_login_req\ndef role_edit(id=None):\n \"\"\"\n 修改角色\n \"\"\"\n form = RoleForm()\n form.auths.choices = [(v.id, v.name) for v in Auth.query.all()]\n role = Role.query.get_or_404(id)\n\n # 对权限列表赋予初值,先对数据进行处理,转化成int型的列表\n if request.method == 'GET':\n form.auths.data = [int(auth) for auth in role.auths.split(',')]\n\n if form.validate_on_submit():\n data = form.data\n # 将修改权限更新到数据库\n role.name = data['name']\n role.auths = ','.join([str(auth) for auth in data['auths']])\n db.session.add(role)\n db.session.commit()\n flash('修改权限成功', 'success')\n return redirect(url_for('admin.role_edit', id=id))\n return render_template('admin/role_edit.html', form=form, role=role)\n\n\n@admin.route('/role/delete//', methods=['GET'])\n@admin_login_req\ndef role_del(id=None):\n \"\"\"\n 角色删除\n \"\"\"\n role = Role.query.filter_by(id=id).first_or_404()\n db.session.delete(role)\n db.session.commit()\n flash('删除角色成功', 'success')\n return redirect(url_for('admin.role_list', page=1))\n\n\n@admin.route('/role/list//', methods=['GET'])\n@admin_login_req\ndef role_list(page=None):\n \"\"\"\n 角色列表\n \"\"\"\n if page is None:\n page = 1\n data = Role.query.order_by(\n Role.add_time.desc()\n ).paginate(page=page, per_page=5)\n return render_template('admin/role_list.html', data=data)\n\n\n@admin.route('/auth/add/', methods=['GET', 'POST'])\n@admin_login_req\ndef auth_add():\n \"\"\"\n 添加权限\n \"\"\"\n form = AuthForm()\n if form.validate_on_submit():\n data = form.data\n\n auth_count = Auth.query.filter_by(url=data['url']).count()\n # 标签是否已经存在\n if auth_count == 1:\n flash('该权限已经存在', 'error')\n return redirect(url_for('admin.auth_add'))\n\n auth = Auth(\n name=data['name'],\n url=data['url']\n )\n db.session.add(auth)\n db.session.commit()\n flash('权限添加成功', 'success')\n return redirect(url_for('admin.auth_add'))\n return render_template('admin/auth_add.html', form=form)\n\n\n@admin.route('/auth/edit//', methods=['GET', 'POST'])\n@admin_login_req\ndef auth_edit(id=None):\n \"\"\"\n 修改权限\n \"\"\"\n form = AuthForm()\n auth = Auth.query.get_or_404(id)\n if form.validate_on_submit():\n data = form.data\n auth_count = Auth.query.filter_by(url=data['url']).count()\n # 如果根据名字查到权限对象而且该url不等于正在修改的权限的url,则权限重复\n if auth_count == 1 and auth.url != data['url']:\n flash('权限已经存在', 'error')\n return redirect(url_for('admin.auth_edit', id=id))\n # 将修改权限更新到数据库\n auth.name = data['name']\n auth.url = data['url']\n db.session.add(auth)\n db.session.commit()\n flash('修改权限成功', 'success')\n return redirect(url_for('admin.auth_edit', id=id))\n return render_template('admin/auth_edit.html', form=form, auth=auth)\n\n\n@admin.route('/auth/delete//', methods=['GET'])\n@admin_login_req\ndef auth_del(id=None):\n \"\"\"\n 权限删除\n \"\"\"\n auth = Auth.query.filter_by(id=id).first_or_404()\n db.session.delete(auth)\n db.session.commit()\n flash('删除权限成功', 'success')\n return redirect(url_for('admin.auth_list', page=1))\n\n\n@admin.route('/auth/list//', methods=['GET'])\n@admin_login_req\ndef auth_list(page=None):\n \"\"\"\n 权限列表\n \"\"\"\n if page is None:\n page = 1\n data = Auth.query.order_by(\n Auth.add_time.desc()\n ).paginate(page=page, per_page=5)\n return render_template('admin/auth_list.html', data=data)\n\n\n@admin.route('/admin/add/', methods=['GET', 'POST'])\n@admin_login_req\ndef admin_add():\n \"\"\"\n 添加管理员\n \"\"\"\n from werkzeug.security import generate_password_hash\n form = AdminForm()\n form.role_id.choices = [(v.id, v.name) for v in Role.query.all()]\n if form.validate_on_submit():\n data = form.data\n admin = Admin(\n name=data['name'],\n pwd=generate_password_hash(data['pwd']),\n role_id=data['role_id'],\n # 代表普通管理员\n is_super=1,\n )\n db.session.add(admin)\n db.session.commit()\n flash('添加管理员成功', 'success')\n return redirect(url_for('admin.admin_add'))\n return render_template('admin/admin_add.html', form=form)\n\n\n@admin.route('/admin/list/', methods=['GET'])\n@admin_login_req\ndef admin_list(page=None):\n \"\"\"\n 管理员列表\n \"\"\"\n if page is None:\n page = 1\n # 关联Role表\n data = Admin.query.join(Role).filter(\n Admin.role_id == Role.id,\n ).order_by(\n Admin.add_time.desc()\n ).paginate(page=page, per_page=5)\n return render_template('admin/admin_list.html', data=data)\n","sub_path":"app/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130561727","text":"# test comment\nimport os\nfilename = input(\"File to format: \")\nos.system(\"gunzip \"+filename)\nn = int(input(\"What number genome is this? \"))\nos.system(\"mv \"+filename[:-3]+\" genome\"+str(n)+\".fna\")\noriginal = \"genome\"+str(n)+\".fna\"\ncopy = \"genome\"+str(n)+\"_copy.fna\"\nfiltered = \"genome\"+str(n)+\"_filtered.fna\"\nrem = ['>']\nwith open(original) as old, open(copy,'w') as new:\n for line in old:\n if not any(bad in line for bad in rem):\n new.write(line)\nwith open(copy) as f, open(filtered,'a') as f2:\n f2.write(\"\".join(line.strip() for line in f))\nwith open(filtered, 'r+') as inp:\n y = inp.read().upper()\n inp.truncate(0)\nwith open(filtered, 'a') as out:\n out.write(y)\nos.remove(copy)\n","sub_path":"genome-experimentation/cleaning-genome-data.py","file_name":"cleaning-genome-data.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"210021147","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mysite', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='product',\n name='nickname',\n field=models.CharField(verbose_name='摘要', max_length=15, default='Great Value Secondhand Phones'),\n ),\n migrations.AlterField(\n model_name='product',\n name='pmodel',\n field=models.ForeignKey(verbose_name='型号', to='mysite.PModel'),\n ),\n ]\n","sub_path":"ch7/mysite/migrations/0002_auto_20180426_2256.py","file_name":"0002_auto_20180426_2256.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187230631","text":"# Create your views here.\nimport datetime\nfrom django.http import HttpResponse\n\n\ndef welcome(request):\n timevar = datetime.datetime.now()\n html = \"The current time is: %s.\" % timevar \n return HttpResponse(html)\n\ndef hours_ahead(request, offset):\n #offset is the string value captured by the paranthesized regexp in\n #the urls.py class\n try:\n offset = int(offset)\n except ValueError:\n raise Http404()\n timevar = datetime.datetime.now() + datetime.timedelta(hours=offset)\n assert False\n html = \"In %s hours, the clock will show: %s\" \\\n %(offset, timevar)\n return HttpResponse(html)\n\n\n","sub_path":"show_current_time/curr_time_views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"120515833","text":"import numpy as np\r\nimport psutil\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib import animation\r\nglobal a\r\n\r\na=0\r\n# First set up the figure, the axis, and the plot element we want to animate\r\nfig = plt.figure()\r\nax = plt.axes(xlim=(0, 300), ylim=(0, 30))\r\nline, = ax.plot([], [], lw=2)\r\n\r\n# initialization function: plot the background of each frame\r\ndef init():\r\n line.set_data([], [])\r\n return line,\r\n\r\n# animation function. This is called sequentially\r\ndef animate(i):\r\n pullData = open(\"sampleText.txt\",\"r\").read()\r\n dataArray = pullData.split('\\n')\r\n xar = []\r\n yar = []\r\n\r\n for eachLine in dataArray:\r\n if len(eachLine)>1:\r\n x,y = eachLine.split(',')\r\n xar.append(float(x))\r\n yar.append(float(y))\r\n\r\n line.set_data(xar, yar)\r\n return line,\r\n\r\n# call the animator. blit=True means only re-draw the parts that have changed.\r\nanim = animation.FuncAnimation(fig, animate, init_func=init,\r\n frames=50, interval=1, blit=True)\r\n\r\n# save the animation as an mp4. This requires ffmpeg or mencoder to be\r\n# installed. The extra_args ensure that the x264 codec is used, so that\r\n# the video can be embedded in html5. You may need to adjust this for\r\n# your system: for more information, see\r\n# http://matplotlib.sourceforge.net/api/animation_api.html\r\n#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\r\n\r\nplt.show()","sub_path":"Networking/Continous_writing.py","file_name":"Continous_writing.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"455668630","text":"import boto\nimport boto.ec2\nfrom boto.exception import EC2ResponseError\nimport random\nfrom app import app, db\nimport os\nfrom .models import SSHKey, AWSAccount, AWSRegion\nfrom datetime import datetime\nimport shutil\nimport base64\nimport digitalocean\nfrom Crypto.PublicKey import RSA\n\n\nclass DOAPI(object):\n def __init__(self, token):\n self.token = token\n self.manager = digitalocean.Manager(token=self.token)\n\n def create_instance(self, image, key, region, size_slug='1gb'):\n r = random.randint(10000,99999)\n\n keys = self.manager.get_all_sshkeys()\n kid = None\n\n for ke in keys:\n if ke.name == key:\n kid = ke.id\n\n droplet = digitalocean.Droplet(token=self.token, image=image, name='obliterator-{}'.format(r), region=region, size_slug=size_slug, ssh_keys=[kid])\n droplet.create()\n\n return droplet\n\n def delete_instance(self, instance):\n droplet = digitalocean.Droplet(token=self.token, id=instance)\n return droplet.destroy()\n\n\n def validate_credentials(self):\n try:\n m = digitalocean.Manager(token=self.token)\n m.get_account()\n return True\n except:\n return False\n\n def get_regions(self):\n self.regions = [r.slug for r in self.manager.get_all_regions()]\n\n return self.regions\n\n def generate_key_pair(self, name, user_id, account_id):\n r = random.randint(10000,99999)\n k = RSA.generate(2048)\n key = SSHKey(name='DO - {}'.format(name), description='This key was autogenerated when creating an DigitalOcean account', user_id=user_id, key_type='DO', key=base64.b64encode(k.exportKey('PEM')), creation_date=datetime.now(), do_name='obliterator_{}'.format(r), do_account_id=account_id)\n\n dk = digitalocean.SSHKey(name='obliterator_{}'.format(r), public_key=k.publickey().exportKey('OpenSSH'))\n dk.token = self.token\n\n dk.create()\n\n db.session.add(key)\n db.session.commit()\n\n return key.id\n\n\nclass AWSAPI(object):\n def __init__(self, access_key, secret_key):\n self.access_key = access_key\n self.secret_key = secret_key\n\n\n def get_connection(self, region):\n self.region = region\n self.conn = boto.ec2.connect_to_region(region, aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_key)\n\n return self.conn\n\n def get_security_groups(self):\n self.groups = [g.name for g in self.conn.get_all_security_groups()]\n\n return self.groups\n\n def generate_key_pair(self, name, user_id, account_id, region_id):\n\n r = random.randint(10000,99999)\n\n key = self.conn.create_key_pair('obliterator_{}'.format(r))\n\n os.mkdir('/tmp/.obliterator_{}_key'.format(r))\n\n key.save('/tmp/.obliterator_{}_key'.format(r))\n\n f = open('/tmp/.obliterator_{r}_key/obliterator_{r}.pem'.format(r=r), 'r').read()\n\n a = AWSAccount.query.filter_by(id=account_id).first()\n re = AWSRegion.query.filter_by(id=region_id).first()\n\n k = SSHKey(name='AWS - {} - {}'.format(name,re.name), description='This key was autogenerated when creating an AWS account', user_id=user_id, key_type='AWS', key=base64.b64encode(f), creation_date=datetime.now(), aws_name='obliterator_{}'.format(r), aws_account_id=a.id, aws_region_id=re.id)\n\n db.session.add(k)\n db.session.commit()\n\n shutil.rmtree('/tmp/.obliterator_{r}_key/'.format(r=r))\n\n return k.id\n\n\n def validate_credentials(self):\n try:\n x = boto.ec2.connect_to_region('us-east-1', aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_key)\n x.get_all_regions()\n return True\n except EC2ResponseError as e:\n if '401 Unauthorized' in str(e):\n return False\n else:\n return False\n\n def get_regions(self):\n self.regions = [l.name for l in boto.ec2.regions(aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_key)]\n\n return self.regions\n\n\n def create_security_group(self):\n\n try:\n self.conn.delete_security_group('obliterator')\n except:\n pass\n obli = self.conn.create_security_group('obliterator', 'The Obliterator Security Group')\n results = []\n results.append(obli.authorize(ip_protocol='tcp', from_port=22, to_port=22, cidr_ip='0.0.0.0/0'))\n results.append(obli.authorize(ip_protocol='tcp', from_port=6254, to_port=6254, cidr_ip='0.0.0.0/0'))\n\n return all(results)\n\n def create_instance(self, ami, key, instance_type='t2.small'):\n\n return self.conn.run_instances(ami, key_name=key, security_groups=['obliterator'], instance_type='t1.micro')\n\n def delete_instance(self, instance):\n\n return self.conn.terminate_instances(instance_ids=[instance])\n\n\n\n","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"411588420","text":"\nname=input(\"What is your name?\")\n\nif name==\"Tim\":\n print(\"Greetings, Tim the Enchanter\")\n \nelif name==\"Brian\":\n print(\"Bad luck, Brian\")\nelse:\n print(\"Hello\"+name+\".\")\n\nwhile True: \n topic =input(\"What do you want to talk about?\")\n if topic ==\"nothing\":\n break\n like=input(\"Do you like\"+topic+\"?\")\n response=input(\"Why do you think that?\")\n print(\"I also think that\", response)\n \nprint(\"Okay. Goodbye,\"+name+\"!\")\n\n\n","sub_path":"interaction_while.py","file_name":"interaction_while.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"23463337","text":"import numpy as np\n\nfrom PaPr.diff_calssify.scikit_learn import bayes_sci\n\nfoo1 = bayes_sci()\nfoo1.read_matrix('/home/yangfang/PCSF/test_java_gificlee/all_kegg_matrix_re111.txt')\nfoo1.tree_label\nfoo1.profile\nfoo1.prepare_data()\nfoo1.input_genes_labels\nfoo1.input_genes_data\nfoo1.input_genes_names\nfoo1.profile_names\nfoo1.profile_data\n\nfoo1.get_no_info_gene('/home/yangfang/PCSF/clime_roc/species111.abbrev.manual_binary.nwk')\n# foo1.null_by_means()\nfoo1.get_dp_score()\nfoo1.read_input('/home/yangfang/GFICLEE/test_corum_clime/input/1_0.txt')\nfoo1.clime_name = foo1.input_genes_names\naffi = list(range(len(foo1.clime_name)))\naffi = np.array(affi)\nfoo1.clime_index = affi + 1\nfoo1.get_each_cluster_pre_sci()\nresult = foo1.run_bayes_sci()\n\n\nresult[result['name'] == 'TAF11']\n\n\n\nx = np.where(foo1.profile_names == 'TAF11')[0][0]\ny = np.where(foo1.profile_names == 'RPL22L1')[0][0]\nz = np.where(foo1.profile_names == 'DDB1')[0][0]\nfoo1.dp_single_loss[x]\nfoo1.dp_single_loss[y]\nfoo1.dp_single_loss[z]\n\ntem = []\nfor i in foo1.clime_name:\n gain_node = foo1.dp_gain_node[np.where(foo1.profile_names == i)[0][0]]\n if foo1.dp_gain_node[x] == gain_node:\n print(i)\n\ny = foo1.run_bayes_sci_single(x)\nprint(y)","sub_path":"test/test_scikit_learn.py","file_name":"test_scikit_learn.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"127816875","text":"import numbers\r\n\r\n\r\nclass Polynomial:\r\n def __init__(self, p: list):\r\n self.p = p\r\n\r\n def __repr__(self):\r\n return \"Polynomial(\" + str(self.p) + \")\"\r\n\r\n def scalar_mul(self, c: float) -> list:\r\n result = []\r\n for a in self.p:\r\n result += [a * c]\r\n self.p = result\r\n return Polynomial(result)\r\n\r\n def evaluate(self, x: float) -> float:\r\n result = 0\r\n for i, a in enumerate(self.p):\r\n result += a * x ** i\r\n return round(result, 3)\r\n\r\n def derivate(self) -> list:\r\n result = []\r\n for i, a in enumerate(self.p):\r\n if i > 0:\r\n result += [i * a]\r\n self.p = result\r\n return Polynomial(result)\r\n\r\n def integrate(self,\r\n c=0. # float\r\n ) -> list:\r\n result = [float(c)]\r\n for i, a in enumerate(self.p):\r\n result += [round(a/(i+1), 3)]\r\n self.p = result\r\n return Polynomial(result)\r\n\r\n def __add__(self, oth) -> list:\r\n if isinstance(oth, Polynomial):\r\n maxlen = max(len(self.p), len(oth.p))\r\n result = []\r\n for i in range(maxlen):\r\n result += [(self.p[i] if i < len(self.p) else 0) +\r\n (oth.p[i] if i < len(oth.p) else 0)]\r\n return result\r\n elif isinstance(oth, numbers.Number):\r\n return [self.p[0] + oth] + self.p[1:]\r\n else:\r\n raise TypeError(\"cant add with \" + str(type(oth)))\r\n\r\n def __radd__(self, other) -> list:\r\n if isinstance(other, numbers.Number):\r\n return [self.p[0] + other] + self.p[1:]\r\n else:\r\n raise TypeError(\"cant add with \" + str(type(other)))\r\n\r\n def __mul__(self, other) -> list:\r\n if isinstance(other, Polynomial):\r\n result = []\r\n for k in range(len(self.p) + len(other.p) - 1):\r\n rk = 0\r\n for i in range(k + 1):\r\n rk += ((self.p[i] if i < len(self.p) else 0) *\r\n (other.p[k-i] if k-i < len(other.p) else 0))\r\n result += [rk]\r\n return result\r\n elif isinstance(other, numbers.Number):\r\n result = [self.p[0] + other] + self.p[1:]\r\n return self.scalar_mul(other)\r\n else:\r\n raise TypeError(\"cant multiply with \" + str(type(other)))\r\n\r\n def __rmul__(self, other) -> list:\r\n if isinstance(other, numbers.Number):\r\n result = [self.p[0] + other] + self.p[1:]\r\n return self.scalar_mul(other)\r\n else:\r\n raise TypeError(\"cant multiply with \" + str(type(other)))\r\n","sub_path":"Einfuehrung_in_die_Programmierung/skipt/useful_algorithms/polynomial_v3.py","file_name":"polynomial_v3.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524171988","text":"from flask import Flask, render_template, request\nimport json\nimport math\nfrom functional import seq\nfrom Course import Course\n\n\napp = Flask(__name__)\n\n\n#\n# Load courses\n#\ncourses = []\nwith open('data/courses.json') as f:\n\tcourses = list(map(\n\t\tlambda c: Course(c),\n\t\tjson.loads(f.read())\n\t))\n\n\n#\n# Routes\n#\n@app.route('/')\ndef index():\n\treturn render_template('index.html')\n\n\n@app.route('/subject/', methods=['GET'])\ndef subject(subject):\n\treturn render_template('courses.html', courses=seq(courses)\n\t\t.filter(lambda c: c.subject == subject))\n\n\n@app.route('/query', methods=['GET'])\ndef query():\n\tif(len(request.args) == 0):\n\t\treturn render_template('query.html')\n\n\tsubject = request.args.get('subject')\n\tmin_query_number = request.args.get('min')\n\tmax_query_number = request.args.get('max')\n\ttitle = request.args.get('title')\n\tinstructor = request.args.get('instructor')\n\n\tif max_query_number == None or max_query_number == '':\n\t\tmax_query_number = math.inf\n\telse:\n\t\tmax_query_number = int(max_query_number)\n\n\tif min_query_number == None or min_query_number == '':\n\t\tmin_query_number = 0\n\telse:\n\t\tmin_query_number = int(min_query_number)\n\n\tif(request.args.get('compact') == 'on'):\n\t\ttemplate = 'courses-compact.html'\n\telse:\n\t\ttemplate = 'courses.html'\n\n\treturn render_template(template, courses=seq(courses)\n\t\t.filter(lambda c: subject == None or subject == '' or c.subject.lower() == subject.lower())\n\t\t.filter(lambda c: c.number >= min_query_number)\n\t\t.filter(lambda c: c.number <= max_query_number)\n\t\t.filter(lambda c: title == None or title == '' or title.lower() in c.title.lower())\n\t\t.filter(lambda c: instructor == None or instructor == '' or any(map(lambda t: instructor.lower() in t.name.lower() , c.instructors))))\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"495359868","text":"import copy\n\n\ndef xor_i(index: int, bit_l: str, bit_s: str):\n\tresult = ''\n\tfor i in range(len(bit_l)):\n\t\tif i >= index and i < index + len(bit_s):\n\t\t\tif bit_l[i] == bit_s[i - index]:\n\t\t\t\tresult += '0'\n\t\t\telse:\n\t\t\t\tresult += '1'\n\t\telse:\n\t\t\tresult += bit_l[i]\n\n\treturn result\n\n\ndef main():\n\tresult = []\n\traw_bit = input()\n\toriginal_error_bit = raw_bit.replace(' ', '')[-4:]\n\traw_bit = raw_bit.replace(' ', '')[:-4]\n\tfor i in range(16, 32):\n\t\tdivisor = format(i, 'b').zfill(5)\n\t\ttarget = copy.deepcopy(raw_bit)\n\t\t# print(divisor)\n\t\tfor j in range(len(target) - 4):\n\t\t\tif target[j] == '0':\n\t\t\t\tcontinue\n\t\t\ttarget = xor_i(j, target, divisor)\n\t\t# print(target)\n\t\tif original_error_bit == target[-4:]:\n\t\t\tresult.append(divisor)\n\tprint(result)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"src/error_detection.py","file_name":"error_detection.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"93062698","text":"from runonce.util import *\n\n\ndef upgrade():\n session = getSession()\n #\n # Add the ROLE records\n #\n executeListCommands( session,\n loadDataFile( \"roles.yaml\", __name__ ),\n \"INSERT INTO role ( r_id, r_role, r_remark ) \"\n \"VALUES( :r_id, :r_role, :r_remark )\" )\n #\n # Add the MODULE ACCESS records\n #\n executeListCommands( session,\n loadDataFile( \"module_access.yaml\", __name__ ),\n \"INSERT INTO mod_access ( ma_id, ma_module, ma_description ) \"\n \"VALUES ( :ma_id, :ma_module, :ma_description)\" )\n #\n # Add the USER records\n #\n executeListCommands( session,\n loadDataFile( \"users.yaml\", __name__ ),\n \"INSERT INTO user ( u_id, u_active, u_name, u_role, u_hash_password, u_must_change, \"\n \"u_first_name, u_last_name, u_email, u_locale, u_listitems ) \"\n \"VALUES( :u_id, :u_active, :u_name, :u_role, :u_hash_password, :u_must_change, \"\n \":u_first_name, :u_last_name, :u_email, :u_locale, :u_listitems )\" )\n\n #\n # Add the ROLE ACCESS records\n #\n executeListCommands( session,\n loadDataFile( \"role_access.yaml\", __name__ ),\n \"INSERT INTO role_access ( ra_id, ra_r_id, ra_module, ra_create, ra_read, ra_update, ra_delete, r_remark ) \"\n \"VALUES ( :ra_id, :ra_r_id, :ra_module, :ra_create, :ra_read, :ra_update, :ra_delete, :r_remark )\" )\n #\n # Add the NEWS records\n #\n startDate = datetime.utcnow().date()\n endDate = ( datetime.utcnow() + timedelta( days = 100 ) ).date()\n executeListCommands( session,\n [ { 'n_id': 1,\n 'n_message': 'NOTIFICATION, this is an alert message',\n 'n_active': True,\n 'n_alert': True,\n 'n_keep': True,\n 'n_start_date': startDate,\n 'n_end_date': endDate },\n { \"n_id\": 2,\n 'n_message': 'Hello world, this is a normal message',\n 'n_active': True,\n 'n_alert': False,\n 'n_keep': True,\n 'n_start_date': startDate,\n 'n_end_date': endDate }\n ],\n \"INSERT INTO news ( n_id, n_message, n_active, n_alert, n_keep, n_start_date, n_end_date ) \"\n \"VALUES( :n_id, :n_message, :n_active, :n_alert, :n_keep, :n_start_date, :n_end_date )\" )\n #\n # Add the LANGUAGE records\n #\n executeListCommands( session,\n loadDataFile( \"languages.yaml\", __name__ ),\n \"INSERT INTO language ( la_id, la_label, la_code2, la_code3, la_country_code2, la_country_code3 )\"\n \"VALUES ( :la_id, :la_label, :la_code2, :la_code3, :la_country_code2, :la_country_code3 )\" )\n #\n # Add the LANGUAGE TRANSACTION label records\n #\n session.execute( \"DELETE FROM language_translates\" )\n executeListCommands( session,\n loadDataFile( \"language_reference.yaml\", __name__ ),\n \"INSERT INTO language_translates ( lt_id, lt_label )\"\n \"VALUES ( :lt_id, :lt_label )\" )\n #\n # Add the X records\n #\n session.execute( \"DELETE FROM language_reference\" )\n for language in ( 'en', 'nl', 'de', 'fr', 'it' ):\n executeListCommands( session,\n loadDataFile( \"language-{}.yaml\".format( language ), __name__ ),\n \"INSERT INTO language_reference ( lr_la_id, lr_lt_id, tr_text )\"\n \"VALUES ( :lr_la_id, :lr_lt_id, :tr_text )\" )\n\n session.commit()\n return\n\n\ndef downgrade():\n return","sub_path":"runonce/WEBAPP_CORE_V2.py","file_name":"WEBAPP_CORE_V2.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"556935556","text":"from . import plugin\nfrom mysql.connector import Error\nimport json\nimport mysql.connector\n\nclass DBStorePlugin(plugin.Plugin):\n def __init__(self, web_client, plugin_config):\n super().__init__(web_client=web_client, plugin_config=plugin_config)\n self.__init_db()\n self.__cache = None\n\n\n def __init_db(self):\n try:\n self.__conn = mysql.connector.connect(\n host=self._config.get(\"DB_HOST\"),\n database=self._config.get(\"DB_NAME\"),\n user=self._config.get(\"DB_USER\"),\n password=self._config.get(\"DB_PASSWORD\")\n )\n except Error as e:\n self._log.exception(f\"Failed to connect to db: {e}\")\n self.__conn = None\n\n\n def __store_message(self, data):\n if not self.__cache:\n self.__cache = {\n \"users\": {},\n \"channels\": {},\n \"teams\": {},\n }\n\n if data.get(\"subtype\") == \"message_changed\":\n message = data.get(\"message\")\n if message:\n client_msg_id = message.get(\"client_msg_id\")\n text = message.get(\"text\")\n if client_msg_id and text:\n self.__update_message(\n client_msg_id=client_msg_id,\n text=text,\n )\n return\n\n timestamp = data[\"ts\"].split(\".\")[0]\n #if \"bot_id\" in data.keys():\n # return\n try:\n slack_user_id = data.get(\"user\")\n if not slack_user_id:\n slack_user_id = data.get(\"bot_id\")\n except KeyError as ke:\n return\n try:\n slack_team_id = data[\"team\"]\n except KeyError as e:\n return\n client_msg_id = data.get('client_msg_id')\n slack_channel_id = data[\"channel\"]\n text = data[\"text\"]\n files = []\n if \"files\" in data.keys():\n files = data['files']\n if \"file\" in data.keys():\n files.append(data['file'])\n\n if not slack_team_id in self.__cache[\"teams\"].keys():\n team_id = self.__insert(\"tbl_teams\", \"slack_team_id\", slack_team_id, \"slack_team_id\", slack_team_id)\n self.__cache[\"teams\"][slack_team_id] = team_id\n else:\n team_id = self.__cache[\"teams\"][slack_team_id]\n if not slack_user_id in self.__cache[\"users\"].keys():\n columns = [\"slack_user_id\", \"team_id\"]\n values = [slack_user_id, team_id]\n if \"username\" in data.keys():\n columns.append(\"username\")\n values.append(data[\"username\"])\n user_id = self.__insert(\"tbl_users\", columns, values, \"slack_user_id\", slack_user_id)\n self.__cache[\"users\"][slack_user_id] = user_id\n else:\n user_id = self.__cache[\"users\"][slack_user_id]\n if not slack_channel_id in self.__cache[\"channels\"].keys():\n channel_id = self.__insert(\"tbl_channels\", [\"slack_channel_id\", \"team_id\"], [slack_channel_id, team_id], \"slack_channel_id\", slack_channel_id)\n self.__cache[\"channels\"][slack_channel_id] = channel_id\n else:\n channel_id = self.__cache[\"channels\"][slack_channel_id]\n team_url = self.__select(f\"select team_url from tbl_teams where id = {team_id}\")\n if len(team_url) > 0 and len(team_url[0]) > 0 and team_url[0][0]:\n team_url = team_url[0][0]\n archive_ts = data[\"ts\"].replace(\".\", \"\")\n archive_url = \"/\".join([team_url, \"archives\", slack_channel_id, f\"p{archive_ts}\"])\n else:\n archive_url = None\n message_id = self.__insert_message(team_id, channel_id, user_id, timestamp, client_msg_id, archive_url, text)\n self.__handle_files(files, message_id)\n if \"user_profile\" in data.keys():\n self.__handle_user_profile(data['user_profile'], user_id)\n\n\n def __select(self, query):\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n cursor.execute(query)\n records = cursor.fetchall()\n cursor.close()\n return records\n\n\n def __get_id(self, table, slack_id_column, slack_id):\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n query = f\"select id from {table} where {slack_id_column} = '{slack_id}'\"\n cursor.execute(query)\n records = cursor.fetchall()\n cursor.close()\n if records:\n return records\n return False\n\n\n def __insert(self, table, columns, values, slack_id_column, slack_id):\n item_id = self.__get_id(table, slack_id_column, slack_id)\n if item_id:\n return item_id[0][0]\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n if isinstance(columns, list):\n columns = \", \".join(columns)\n if isinstance(values, list):\n for index, value in enumerate(values):\n if isinstance(value, int):\n self._log.debug(f\"inserting {str(value)} at index {value}\")\n values[index] = str(value)\n else:\n values[index] = value.replace(u\"'\", u\"\\'\")\n self._log.debug(values)\n values = u\", \".join(\"'\" + value + \"'\" for value in values)\n else:\n values = f\"'{values}'\"\n query = f\"insert into {table}({columns}) values ({values})\"\n self._log.debug(query)\n cursor.execute(query)\n self.__conn.commit()\n item_id = self.__get_id(table, slack_id_column, slack_id)\n cursor.close()\n return item_id[0][0]\n\n\n def __get_message_id(self, timestamp, user_id):\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n query = \"select id from tbl_messages where timestamp = %s and user_id = %s\"\n cursor.execute(query, (timestamp, user_id))\n records = cursor.fetchall()\n cursor.close()\n if records:\n return records[0][0]\n return False\n\n\n def __insert_message(self, team_id, channel_id, user_id, timestamp, client_msg_id, archive_url, text):\n message_id = self.__get_message_id(timestamp, user_id)\n if message_id:\n return message_id\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n query = \"insert into tbl_messages (team_id, channel_id, user_id, timestamp, client_msg_id, archive_url, text) values (%s, %s, %s, %s, %s, %s, %s)\"\n self._log.debug(\"Inserting message:\")\n self._log.debug(query % (team_id, channel_id, user_id, timestamp, client_msg_id, archive_url, text))\n cursor.execute(query, (team_id, channel_id, user_id, timestamp, client_msg_id, archive_url, text))\n self.__conn.commit()\n cursor.close()\n message_id = self.__get_message_id(timestamp, user_id)\n self._log.debug(f\"Got message ID : ({message_id})\")\n return message_id\n\n\n def __update_message(self, client_msg_id, text):\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n query = \"update tbl_messages set text = %s where client_msg_id = %s\"\n self._log.debug(query % (text, client_msg_id))\n cursor.execute(query, (text, client_msg_id))\n self.__conn.commit()\n cursor.close()\n\n\n def __insert_file(self, file_data):\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n query = \"insert into tbl_files (message_id, mimetype, thumb_800, thumb_80, permalink, permalink_public, name) values (%s, %s, %s, %s, %s, %s, %s)\"\n values = (\n file_data['message_id'],\n file_data['mimetype'],\n file_data.get('thumb_800'),\n file_data.get('thumb_80'),\n file_data.get('permalink'),\n file_data.get('permalink_public'),\n file_data.get('name'),\n )\n self._log.debug(query % values)\n cursor.execute(query, values)\n self.__conn.commit()\n cursor.close()\n\n\n def __handle_files(self, files, message_id):\n for file_data in files:\n file = {\n 'message_id': message_id,\n 'mimetype': file_data['mimetype'],\n }\n if 'thumb_800' in file_data.keys():\n file['thumb_800'] = file_data['thumb_800']\n if 'thumb_80' in file_data.keys():\n file['thumb_80'] = file_data['thumb_80']\n if 'permalink' in file_data.keys():\n file['permalink'] = file_data['permalink']\n if 'permalink_public' in file_data.keys() and 'is_public' in file_data.keys() and file_data['is_public'] == True:\n file['permalink_public'] = file_data['permalink_public']\n if 'name' in file_data.keys():\n file['name'] = file_data['name']\n elif 'title' in file_data.keys():\n file['name'] = file_data['title']\n self.__insert_file(file)\n\n\n def __handle_user_profile(self, user_profile, user_id):\n subs = []\n query = \"update tbl_users set\"\n if \"name\" in user_profile.keys():\n query += \" username = %s,\"\n subs.append(user_profile['name'])\n if \"real_name\" in user_profile.keys():\n query += \" full_name = %s,\"\n subs.append(user_profile['real_name'])\n if \"image_72\" in user_profile.keys():\n query += \" avatar_url = %s,\"\n subs.append(user_profile['image_72'])\n if not subs:\n return\n if not self.__conn or not self.__conn.is_connected():\n self.__init_db()\n cursor = self.__conn.cursor()\n query = query[:-1]\n query += \" where id = %s\"\n subs.append(user_id)\n self._log.debug(query % tuple(subs))\n cursor.execute(query, tuple(subs))\n self.__conn.commit()\n cursor.close()\n\n\n def receive(self, request):\n try:\n self.__store_message(request)\n except mysql.connector.errors.IntegrityError as ie:\n self._log.warning(f\"Refusing to insert duplicate message: {ie}\")\n except Exception as e:\n self._log.exception(e)\n return []\n","sub_path":"plugins/dbstore.py","file_name":"dbstore.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"470871648","text":"\"\"\"RB_scatter.py\n\nauthor: Auke Visser\ndate: 27.10.2016\n\nThis script calls a routine to calculate the irrigation impact on \ntemperature with either the threshold- or the regression-based\napproach. The user has the option to print or visualize output.\n\n\"\"\"\n\nimport netCDF4 as nc\nimport numpy as np\nimport scipy\nimport os\nimport matplotlib\nmatplotlib.rcParams['backend'] = \"Qt4Agg\"\nfrom mpl_toolkits.basemap import Basemap\nfrom matplotlib.colors import LogNorm\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\nimport scipy.stats as stats\nimport matplotlib.patches as mpatches\nimport matplotlib.colors as colors\n\nexecfile('calc_irr_impact_thres.py')\nexecfile('calc_irr_impact_regr.py')\n\n#################################\n#User-specified options\n#################################\ndatasource = \"CRU\"\ntemp_product = \"tmx\"\nresponse = \"PD\"\nt_res = \"seasonal\"\nmethod = \"threshold\"\nthres_irr = 0.25\n\nyr_start1 = 1901\nyr_end1 = 1930\nyr_start2 = 1981\nyr_end2 = 2010\n\n#figsave = True\n#figformat = 'png'\n#################################\n\n_, indvals, codvals = calc_irr_impact_regr(datasource,temp_product,response,t_res,thres_irr,False,yr_start1,yr_end1,yr_start2,yr_end2)\n\nirrvals = indvals[0][0]\nTvals = indvals[0][1]\n\nfor i in range(1,len(indvals)):\n irrvals = np.append(irrvals,indvals[i][0],axis=0)\n Tvals = np.append(Tvals,indvals[i][1],axis=0)\n \ns = stats.linregress(irrvals,Tvals).slope\ni = stats.linregress(irrvals,Tvals).intercept\n\nplt.figure(figsize=(12,8))\nplt.scatter(irrvals,Tvals)\nplt.plot([-0.2,1],[-0.2*s+i,s+i],'k--')\nplt.xlabel('PD $f_{irr}$ [-]')\nplt.ylabel('$\\Delta T_{irr}$ [$^\\circ$C]')\nplt.title('Dataset: %s %s %s %1.2f'%(datasource,temp_product,response,thres_irr))\n\ncc = np.corrcoef(irrvals,Tvals)[1,0]\nplt.text(0.8,0,'$r^2 = %1.4f$'%cc)\n\nplt.show(block=False)","sub_path":"observational_analysis/RB_scatter.py","file_name":"RB_scatter.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"588301958","text":"import urllib\nimport urllib2\nimport json\nimport urlparse\nimport time\nimport logging\nimport hmac\nimport hashlib\nimport base64\nimport abc\n\nfrom urllib2 import HTTPError\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(\"API_CLIENT\")\nlogger.setLevel(logging.DEBUG)\n\n\nclass AbsAPIClient(object): # provide overwrite later\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def send_request(self, url, data=None, datafunc=json.loads):\n return\n\n\nclass APIClientHTTPError(Exception):\n def __init__(self, reason, code, *args, **kwargs):\n super(self).__init__(reason, code, *args, **kwargs)\n self.code = code\n self.message = reason\n\n\nclass APIClient(AbsAPIClient):\n def __init__(self, apikey, seckey, url):\n self.opener = urllib2.build_opener()\n self._baseurl = url\n self._ak = str(apikey)\n self._sk = str(seckey)\n\n def _sign_msg(self, msg):\n dig = hmac.new(self._sk, msg, digestmod=hashlib.sha256).digest()\n return base64.b64encode(dig).decode()\n\n def _sign_url(self, _url):\n url = (\"/\" + _url) if not _url.startswith(\"/\") else _url\n url_parts = urlparse.urlparse(url)\n qs = urlparse.parse_qs(url_parts.query)\n qs[\"timestamp\"] = time.time() # UNIX time\n qs[\"apikey\"] = self._ak\n new_qs = urllib.urlencode(qs, True)\n tmpurl = urlparse.urlunparse(\n list(url_parts[0:4]) + [new_qs] + list(url_parts[5:]))\n final_url = tmpurl + \"&signature=\" + self._sign_msg(tmpurl) # sign url\n return final_url\n\n def send_request(self, url, data=None, datafunc=json.loads):\n logger.debug(\"send to: %s\" % urlparse.urljoin(\n self._baseurl, self._sign_url(url)))\n try:\n resp = self.opener.open(urlparse.urljoin(\n self._baseurl, self._sign_url(url)), data)\n return resp.code, datafunc(resp.read()) if datafunc else resp.read()\n except HTTPError as e:\n raise Exception(e.msg)\n\n\nclient = APIClient(**SSO_API_AUTH_SETTING)\n","sub_path":"superset/custom_security/apiclient.py","file_name":"apiclient.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"184721830","text":"# -*- coding: utf-8 -*-\n#試作品\nimport RPi.GPIO as GPIO\nimport time\nimport wiringpi as pi\nimport dht11 #gitでクローンする\n\ntemp_sensor=23 #GPIO23に接続\n\ndef temp_init(): #初期設定\n GPIO.setmode(GPIO.BCM)\n pi.wiringPiSetupGpio() # GPIO名で番号を指定する\n pi.pinMode( temp_sensor, pi.INPUT ) #温湿度センサのデータを入力として扱う\n\ndef main(): #動作設定\n\n temp_init() #初期設定の呼び出し\n\n instance = dht11.DHT11( pin = temp_sensor ) #温湿度センサのデータをinstanceに格納\n while True:\n result = instance.read() #resultにデータを読ませる\n if result.is_valid(): #もしresultにデータが入っている場合\n print(\"Temperature = \",result.temperature,\"C\",\" Humidity = \",result.humidity,\"%\") #データにある温度と湿度を画面に表示\n time.sleep(1)\n\nif __name__ == '__main__':\n\n try: #通常時\n main()\n except KeyboardInterrupt: #キーボードが押されたとき\n pass\n finally: #終了時(ctrl+cなど)\n GPIO.cleanup() #GPIOの終了\n","sub_path":"temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"109875246","text":"__author__ = 'mikaelmork'\n\n# Requirement to access environment variables\nimport os\n\n# Requirement to access system arguments\nimport sys\n\n# Requirements for making calls to Heroku API\nimport requests\nimport base64\nimport json\n\n# App name\nAPP = os.environ['HEROKU_APP_NAME']\n\n# Heroku API key\nKEY = bytes(os.environ['HEROKU_API_KEY'], encoding='UTF-8')\n\n# Generate Base64 encoded API Key\nBASEKEY = base64.b64encode(b':' + KEY)\n\n# Create headers for API call\nHEADERS = {\n\t'Accept': 'application/vnd.heroku+json; version=3',\n\t'Authorization': BASEKEY,\n}\n\ndef scale(process, size):\n\t# Define output variable\n\toutput = ''\n\n\t# Create payload (scale)\n\tpayload = {'quantity': size}\n\n\t# Generate JSON\n\tjson_payload = json.dumps(payload)\n\n\t# Compose URL\n\turl = \"https://api.heroku.com/apps/\" + APP + \"/formation/\" + process\n\n\ttry:\n\t\t# Make API call\n\t\tresult = requests.patch(url, headers=HEADERS, data=json_payload)\n\n\t\tif result.status_code == 200:\n\t\t\t# API call success\n\t\t\toutput = True\n\t\n\t\t\tprint('%s (%s): scaled to %s' % (APP, process, size))\n\t\telse:\n\t\t\t# API call failure\n\t\t\toutput = False\n\t\n\t\t\tprint('scaler.py: An error occurred during the API call, HTTP status code: %s' % result.status_code)\n\n\texcept Exception as e:\n\t\t# API call failure\n\t\toutput = False\n\n\t\tprint('scaler.py: An error occurred during the API call: %s' % e)\n\n\treturn output\n\ntry:\n\tif sys.argv[1]:\n\t\t# Scale web\n\t\tscale('web', sys.argv[1])\n\n\tif sys.argv[2]:\n\t\t# Scale worker\n\t\tscale('worker', sys.argv[2])\nexcept Exception:\n\tprint('scaler.py: There was a problem with the provided arguments.')\n","sub_path":"scaler.py","file_name":"scaler.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"433753323","text":"import datetime\nimport os\n\nfrom docopt import docopt as docoptinit\n\nhaproxy_doc = \"\"\"\nUsage:\n haproxy.py [options]\n\nOptions:\n --port=\n --dest=\n --daemon\n --timeout_server= Timeout For Server [default: 86400000]\n --timeout_client= Timeout For Server [default: 86400000]\n\n\"\"\"\n\n\n# haproxy --port port --dest host:port\ndef haproxy(argv, toy=False):\n docopt = docoptinit(haproxy_doc, argv)\n print(docopt)\n port = int(docopt['--port'])\n opt = {'dest': docopt['--dest'],\n 'timeout_server': docopt['--timeout_server'],\n 'timeout_client': docopt['--timeout_client']}\n cfg = \"\"\"\n global\n debug\n log 127.0.0.1 local0\n maxconn 20480\n\n defaults\n mode tcp\n log global\n option tcplog\n option tcp-check\n timeout connect 5000\n timeout client {timeout_client} # 1day 86400 * 1000 ms\n timeout server {timeout_server}\n\n\n frontend shadow1\n bind :9998\n option tcplog\n default_backend haproxy-nodes\n\n backend haproxy-nodes\n server node-1 {dest} check\n\n \"\"\".format(**opt)\n print(cfg)\n home = os.path.expanduser('~')\n if not os.path.exists('{}/.qbx'.format(home)):\n print('make directory ~/.qbx')\n os.system('mkdir ~/.qbx')\n filename = '{}/.qbx/haproxy-{}.cfg'.format(home, str(int(datetime.datetime.now().timestamp() * 10e6)))\n fp = open(filename, 'w')\n fp.write(cfg)\n fp.close()\n\n if docopt['--daemon']:\n addon = '--restart always -d --name haproxy-{}'.format(port)\n else:\n addon = '-it --rm'\n cmd = 'sudo docker run {} -v {}:/usr/local/etc/haproxy/haproxy.cfg -p {}:9998 haproxy'\n cmd = cmd.format(addon, filename, port)\n if toy:\n print(cmd)\n else:\n os.system(cmd)\n\n\nif __name__ == '__main__':\n haproxy(['--port', '123', '--daemon'], toy=True)\n","sub_path":"qbx/haproxy.py","file_name":"haproxy.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"627020168","text":"# -*- coding: utf-8 -*-\n'''\nSet up the correct search system\n'''\n\n# Import python libs\nimport os\n\n# Import bonneville libs\nimport bonneville.minion\nimport bonneville.loader\nimport bonneville.utils\n\n\ndef iter_ret(opts, ret):\n '''\n Yield returner data if the external job cache is enabled\n '''\n if not opts['ext_job_cache']:\n raise StopIteration\n get_load = '{0}.get_load'.format(opts['ext_job_cache'])\n get_jid = '{0}.get_jid'.format(opts['ext_job_cache'])\n get_jids = '{0}.get_jids'.format(opts['ext_job_cache'])\n if get_load not in ret:\n raise StopIteration\n else:\n get_load = ret[get_load]\n if get_jid not in ret:\n raise StopIteration\n else:\n get_jid = ret[get_jid]\n if get_jids not in ret:\n raise StopIteration\n else:\n get_jids = ret[get_jids]\n for jid in get_jids():\n jids = {}\n jids['load'] = get_load(jid)\n jids['ret'] = get_jid(jid)\n jids['jid'] = jid\n yield jids\n\n\ndef _iter_dir(dir_, env):\n ret = []\n for fn_ in os.listdir(dir_):\n path = os.path.join(dir_, fn_)\n if os.path.isdir(path):\n yield _iter_dir(path, env)\n elif os.path.isfile(path):\n with bonneville.utils.fopen(path) as fp_:\n if bonneville.utils.istextfile(fp_):\n ret.append(\n {'path': unicode(path),\n 'env': unicode(env),\n 'content': unicode(fp_.read())}\n )\n else:\n ret.append(\n {'path': unicode(path),\n 'env': unicode(env),\n 'content': u'bin'}\n )\n yield ret\n\n\ndef iter_roots(roots):\n '''\n Accepts the file_roots or the pillar_roots structures and yields\n {'path': ,\n 'env': ,\n 'cont': }\n '''\n for env, dirs in roots.items():\n for dir_ in dirs:\n if not os.path.isdir(dir_):\n continue\n for ret in _iter_dir(dir_, env):\n yield ret\n\n\nclass Search(object):\n '''\n Set up the object than manages search operations\n '''\n def __init__(self, opts):\n self.opts = opts\n self.mminion = bonneville.minion.MasterMinion(\n self.opts,\n states=False,\n rend=False,\n matcher=False)\n self.search = bonneville.loader.search(self.opts, self.mminion.returners)\n\n def index(self):\n '''\n Execute a search index run\n '''\n ifun = '{0}.index'.format(self.opts.get('search', ''))\n if ifun not in self.search:\n return\n return self.search[ifun]()\n\n def query(self, term):\n '''\n Search the index for the given term\n '''\n qfun = '{0}.query'.format(self.opts.get('search', ''))\n if qfun not in self.search:\n return\n return self.search[qfun](term)\n","sub_path":"bonneville/search/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"620641228","text":"#Embedded file name: carbon/common/script/util\\xpermutations.py\n\"\"\"\ncode borrowed from: http://code.activestate.com/recipes/190465/\n\nUseful methods for generating combinations and permutations from any list\n\norginal doc:\nxpermutations.py\nGenerators for calculating a) the permutations of a sequence and\nb) the combinations and selections of a number of elements from a\nsequence. Uses Python 2.2 generators.\n\nSimilar solutions found also in comp.lang.python\n\nKeywords: generator, combination, permutation, selection\n\nSee also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962\nSee also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66463\nSee also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66465\n\"\"\"\n\ndef xcombinations(items, n):\n if n == 0:\n yield []\n else:\n for i in xrange(len(items)):\n for cc in xcombinations(items[:i] + items[i + 1:], n - 1):\n yield [items[i]] + cc\n\n\ndef xuniqueCombinations(items, n):\n if n == 0:\n yield []\n else:\n for i in xrange(len(items)):\n for cc in xuniqueCombinations(items[i + 1:], n - 1):\n yield [items[i]] + cc\n\n\ndef xselections(items, n):\n if n == 0:\n yield []\n else:\n for i in xrange(len(items)):\n for ss in xselections(items, n - 1):\n yield [items[i]] + ss\n\n\ndef xpermutations(items):\n return xcombinations(items, len(items))\n\n\nexports = {'util.xcombinations': xcombinations,\n 'util.xuniqueCombinations': xuniqueCombinations,\n 'util.xselections': xselections,\n 'util.xpermutations': xpermutations}\n","sub_path":"carbon/common/script/util/xpermutations.py","file_name":"xpermutations.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"623667841","text":"from django.shortcuts import render, redirect\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse, HttpResponseBadRequest\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils import timezone\nfrom django.db.models import Avg\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.datastructures import MultiValueDictKeyError\n\nfrom store.models import *\n# Create your views here.\n\n\ndef index(request):\n return render(request, 'store/index.html')\n\n\n@csrf_exempt\ndef bookDetailView(request, bid):\n book = get_object_or_404(Book, pk=bid)\n book.rating = BookRating.objects.filter(\n book=book).aggregate(rating=Avg('rating'))['rating']\n book.save()\n\n context = {\n 'book': None,\n 'num_available': None,\n }\n if request.user.is_authenticated:\n try:\n context['user_review'] = BookRating.objects.get(\n book=book, username=request.user).rating\n except ObjectDoesNotExist:\n context['user_review'] = None\n\n context['num_available'] = BookCopy.objects.filter(\n book=book, status=True).count()\n context['book'] = book\n template_name = 'store/book_detail.html'\n\n return render(request, template_name, context=context)\n\n\n@csrf_exempt\n@login_required\ndef book_rating(request, bid):\n book = get_object_or_404(Book, pk=bid)\n\n user = request.user\n try:\n rating = request.POST['rating']\n except MultiValueDictKeyError:\n return HttpResponseBadRequest(content=\"Invalid Data format\")\n\n if int(rating) > 10 or int(rating) < 0:\n return HttpResponseBadRequest(content=\"Don't mess with frontend validation\")\n\n change_rating, create = BookRating.objects.get_or_create(\n book=book, username=user)\n change_rating.rating = rating\n change_rating.save()\n\n book.rating = BookRating.objects.filter(\n book=book).aggregate(rating=Avg('rating'))['rating']\n book.save()\n\n return redirect(\"book-detail\", bid=bid)\n\n\n@csrf_exempt\ndef bookListView(request):\n template_name = 'store/book_list.html'\n context = {\n 'books': None,\n }\n get_data = request.GET\n\n if get_data:\n context['books'] = Book.objects.filter(\n title__icontains=get_data['title'], author__icontains=get_data['author'], genre__icontains=get_data['genre']\n )\n\n else:\n context['books'] = Book.objects.all()\n\n for i in context['books']:\n i.rating = BookRating.objects.filter(\n book=i).aggregate(rating=Avg('rating'))['rating']\n\n return render(request, template_name, context=context)\n\n\n@login_required\ndef viewLoanedBooks(request):\n template_name = 'store/loaned_books.html'\n context = {\n 'books': None,\n }\n user = request.user\n books = BookCopy.objects.filter(borrower=user)\n context['books'] = books\n return render(request, template_name, context=context)\n\n\n@csrf_exempt\n@login_required\ndef loanBookView(request):\n response_data = {\n 'message': None,\n }\n try:\n bid = request.POST['bid']\n except MultiValueDictKeyError:\n return HttpResponseBadRequest(content=\"Invalid Data format\")\n\n book = BookCopy.objects.filter(book_id=bid, status=True)[0]\n\n if book:\n book.borrower = request.user\n book.borrow_date = timezone.datetime.today().date()\n book.status = False\n book.save()\n response_data['message'] = 'success'\n else:\n response_data['message'] = 'failure'\n return JsonResponse(response_data)\n\n\n@csrf_exempt\n@login_required\ndef returnBookView(request):\n response_data = {\n 'message': None,\n }\n try:\n bid = request.POST['bid']\n except MultiValueDictKeyError:\n return HttpResponseBadRequest(content=\"Invalid Data format\")\n\n book = get_object_or_404(BookCopy, pk=bid)\n\n if book and book.borrower == request.user:\n book.borrower = None\n book.borrow_date = None\n book.status = True\n book.save()\n response_data['message'] = 'success'\n else:\n response_data['message'] = 'failure'\n return JsonResponse(response_data)\n","sub_path":"store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"490014454","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport json\nimport requests\n\nfrom bs4 import BeautifulSoup\nfrom builtins import input\nfrom datetime import datetime\nfrom future.moves.itertools import zip_longest\nfrom getpass import getpass\nfrom itertools import chain\nfrom textwrap import TextWrapper, wrap\n\nfrom toot import api, config, DEFAULT_INSTANCE, User, App, ConsoleError\nfrom toot.output import green, yellow, print_error\nfrom toot.app import TimelineApp\n\n\ndef register_app(instance):\n print(\"Registering application with %s\" % green(instance))\n\n try:\n response = api.create_app(instance)\n except:\n raise ConsoleError(\"Registration failed. Did you enter a valid instance?\")\n\n base_url = 'https://' + instance\n\n app = App(instance, base_url, response['client_id'], response['client_secret'])\n path = config.save_app(app)\n print(\"Application tokens saved to: {}\\n\".format(green(path)))\n\n return app\n\n\ndef create_app_interactive():\n instance = input(\"Choose an instance [%s]: \" % green(DEFAULT_INSTANCE))\n if not instance:\n instance = DEFAULT_INSTANCE\n\n return config.load_app(instance) or register_app(instance)\n\n\ndef login_interactive(app):\n print(\"\\nLog in to \" + green(app.instance))\n email = input('Email: ')\n password = getpass('Password: ')\n\n if not email or not password:\n raise ConsoleError(\"Email and password cannot be empty.\")\n\n try:\n print(\"Authenticating...\")\n response = api.login(app, email, password)\n except api.ApiError:\n raise ConsoleError(\"Login failed\")\n\n user = User(app.instance, email, response['access_token'])\n path = config.save_user(user)\n print(\"Access token saved to: \" + green(path))\n\n return user\n\n\ndef two_factor_login_interactive(app):\n \"\"\"Hacky implementation of two factor authentication\"\"\"\n\n print(\"Log in to \" + green(app.instance))\n email = input('Email: ')\n password = getpass('Password: ')\n\n sign_in_url = app.base_url + '/auth/sign_in'\n\n session = requests.Session()\n\n # Fetch sign in form\n response = session.get(sign_in_url)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.content, \"html.parser\")\n form = soup.find('form')\n inputs = form.find_all('input')\n\n data = {i.attrs.get('name'): i.attrs.get('value') for i in inputs}\n data['user[email]'] = email\n data['user[password]'] = password\n\n # Submit form, get 2FA entry form\n response = session.post(sign_in_url, data)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.content, \"html.parser\")\n form = soup.find('form')\n inputs = form.find_all('input')\n\n data = {i.attrs.get('name'): i.attrs.get('value') for i in inputs}\n data['user[otp_attempt]'] = input(\"2FA Token: \")\n\n # Submit token\n response = session.post(sign_in_url, data)\n response.raise_for_status()\n\n # Extract access token from response\n soup = BeautifulSoup(response.content, \"html.parser\")\n initial_state = soup.find('script', id='initial-state')\n\n if not initial_state:\n raise ConsoleError(\"Login failed: Invalid 2FA token?\")\n\n data = json.loads(initial_state.get_text())\n access_token = data['meta']['access_token']\n\n user = User(app.instance, email, access_token)\n path = config.save_user(user)\n print(\"Access token saved to: \" + green(path))\n\n\ndef _print_timeline(item):\n def wrap_text(text, width):\n wrapper = TextWrapper(width=width, break_long_words=False, break_on_hyphens=False)\n return chain(*[wrapper.wrap(l) for l in text.split(\"\\n\")])\n\n def timeline_rows(item):\n name = item['name']\n time = item['time'].strftime('%Y-%m-%d %H:%M%Z')\n\n left_column = [name, time]\n if 'reblogged' in item:\n left_column.append(item['reblogged'])\n\n text = item['text']\n\n right_column = wrap_text(text, 80)\n\n return zip_longest(left_column, right_column, fillvalue=\"\")\n\n for left, right in timeline_rows(item):\n print(\"{:30} │ {}\".format(left, right))\n\n\ndef _parse_timeline(item):\n content = item['reblog']['content'] if item['reblog'] else item['content']\n reblogged = item['reblog']['account']['username'] if item['reblog'] else \"\"\n\n name = item['account']['display_name'] + \" @\" + item['account']['username']\n soup = BeautifulSoup(content, \"html.parser\")\n text = soup.get_text().replace(''', \"'\")\n time = datetime.strptime(item['created_at'], \"%Y-%m-%dT%H:%M:%S.%fZ\")\n\n return {\n \"name\": name,\n \"text\": text,\n \"time\": time,\n \"reblogged\": reblogged,\n }\n\n\ndef timeline(app, user, args):\n items = api.timeline_home(app, user)\n parsed_items = [_parse_timeline(t) for t in items]\n\n print(\"─\" * 31 + \"┬\" + \"─\" * 88)\n for item in parsed_items:\n _print_timeline(item)\n print(\"─\" * 31 + \"┼\" + \"─\" * 88)\n\n\ndef curses(app, user, args):\n generator = api.timeline_generator(app, user)\n TimelineApp(generator).run()\n\n\ndef post(app, user, args):\n if args.media:\n media = _do_upload(app, user, args.media)\n media_ids = [media['id']]\n else:\n media_ids = None\n\n response = api.post_status(app, user, args.text, media_ids=media_ids, visibility=args.visibility)\n\n print(\"Toot posted: \" + green(response.get('url')))\n\n\ndef auth(app, user, args):\n if app and user:\n print(\"You are logged in to {} as {}\\n\".format(\n yellow(app.instance),\n yellow(user.username)\n ))\n print(\"User data: \" + green(config.get_user_config_path()))\n print(\"App data: \" + green(config.get_instance_config_path(app.instance)))\n else:\n print(\"You are not logged in\")\n\n\ndef login(app, user, args):\n app = create_app_interactive()\n login_interactive(app)\n\n print()\n print(green(\"✓ Successfully logged in.\"))\n\n\ndef login_2fa(app, user, args):\n print()\n print(yellow(\"Two factor authentication is experimental.\"))\n print(yellow(\"If you have problems logging in, please open an issue:\"))\n print(yellow(\"https://github.com/ihabunek/toot/issues\"))\n print()\n\n app = create_app_interactive()\n two_factor_login_interactive(app)\n\n print()\n print(green(\"✓ Successfully logged in.\"))\n\n\ndef logout(app, user, args):\n config.delete_user()\n\n print(green(\"✓ You are now logged out\"))\n\n\ndef upload(app, user, args):\n response = _do_upload(app, user, args.file)\n\n print(\"\\nSuccessfully uploaded media ID {}, type '{}'\".format(\n yellow(response['id']), yellow(response['type'])))\n print(\"Original URL: \" + green(response['url']))\n print(\"Preview URL: \" + green(response['preview_url']))\n print(\"Text URL: \" + green(response['text_url']))\n\n\ndef _print_accounts(accounts):\n if not accounts:\n return\n\n print(\"\\nAccounts:\")\n for account in accounts:\n acct = green(\"@{}\".format(account['acct']))\n display_name = account['display_name']\n print(\"* {} {}\".format(acct, display_name))\n\n\ndef _print_hashtags(hashtags):\n if not hashtags:\n return\n\n print(\"\\nHashtags:\")\n print(\", \".join([green(\"#\" + t) for t in hashtags]))\n\n\ndef search(app, user, args):\n response = api.search(app, user, args.query, args.resolve)\n\n _print_accounts(response['accounts'])\n _print_hashtags(response['hashtags'])\n\n\ndef _do_upload(app, user, file):\n print(\"Uploading media: {}\".format(green(file.name)))\n return api.upload_media(app, user, file)\n\n\ndef _find_account(app, user, account_name):\n \"\"\"For a given account name, returns the Account object or raises an exception if not found.\"\"\"\n response = api.search(app, user, account_name, False)\n\n for account in response['accounts']:\n if account['acct'] == account_name or \"@\" + account['acct'] == account_name:\n return account\n\n raise ConsoleError(\"Account not found\")\n\n\ndef _print_account(account):\n print(\"{} {}\".format(green(\"@\" + account['acct']), account['display_name']))\n\n if account['note']:\n print(\"\")\n note = BeautifulSoup(account['note'], \"html.parser\")\n print(\"\\n\".join(wrap(note.get_text())))\n\n print(\"\")\n print(\"ID: \" + green(account['id']))\n print(\"Since: \" + green(account['created_at'][:19].replace('T', ' @ ')))\n print(\"\")\n print(\"Followers: \" + yellow(account['followers_count']))\n print(\"Following: \" + yellow(account['following_count']))\n print(\"Statuses: \" + yellow(account['statuses_count']))\n print(\"\")\n print(account['url'])\n\n\ndef follow(app, user, args):\n account = _find_account(app, user, args.account)\n\n if not account:\n print_error(\"Account not found\")\n return\n\n api.follow(app, user, account['id'])\n\n print(green(\"✓ You are now following %s\" % args.account))\n\n\ndef unfollow(app, user, args):\n account = _find_account(app, user, args.account)\n\n if not account:\n print_error(\"Account not found\")\n return\n\n api.unfollow(app, user, account['id'])\n\n print(green(\"✓ You are no longer following %s\" % args.account))\n\n\ndef whoami(app, user, args):\n account = api.verify_credentials(app, user)\n _print_account(account)\n\n\ndef whois(app, user, args):\n account = _find_account(app, user, args.account)\n _print_account(account)\n","sub_path":"toot/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":9347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"4873889","text":"# -*- coding: utf8 -*-\n\nimport matplotlib.pyplot as plt;\nimport matplotlib as mpl;\nimport numpy as np;\nfrom scipy.integrate import simps;\n\nimport sys;\nimport AuxOperators as aux;\n\n# ----------------------------------------------------------------------------\n# Configure Plot parameters\n\nimport matplotlib as mpl;\n\n# Set up fonts\nmpl.rcParams['text.usetex'] = True;\nmpl.rcParams['font.size'] = 11;\nmpl.rcParams['font.family'] = 'serif'\nmpl.rcParams['font.serif'] = 'Times New Roman'\n\n# Set up ticks\nmpl.rcParams['xtick.major.size'] = 6\n#mpl.rcParams['xtick.major.width'] = 0.8\n#mpl.rcParams['xtick.direction'] = 'inout'\nmpl.rcParams['ytick.major.size'] = 6\n#mpl.rcParams['ytick.major.width'] = 0.8\n#mpl.rcParams['ytick.direction'] = 'inout'\n\n# minor ticks\nmpl.rcParams['xtick.minor.size'] = 3\nmpl.rcParams['xtick.minor.width'] = 0.6\nmpl.rcParams['ytick.minor.size'] = 3\nmpl.rcParams['ytick.minor.width'] = 0.6\n\n# Set shadow around the legend box\nmpl.rcParams['legend.shadow'] = True\n# Set up grid\nmpl.rcParams['grid.color'] = 'gray'\nmpl.rcParams['grid.alpha'] = 0.6\nmpl.rcParams['grid.linestyle'] = '--'\n\n# Subplots spacing\nmpl.rcParams['figure.subplot.wspace'] = 0.0\nmpl.rcParams['figure.subplot.hspace'] = 0.15\n\n# delta = sys.argv[1];\n\nf, ax = plt.subplots(figsize=(8, 4));\nColorStyle = ['r-', 'b-'];\n\nl = 0;\nfor Omega in ['2.0', '8.0']:\n DataD = np.load('Results/PhaseDiagramLineDOWN(2.0)('+ Omega +').npy');\n DataUP = np.load('Results/PhaseDiagramLineUP(2.0)('+ Omega +').npy');\n\n delta = np.arange(-2.0, 2.0005, 0.001);\n kl = 2.0;\n Omega = float(Omega);\n N = delta.size;\n M = DataD[0,:].size;\n dx = 20.0 / (M - 1);\n Norm = 2.0;\n x = np.linspace(-10, 10, M);\n\n E = np.empty(N);\n V = np.zeros(M);\n \n for i in range(N):\n eqPar = (kl, delta[i], -1.0, -1.0, -1.0, Omega);\n E[i] = aux.Epart(dx, M, V, DataUP[i,:], DataD[i,:], *eqPar);\n \n ax.plot(delta, E, ColorStyle[l], label='$\\Omega$ = %.1f' % Omega);\n\nax.set_ylabel('$E_o(\\\\delta)$', rotation=0, ha='right', fontsize=14);\nax.set_xlabel('$\\\\delta$', fontsize=14);\nax.set_xlim(-2, 2);\n# ax.set_ylim(-85, -25);\nAxLeg = ax.legend(loc='lower left', fontsize=14, handletextpad=0.5);\n\nax.xaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(4));\nax.yaxis.set_minor_locator(mpl.ticker.AutoMinorLocator(4));\n\n# plt.savefig('Results/GroundEnergy.pdf', dpi=128, bbox_inches='tight');\nplt.show();\n","sub_path":"GroundEnergyDelta.py","file_name":"GroundEnergyDelta.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"560933429","text":"import unittest\n\nimport bleu\nfrom bleu.tests.data import REF_FILES, TRANS_FILES\nfrom bleu.utils import load_reference_corpus, load_translation_corpus\n\n\nclass TestMetrics(unittest.TestCase):\n reference_corpus = load_reference_corpus(REF_FILES)\n\n def test_corpus_level(self):\n scores = [\n bleu.bleu_corpus_level(\n translation_corpus=load_translation_corpus(file),\n reference_corpus=self.reference_corpus,\n ).bleu\n for file in TRANS_FILES\n ]\n\n self.assertGreater(scores[1], scores[0], msg='score2 should be better than score1')\n\n def test_sentence_level(self):\n trans = TRANS_FILES[0]\n trans_corpus = load_translation_corpus(trans)\n\n sentence_score = bleu.bleu_sentence_level(\n translation_sentence=trans_corpus[0],\n reference_corpus=self.reference_corpus[0],\n )\n corpus_score = bleu.bleu_corpus_level(\n translation_corpus=trans_corpus,\n reference_corpus=self.reference_corpus,\n )\n\n self.assertAlmostEqual(\n sentence_score,\n corpus_score,\n msg=\"\"\"\n sentence_score: %r\n corpus_score: %r\n \"\"\" % (sentence_score, corpus_score)\n )\n\n def test_smooth(self):\n translation_corpus = ['this sentence only has unigram matches'.split()]\n reference_corpus = [[\n 'matches unigram has only sentence this'.split()\n ]]\n\n score = bleu.bleu_corpus_level(translation_corpus, reference_corpus)\n self.assertAlmostEqual(score.bleu, 0.0, msg='get 0 without smoothing')\n\n score = bleu.bleu_corpus_level(translation_corpus, reference_corpus, smooth=True)\n self.assertGreater(score.bleu, 0.0, msg='get non-zero after smoothing')\n","sub_path":"bleu/tests/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"231574723","text":"\"\"\"\r\npython --version : Python 3.5.3\r\n\r\n5177. [파이썬 S/W 문제해결 기본] 8일차 - 이진 힙\r\n\r\n\r\n\"\"\"\r\nimport sys\r\nsys.stdin = open(\"input.txt\",\"r\")\r\n\r\nclass Node:\r\n def __init__(self, num):\r\n self.num = num\r\n self.parent = None\r\n self.left = None\r\n self.right = None\r\n\r\nclass CompleteBinaryTree:\r\n def __init__(self):\r\n self.root = None\r\n self.queue = []\r\n self.last_leaf = None\r\n\r\n def insert_tree(self, num):\r\n self.queue = [self.root]\r\n while self.queue:\r\n node = self.queue.pop(0)\r\n if self.root is None:\r\n self.last_leaf = self.root = Node(num)\r\n break\r\n elif node is not None:\r\n if node.left is None:\r\n self.last_leaf = node.left = Node(num)\r\n node.left.parent = node\r\n self.check_tree(node, node.left)\r\n break\r\n elif node.right is None:\r\n self.last_leaf = node.right = Node(num)\r\n node.right.parent = node\r\n self.check_tree(node, node.right)\r\n break\r\n else:\r\n self.queue.extend([node.left, node.right])\r\n self.queue.clear\r\n\r\n def check_tree(self,p_node,c_node):\r\n # 부모 노드가 더 크면 자리 바꿈 시작\r\n if p_node.num > c_node.num:\r\n p_node.num, c_node.num = c_node.num, p_node.num\r\n temp = p_node\r\n while temp != self.root:\r\n if temp.parent.num > temp.num:\r\n temp.num, temp.parent.num = temp.parent.num, temp.num\r\n temp = temp.parent\r\n \r\n \r\nT = int(input())\r\n\r\nfor t in range(1, T+1):\r\n N = int(input())\r\n data = list(map(int,input().split()))\r\n mytree = CompleteBinaryTree()\r\n for d in data:\r\n mytree.insert_tree(d)\r\n res = 0\r\n temp = mytree.last_leaf\r\n while temp != mytree.root:\r\n temp = temp.parent\r\n res += temp.num\r\n\r\n print(\"#{} {}\".format(t, res))","sub_path":"OnlineJudge/SWExpertAcademy/InterMediate/08/im1903055177.py","file_name":"im1903055177.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"67122414","text":"print(\"Welcome to SpongeMock.py,\")\nprint(\"the script that makes your text...\")\nprint(\"sPoNgEmOcKeD\")\nprint()\nprint(\"What text do you want to sPoNgEmOcK?\")\nrawText = input()\nprint()\noutchars = []\nuCase = True\nfor char in rawText:\n if uCase == True:\n outchars.append(char.upper())\n uCase = False\n elif uCase == False:\n outchars.append(char.lower())\n uCase = True\n else:\n chars.append(char)\n \nprint(\"\".join(outchars))\n","sub_path":"SpongeMock.py","file_name":"SpongeMock.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"74992253","text":"'''\n Schema to use graphene framework to requirement on db\n'''\n\nimport graphene\nfrom graphene_django.types import DjangoObjectType\nfrom configuration.models import Config\n\n# pylint: disable = too-few-public-methods\n\n\nclass ConfigType(DjangoObjectType):\n '''\n Defining the CyclesConfig Type\n '''\n class Meta:\n '''\n Defining the CyclesConfig Type\n '''\n model = Config\n\n\nclass CreateConfig(graphene.Mutation):\n # pylint: disable = unused-argument, no-self-use, too-many-arguments\n '''\n Class to create a new Config object on db\n '''\n config = graphene.Field(ConfigType)\n\n class Arguments:\n '''\n Arguments required to create a new config\n '''\n number = graphene.Int()\n time_between_cycles = graphene.Int()\n upper_limit = graphene.Int()\n inferior_limit = graphene.Int()\n upper_time = graphene.Int()\n inferior_time = graphene.Int()\n disable_shutdown = graphene.Boolean()\n enable_output = graphene.Boolean()\n temperature = graphene.Float()\n time = graphene.Float()\n\n def mutate(self, info, number, time_between_cycles, upper_limit,\n inferior_limit, upper_time, inferior_time, disable_shutdown,\n enable_output, temperature, time):\n '''\n Create the user with the given parameters end add to db\n '''\n config = Config(\n number=number,\n time_between_cycles=time_between_cycles,\n upper_limit=upper_limit,\n inferior_limit=inferior_limit,\n upper_time=upper_time,\n inferior_time=inferior_time,\n disable_shutdown=disable_shutdown,\n enable_output=enable_output,\n temperature=temperature,\n time=time,\n )\n config.save()\n\n return CreateConfig(config=config)\n\n\nclass Mutation(graphene.ObjectType):\n '''\n GraphQL class to declare all the mutations\n '''\n create_config = CreateConfig.Field()\n\n\nclass Query:\n # pylint: disable = unused-argument, no-self-use\n '''\n The Query list all the types created above\n '''\n config = graphene.Field(\n ConfigType,\n id=graphene.Int(),\n number=graphene.Int(),\n time_between_cycles=graphene.Int(),\n upper_limit=graphene.Int(),\n inferior_limit=graphene.Int(),\n upper_time=graphene.Int(),\n inferior_time=graphene.Int(),\n disable_shutdown=graphene.Boolean(),\n enable_output=graphene.Boolean(),\n temperature=graphene.Float(),\n Time=graphene.Float())\n\n all_config = graphene.List(ConfigType)\n\n def resolve_all_config(self, info, **kwargs):\n '''\n Returning all CyclesConfig on db\n '''\n return Config.objects.all()\n\n def resolve_config(self, info, **kwargs):\n '''\n Returning only one CyclesConfig by id\n '''\n pk = kwargs.get('id')\n\n if pk is not None:\n return Config.objects.get(pk=pk)\n return None\n","sub_path":"unbrake-api/configuration/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"204006786","text":"\"\"\"Django urlpatterns declaration for nautobot_chatops plugin.\"\"\"\n\nimport logging\nfrom django.urls import path\n\nfrom django.conf import settings\nfrom nautobot.core.api import OrderedDefaultRouter\nfrom nautobot_chatops.api.views.lookup import AccessLookupView\nfrom nautobot_chatops.api.views.generic import AccessGrantViewSet, CommandTokenViewSet, NautobotChatopsRootView\n\n\nlogger = logging.getLogger(__name__)\nurlpatterns = [path(\"lookup/\", AccessLookupView.as_view(), name=\"access_lookup\")]\n\nif settings.PLUGINS_CONFIG[\"nautobot_chatops\"].get(\"enable_slack\"):\n from nautobot_chatops.api.views.slack import SlackSlashCommandView, SlackInteractionView\n\n urlpatterns += [\n path(\"slack/slash_command/\", SlackSlashCommandView.as_view(), name=\"slack_slash_command\"),\n path(\"slack/interaction/\", SlackInteractionView.as_view(), name=\"slack_interaction\"),\n ]\n\nif settings.PLUGINS_CONFIG[\"nautobot_chatops\"].get(\"enable_ms_teams\"):\n from nautobot_chatops.api.views.ms_teams import MSTeamsMessagesView\n\n urlpatterns += [\n path(\"ms_teams/messages/\", MSTeamsMessagesView.as_view(), name=\"ms_teams_messages\"),\n ]\n\n# v1.4.0 - Preserve backwards compatibility with variable name until 2.0.0\nif settings.PLUGINS_CONFIG[\"nautobot_chatops\"].get(\"enable_webex\") or settings.PLUGINS_CONFIG[\"nautobot_chatops\"].get(\n \"enable_webex_teams\"\n):\n if settings.PLUGINS_CONFIG[\"nautobot_chatops\"].get(\"webex_teams_token\") and not settings.PLUGINS_CONFIG[\n \"nautobot_chatops\"\n ].get(\"webex_token\"):\n # v1.4.0 Deprecation warning\n logger.warning(\"The 'enable_webex_teams' setting is deprecated. Please use 'enable_webex' instead.\")\n from nautobot_chatops.api.views.webex import WebExView\n\n urlpatterns += [\n path(\"webex/\", WebExView.as_view(), name=\"webex\"),\n path(\"webex_teams/\", WebExView.as_view(), name=\"webex_teams\"), # Deprecated v1.4.0\n ]\n\nif settings.PLUGINS_CONFIG[\"nautobot_chatops\"].get(\"enable_mattermost\"):\n from nautobot_chatops.api.views.mattermost import MattermostSlashCommandView, MattermostInteractionView\n\n urlpatterns += [\n path(\"mattermost/slash_command/\", MattermostSlashCommandView.as_view(), name=\"mattermost_slash_command\"),\n path(\"mattermost/interaction/\", MattermostInteractionView.as_view(), name=\"mattermost_interaction\"),\n ]\n\nrouter = OrderedDefaultRouter()\nrouter.APIRootView = NautobotChatopsRootView\nrouter.register(\"commandtoken\", CommandTokenViewSet)\nrouter.register(\"accessgrant\", AccessGrantViewSet)\n\napp_name = \"nautobot_chatops-api\"\n\nurlpatterns += router.urls\n","sub_path":"nautobot_chatops/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"8988544","text":"import numpy as np\nimport pandas as pd\nimport csv\nfrom itertools import combinations\nfrom itertools import chain\n\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nimport seaborn as sns\n\ncolormap = cm.viridis_r\n\nnp.random.seed(100)\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='User input parameters')\n\nparser.add_argument('-glove_path',\n default='',\n help='path where the 4 GLoVE files are stored')\n\n\nimport nltk\nfrom nltk.corpus import wordnet, brown\n\nnltk.download('averaged_perceptron_tagger')\nnltk.download('wordnet')\n\nargs = parser.parse_args()\nGLOVE_PATH = args.glove_path\n\nGLOVE_50D_PATH = GLOVE_PATH + 'glove.6B/glove.6B.50d.txt'\nGLOVE_100D_PATH = GLOVE_PATH + 'glove.6B/glove.6B.100d.txt'\nGLOVE_200D_PATH = GLOVE_PATH + 'glove.6B/glove.6B.200d.txt'\nGLOVE_300D_PATH = GLOVE_PATH + 'glove.6B/glove.6B.300d.txt'\n\nNOUN_FILENAME = 'nouns.txt'\nVERB_FILENAME = 'verbs.txt'\n\nglove_50d = pd.read_table(GLOVE_50D_PATH, sep=\" \", index_col=0, header=None, quoting=csv.QUOTE_NONE)\nglove_100d = pd.read_table(GLOVE_100D_PATH, sep=\" \", index_col=0, header=None, quoting=csv.QUOTE_NONE)\nglove_200d = pd.read_table(GLOVE_200D_PATH, sep=\" \", index_col=0, header=None, quoting=csv.QUOTE_NONE)\nglove_300d = pd.read_table(GLOVE_300D_PATH, sep=\" \", index_col=0, header=None, quoting=csv.QUOTE_NONE)\n\n'''\n# Q1:\n\n## sub 1:\n# Randomly select 10 nouns and 10 verbs from a vocabulary resource\n\n## sub 2:\n# For each word wi, identify four synonyms, e.g., from synsets in WordNet, to generate a synonym list of length 5\n# Repeat 5 times until you have 5 synonym lists of length 5 for nouns, and 5 synonym lists of length 5 for verbs.\n\n'''\n\n\ndef create_word_list(testmode=False):\n \"\"\"Randomly select nouns and verbs from a vocabulary resource\"\"\"\n token_list = glove_50d.index.tolist()\n word_list = [token for token in token_list if str(token).isalpha()]\n\n # test with words directly extracted from GLoVE to figure out why that is not preferred\n if testmode:\n\n np.random.shuffle(word_list)\n nouns_list = []\n verbs_list = []\n\n for w in word_list:\n if not isinstance(w, float):\n if nltk.pos_tag([w])[0][1] == 'NN':\n nouns_list.append(w)\n elif nltk.pos_tag([w])[0][1] == 'VB':\n verbs_list.append(w)\n else:\n continue\n else:\n break\n\n else:\n nouns_list = [word for word, pos in brown.tagged_words() if pos == 'NN']\n verbs_list = [word for word, pos in brown.tagged_words() if pos == 'VB']\n\n np.random.shuffle(nouns_list)\n np.random.shuffle(verbs_list)\n\n return word_list, nouns_list, verbs_list\n\n\ndef create_syn_list(words, word_list, filename):\n \"\"\"5 synonym lists of length 5 for nouns, and 5 synonym lists of length 5 for verbs\"\"\"\n count = 0\n with open(filename, 'w') as f_in:\n for w in words:\n if count < 5:\n try:\n if filename.startswith('n'):\n synonyms = wordnet.synsets(w, pos='n')\n elif filename.startswith('v'):\n synonyms = wordnet.synsets(w, pos='v')\n else:\n print('please double check your input filename.')\n\n syn_list = list(set(chain.from_iterable([word.lemma_names() for word in synonyms])))\n syn_list = [syn for syn in syn_list if syn != w][:4]\n # the first one is the seed word\n syn_list = [w] + syn_list\n if len(syn_list) > 4 and all(elem in word_list for elem in syn_list):\n # print(syn_list)\n count += 1\n f_in.write(\",\".join(syn_list))\n f_in.write('\\n')\n except Exception as e:\n print(e)\n else:\n break\n\n\n'''\n## sub 3:\n# Extract the 4 GLoVE vectors for each of the 50 words (d \\in [50,100,200,300])\n'''\n\n\ndef creat_glove_dict(filename):\n \"\"\"Store the 4 GLoVE vectors for nouns and verbs into dictionary\"\"\"\n glove_dict = {}\n for word_list in open(filename, 'r'):\n words = word_list.split(',')\n for w in words:\n w = w.strip()\n glove_50d_vec = glove_50d.loc[w, :]\n glove_100d_vec = glove_100d.loc[w, :]\n glove_200d_vec = glove_200d.loc[w, :]\n glove_300d_vec = glove_300d.loc[w, :]\n glove_dict[w] = [list(glove_50d_vec),\n list(glove_100d_vec),\n list(glove_200d_vec),\n list(glove_300d_vec)]\n return glove_dict\n\n\n'''\n# Q2:\n\n## sub 1:\n# read in a synonym list (5 words) and their GLoVE vectors for a given dimensionality d, compute the cosine similarities\n# for every pair of distinct words (N=choose(5,2)), and save the results in a dictionary\n# eg: {(word1, word2): cos_similarity}\n\n## sub 2:\n# Compute the mean and standard deviation of the 10 values of cosine similarity for each set of dimension d vectors for synonym list.\n# Save code in a single python file named assignment1_.py\n'''\n\n\ndef create_word_cos_dict(filename, glove_dict, dim):\n \"\"\"compute the cosine similarities for each word pair and save the results in a dictionary\"\"\"\n word_cos_dict_lst = []\n\n for word_list in open(filename, 'r'):\n words = list(map(lambda x: x.strip(), word_list.split(',')))\n word_pairs = combinations(words, 2)\n word_cos_dict = {}\n for word_pair in word_pairs:\n w1, w2 = word_pair\n cos_dim = cosine_similarity([glove_dict[w1][dim]],\n [glove_dict[w2][dim]])\n word_cos_dict[(w1, w2)] = cos_dim[0]\n\n word_cos_dict_lst.append(word_cos_dict)\n return word_cos_dict_lst\n\n\n'''\n# Q3:\n\n## For each synonym list, (N=10) create a csv file with a header row, then one additional row for each pair of distinct words\n## One column for each dimensionality d \\in [50,100,200,300] in ascending order, with cell values equal to the cosine similarity of the d-dimension vectors for word pair (wi,wj)\n## Save each csv file as synonym-list--.csv with category C instantiated as 'N' or 'V' (noun or verb), and N instantiated as an index from 1 to 5.\n'''\n\n\ndef create_csv():\n \"\"\"create 10 csv files to store cosine similarity for synonym lists of nouns and verbs\"\"\"\n glove_nouns_dict, glove_verbs_dict = creat_glove_dict('nouns.txt'), creat_glove_dict('verbs.txt')\n\n noun_50d_cos_dict_lst = create_word_cos_dict(NOUN_FILENAME, glove_nouns_dict, dim=0)\n noun_100d_cos_dict_lst = create_word_cos_dict(NOUN_FILENAME, glove_nouns_dict, dim=1)\n noun_200d_cos_dict_lst = create_word_cos_dict(NOUN_FILENAME, glove_nouns_dict, dim=2)\n noun_300d_cos_dict_lst = create_word_cos_dict(NOUN_FILENAME, glove_nouns_dict, dim=3)\n\n noun_cos_dict_lst = [noun_50d_cos_dict_lst,\n noun_100d_cos_dict_lst,\n noun_200d_cos_dict_lst,\n noun_300d_cos_dict_lst]\n\n # cos similarity of verbs 50d, 100d, 200d, 300d\n\n verb_50d_cos_dict_lst = create_word_cos_dict(VERB_FILENAME, glove_verbs_dict, dim=0)\n verb_100d_cos_dict_lst = create_word_cos_dict(VERB_FILENAME, glove_verbs_dict, dim=1)\n verb_200d_cos_dict_lst = create_word_cos_dict(VERB_FILENAME, glove_verbs_dict, dim=2)\n verb_300d_cos_dict_lst = create_word_cos_dict(VERB_FILENAME, glove_verbs_dict, dim=3)\n\n verb_cos_dict_lst = [verb_50d_cos_dict_lst,\n verb_100d_cos_dict_lst,\n verb_200d_cos_dict_lst,\n verb_300d_cos_dict_lst]\n noun_cos_mean = []\n noun_cos_sd = []\n verb_cos_mean = []\n verb_cos_sd = []\n\n for l in range(5):\n noun_cos_df = pd.concat([pd.DataFrame(noun_cos_dict_lst[i][l], index=[0]).transpose()\n for i in range(4)],\n axis=1)\n noun_cos_df.columns = ['d=50', 'd=100', 'd=200', 'd=300']\n\n noun_cos_mean.append(noun_cos_df.apply(np.mean))\n noun_cos_sd.append(noun_cos_df.apply(np.std))\n print(noun_cos_df)\n noun_cos_df.to_csv('synonym-list-N-{}.csv'.format(l + 1))\n print('synonym-list-N-{}.csv saved!'.format(l + 1))\n\n for l in range(5):\n verb_cos_df = pd.concat([pd.DataFrame(verb_cos_dict_lst[i][l], index=[0]).transpose()\n for i in range(4)],\n axis=1)\n verb_cos_df.columns = ['d=50', 'd=100', 'd=200', 'd=300']\n\n verb_cos_mean.append(verb_cos_df.apply(np.mean))\n verb_cos_sd.append(verb_cos_df.apply(np.std))\n print(verb_cos_df)\n verb_cos_df.to_csv('synonym-list-V-{}.csv'.format(l + 1))\n print('synonym-list-V-{}.csv saved!'.format(l + 1))\n return noun_cos_mean, noun_cos_sd, verb_cos_mean, verb_cos_sd\n\n\n'''\n# Q4:\n\n## Create a csv file summarizing the results for nouns with a header row, and a row for each synonym list. Do the same for the results for verbs.\n## column 1: file name stem (remove 'csv' extension),\n## column 2: mean of cosine similarity of the vectors in that list,\n## column 3: standard deviation.of cos sim\n## Name the csv files as performance-five-noun-lists.csv, performance-five-verb-lists.csv\n'''\n\n\ndef create_summary(noun_cos_mean, noun_cos_sd, verb_cos_mean, verb_cos_sd):\n \"\"\"performance summary to store filename, mean, sd of cosine similarity and dimension\"\"\"\n noun_cos_summary = pd.concat(\n [pd.Series([y for x in [['synonym-list-N-{}'.format(l + 1)] * 4 for l in range(5)] for y in x]),\n pd.DataFrame(np.resize(pd.DataFrame(noun_cos_mean).values, (20, 1))),\n pd.DataFrame(np.resize(pd.DataFrame(noun_cos_sd).values, (20, 1))),\n pd.Series([y for x in [[50, 100, 200, 300] * 5] for y in x])], axis=1)\n\n noun_cos_summary.columns = ['filename', 'mean', 'sd', 'dim']\n\n print('sensitivity plot for nouns created!')\n noun_cos_summary.to_csv('performance-five-noun-lists.csv')\n print('performance-five-noun-lists.csv saved!')\n\n verb_cos_summary = pd.concat(\n [pd.Series([y for x in [['synonym-list-V-{}'.format(l + 1)] * 4 for l in range(5)] for y in x]),\n pd.DataFrame(np.resize(pd.DataFrame(verb_cos_mean).values, (20, 1))),\n pd.DataFrame(np.resize(pd.DataFrame(verb_cos_sd).values, (20, 1))),\n pd.Series([y for x in [[50, 100, 200, 300] * 5] for y in x])], axis=1)\n\n verb_cos_summary.columns = ['filename', 'mean', 'sd', 'dim']\n\n print('sensitivity plot for verbs created!')\n\n verb_cos_summary.to_csv('performance-five-verb-lists.csv')\n print('performance-five-verb-lists.csv saved!')\n\n\n'''\n\n# Q5:\n\n## Create two plots, one for nouns and one for verbs\n## 5 sets of four (x,y), each set has x = d, y = mean cosine similarity (use a whisker plot to show the range, mean, and sd.)\n'''\n\n\ndef create_sensitivity_plot(mode='both'):\n \"\"\"sensitivity plot\"\"\"\n if mode == 'both':\n fig = plt.figure(figsize=(15, 8))\n u = ['N', 'V']\n for i in range(2):\n for j in range(1, 6):\n filename = 'synonym-list-{}-{}.csv'.format(u[i], j)\n df = pd.read_csv(filename, sep=',')\n plt.subplot(2, 5, j + 5 * i)\n sns.boxplot(data=df)\n plt.title(filename.split('.')[0])\n plt.show()\n fig.savefig('whiskerplot.png')\n elif mode == 'noun':\n fig = plt.figure(figsize=(20, 5))\n for j in range(1, 6):\n filename = 'synonym-list-N-{}.csv'.format(j)\n df = pd.read_csv(filename, sep=',')\n plt.subplot(1, 5, j)\n sns.boxplot(data=df)\n plt.title(filename.split('.')[0])\n plt.show()\n fig.savefig('sensitivity_mean_noun_plot.png')\n elif mode == 'verb':\n fig = plt.figure(figsize=(20, 5))\n for j in range(1, 6):\n filename = 'synonym-list-V-{}.csv'.format(j)\n df = pd.read_csv(filename, sep=',')\n plt.subplot(1, 5, j)\n sns.boxplot(data=df)\n plt.title(filename.split('.')[0])\n plt.show()\n fig.savefig('sensitivity_mean_verb_plot.png')\n\n\ndef create_performance_plot(filepath_noun, filepath_verb, savefile):\n \"\"\"performance plot\"\"\"\n df_noun = pd.read_csv(filepath_noun, sep=',')\n df_verb = pd.read_csv(filepath_verb, sep=',')\n fig, axarr = plt.subplots(2, 2, figsize=(20, 15))\n colormaps = [colors.rgb2hex(colormap(i)) for i in np.linspace(0, 1, 5)]\n\n for i, c in enumerate(colormaps):\n x_n = df_noun['dim'][4 * i:4 * (i + 1)]\n y_n_mean = df_noun['mean'][4 * i:4 * (i + 1)]\n y_n_sd = df_noun['sd'][4 * i:4 * (i + 1)]\n\n l_n = df_noun['filename'][4 * i]\n\n x_v = df_verb['dim'][4 * i:4 * (i + 1)]\n y_v_mean = df_verb['mean'][4 * i:4 * (i + 1)]\n y_v_sd = df_verb['sd'][4 * i:4 * (i + 1)]\n\n l_v = df_verb['filename'][4 * i]\n\n axarr[0, 0].scatter(x_n, y_n_mean, label=l_n, linewidth=2, c=c)\n axarr[0, 0].plot(x_n, y_n_mean, label=l_n, linewidth=2, c=c)\n\n axarr[0, 1].scatter(x_n, y_n_sd, label=l_n, linewidth=2, c=c)\n axarr[0, 1].plot(x_n, y_n_sd, label=l_n, linewidth=2, c=c)\n\n axarr[1, 0].scatter(x_v, y_v_mean, label=l_v, linewidth=2, c=c)\n axarr[1, 0].plot(x_v, y_v_mean, label=l_v, linewidth=2, c=c)\n\n axarr[1, 1].scatter(x_v, y_v_sd, label=l_v, linewidth=2, c=c)\n axarr[1, 1].plot(x_v, y_v_sd, label=l_v, linewidth=2, c=c)\n\n axarr[0, 0].legend(loc='upper right',\n ncol=3,\n fontsize=7)\n axarr[0, 1].legend(loc='upper right',\n ncol=3,\n fontsize=7)\n axarr[1, 0].legend(loc='upper right',\n ncol=3,\n fontsize=7)\n axarr[1, 1].legend(loc='upper right',\n ncol=3,\n fontsize=7)\n\n axarr[0, 0].set_title('mean cosine of nouns')\n axarr[0, 1].set_title('sd cosine of nouns')\n axarr[1, 0].set_title('mean cosine of verbs')\n axarr[1, 1].set_title('sd cosine of verbs')\n\n axarr[0, 0].set_xlabel('dimension')\n axarr[0, 1].set_xlabel('dimension')\n axarr[1, 0].set_xlabel('dimension')\n axarr[1, 1].set_xlabel('dimension')\n\n axarr[0, 0].set_ylabel('mean cosine similarity')\n axarr[0, 1].set_ylabel('sd cosine similarity')\n axarr[1, 0].set_ylabel('mean cosine similarity')\n axarr[1, 1].set_ylabel('sd cosine similarity')\n\n fig.savefig(savefile)\n plt.show()\n\n\ndef main(testmode):\n # word_list, nouns_list, verbs_list = create_word_list(testmode=testmode)\n #\n # create_syn_list(words=nouns_list, word_list=word_list, filename=NOUN_FILENAME)\n # create_syn_list(words=verbs_list, word_list=word_list, filename=VERB_FILENAME)\n\n noun_cos_mean, noun_cos_sd, verb_cos_mean, verb_cos_sd = create_csv()\n\n create_summary(noun_cos_mean, noun_cos_sd, verb_cos_mean, verb_cos_sd)\n\n create_sensitivity_plot('noun')\n create_sensitivity_plot('verb')\n\n # for report\n create_sensitivity_plot('both')\n create_performance_plot('performance-five-noun-lists.csv',\n 'performance-five-verb-lists.csv',\n 'mean_sd.png')\n\n\nif __name__ == '__main__':\n main(testmode=False)\n","sub_path":"NLP_hw1/assignment1_Ye.py","file_name":"assignment1_Ye.py","file_ext":"py","file_size_in_byte":15558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"24942122","text":"import string\ndef build_shift_dict(shift):\n\n a = 'abcdefghijklmnopqrstuvwxyz'\n A = a.upper()\n return (dict(zip(a+A, a[shift:]+a[:shift] + A[shift:]+A[:shift])))\n \n\nget_message_text = 'We are taking 6.00.1x'\n\nshift = 2\nns = ''\nshift_dict = build_shift_dict(shift)\nfor s in get_message_text:\n if s in string.ascii_letters:\n ns=ns+shift_dict[s]\n else:\n ns+=s\n\nprint(ns)\n \n\n","sub_path":"Python/smallProjects/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"135906650","text":"from cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\n\n\nclass PrivateKey:\n def __init__(self, public_exponent=65537, key_size=2048, key=None):\n if key:\n self._key = key\n else:\n self._key = rsa.generate_private_key(\n public_exponent=public_exponent,\n key_size=key_size,\n backend=default_backend()\n )\n\n def to_pem(self):\n \"\"\"\n Convert private key to pem\n :return: private key in pem format\n :rtype: str\n \"\"\"\n return self._key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption()\n ).decode()\n\n @classmethod\n def load_from_pem(cls, private_key_pem):\n \"\"\"\n Load private key from pem\n :param private_key_pem:\n :type private_key_pem: bytes or str\n :return:\n \"\"\"\n if isinstance(private_key_pem, str):\n private_key_pem = private_key_pem.encode()\n\n key = serialization.load_pem_private_key(private_key_pem, password=None, backend=default_backend())\n return cls(key=key)\n\n\nclass UserPrivateKey(PrivateKey):\n def __init__(self, public_exponent=65537, key_size=2048, key=None):\n super(UserPrivateKey, self).__init__(public_exponent=public_exponent, key_size=key_size, key=key)\n\n def sign(self, data):\n \"\"\"\n Sign the data\n :param data:\n :type data: bytes\n :return: bytes\n \"\"\"\n return self._key.sign(data, padding.PKCS1v15(), hashes.SHA256())\n\n def public_numbers(self):\n return self._key.public_key().public_numbers()\n\n\nclass DomainPrivateKey(PrivateKey):\n def __init__(self, public_exponent=65537, key_size=2048, key=None):\n super(DomainPrivateKey, self).__init__(public_exponent=public_exponent, key_size=key_size, key=key)\n\n def generate_domain_csr(self, domains):\n \"\"\"\n Generate domain csr\n\n :param domains: a single domain or a list of domain\n :type domains: str or list\n :return: [CSR_in_PEM_Format, CSR_in_DER_Format]\n :rtype: list\n\n Usage::\n\n >>> domain_private_key = DomainPrivateKey()\n >>> single_domain_csr = domain_private_key.generate_domain_csr('www.example.com')\n >>> multiple_domains_csr = domain_private_key.generate_domain_csr(['example.com', 'www.example.com'])\n \"\"\"\n builder = x509.CertificateSigningRequestBuilder()\n builder = builder.subject_name(x509.Name([\n x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, domains[0])\n ]))\n builder = builder.add_extension(\n x509.SubjectAlternativeName([x509.DNSName(domain) for domain in domains]),\n critical=False\n )\n req = builder.sign(self._key, hashes.SHA256(), default_backend())\n return [req.public_bytes(serialization.Encoding.PEM), req.public_bytes(serialization.Encoding.DER)]\n\n\ndef der_to_pem(der_data):\n x = x509.load_der_x509_certificate(der_data, default_backend())\n return x.public_bytes(serialization.Encoding.PEM).decode()\n","sub_path":"certnode/crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"111636367","text":"import pickle\r\nimport numpy as np\r\nimport random\r\n\r\n# multiplexer\r\n# 6 signals come into the multiplexer\r\n# first two lines are A are decoded as a unsigned binary integer\r\n# this address values is then used to work out which of the four remaining signels\r\n# on the Data or d lines is to be passed thwough to the mulriplexer output\r\n\r\n\r\ndef generate_data(no_of_data_bits):\r\n \r\n data=\"\"\r\n for i in range(0,no_of_data_bits):\r\n data=data+str(random.randint(0,1))\r\n \r\n\r\n return(data)\r\n\r\ndef generate_signal(no_of_address_bits):\r\n \r\n addresses=\"\"\r\n for i in range(0,no_of_address_bits):\r\n addresses=addresses+str(random.randint(0,1))\r\n \r\n \r\n return(addresses)\r\n\r\n\r\n\r\ndef multiplexer(no_of_address_bits,no_of_data_bits):\r\n \r\n data=generate_data(no_of_data_bits)\r\n print(\"data=\",data)\r\n \r\n while True:\r\n signal=generate_signal(no_of_address_bits)\r\n \r\n print(\"signal=\",signal)\r\n # print(\"data=\",data)\r\n output_address=\"\"\r\n for i in range(0,len(signal)):\r\n output_address=output_address+str(int(signal[i],2)) #\"\".join(map(str,signal)),2)\r\n output=data[int(output_address,2)]\r\n\r\n print(\"output address=\",output_address)\r\n print(\"output=\",output)\r\n print(\"\")\r\n \r\n return\r\n\r\n\r\n\r\n\r\n\r\nno_of_address_bits=2\r\nno_of_data_bits=2**no_of_address_bits\r\ntotal_inputs=no_of_address_bits+no_of_data_bits\r\nprint(\"Address bits=\",no_of_address_bits,\" Data bits=\",no_of_data_bits,\" Total number of inputs=\",total_inputs)\r\n\r\n#addresses='0'*no_of_address_bits\r\n#data='0'*no_of_data_bits\r\n\r\n#print(\"before addresses=\",addresses)\r\n#print(\"before data=\",data)\r\n\r\nmultiplexer(no_of_address_bits,no_of_data_bits)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n##\r\n##stop_test=[(1,2),(3,4),(5,6),(7,8)]\r\n##no_of_stops=len(stop_test)\r\n##\r\n##pickle_test=dict(\r\n## names=[\"pid\",\"message\",\"redraw\",\"generation\", \"epoch_length\", \"bestgeneration\", \"best_distance\",\"stop\"],\r\n## formats=[np.int32,'|S25',np.bool,np.int32, np.int32, np.int32, np.float64, (np.int32, (no_of_stops,2))]\r\n##)\r\n##\r\n##path_screen_type = np.dtype(pickle_test)\r\n\r\n\r\n##path_screen_type = np.dtype(dict(\r\n## names=['generation', 'epoch_length', 'bestgeneration', 'best_distance','stop'],\r\n## formats=[np.int32, np.int32, np.int32, np.float64, (np.int32, (no_of_stops,2))],\r\n## offsets=[0, 8, 16, 16, 16]\r\n##))\r\n\r\n##path_screen_type = np.dtype(dict(\r\n## names=[\"pid\",\"message\",\"redraw\",\"generation\", \"epoch_length\", \"bestgeneration\", \"best_distance\",\"stop\"],\r\n## formats=[np.int32,np.str,np.bool,np.int32, np.int32, np.int32, np.float64, (np.int32, (no_of_stops,2))],\r\n## offsets=[5,3,0,0, 8, 8, 16, 0]\r\n##))\r\n\r\n##path_screen_type = np.dtype(dict(\r\n## names=[\"pid\",\"message\",\"redraw\",\"generation\", \"epoch_length\", \"bestgeneration\", \"best_distance\",\"stop\"],\r\n## formats=[np.int32,'|S25',np.bool,np.int32, np.int32, np.int32, np.float64, (np.int32, (no_of_stops,2))]\r\n##))\r\n\r\n##\r\n##\r\n##path_screen=np.zeros((1,),dtype=path_screen_type) # one row only\r\n##\r\n###path_screen=np.empty([1,],dtype=path_screen_type)\r\n##print(path_screen)\r\n##input(\"?\")\r\n####path_screen['epoch_length']=[1] #,2,3]\r\n####print(path_screen)\r\n####input(\"?\")\r\n##path_##\r\n##for i in range(0,no_of_stops):\r\n## path_screen[\"stop\"][0][i]=stop_test[i] # \r\n##\r\n##\r\n##print(path_screen)\r\n##input(\"?\")\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##x_as_bytes = pickle.dumps(path_screen)\r\n##print(x_as_bytes)\r\n##print(type(x_as_bytes))\r\n##\r\n##y = pickle.loads(x_as_bytes)\r\n##print(y)\r\n##\r\n##\r\n##\r\n##print(y[\"message\"][0].decode(\"utf-8\"))\r\n##print(y[\"redraw\"][0])\r\n##print(y[\"pid\"][0])\r\n##print(y[\"stop\"][0])\r\n##\r\n##y['stop'][0][1]=[55,66]\r\n##y['message'][0]=\"Hello, world! more\" #[1,2,3]\r\n##\r\n###print(path_scree)\r\n###input(\"?\")\r\n##y['stop'][0][1][0]=8\r\n##print(y)\r\n##print(y[\"message\"][0].decode(\"utf-8\"))\r\n##print(y[\"redraw\"][0])\r\n##print(y[\"pid\"][0])\r\n##print(y[\"stop\"][0])\r\n##\r\n##print(y)\r\n###input(\"?\")\r\n##\r\n###print(y.names)\r\n###print(y.fields)\r\n##input(\"?\")\r\n##\r\n#screen['generation'][0]=53 #[1,2,3]\r\n###print(path_screen)\r\n###input(\"?\")\r\n##path_screen['message'][0]=\"Hello, world!\" #[1,2,3]\r\n###print(path_screen)\r\n###input(\"?\")\r\n##path_screen['redraw'][0]=True #[1,2,3]\r\n###print(path_screen)\r\n###input(\"?\")\r\n##path_screen['pid'][0]=1234 #[1,2,3]\r\n###print(path_screen)\r\n###input(\"?\")\r\n##path_screen['best_distance'][0]=88.8 #[1,2,3]\r\n###print(path_screen)\r\n###input(\"?\")\r\n##path_screen['bestgeneration'][0]=9 #[1,2,3]\r\n###print(path_screen)\r\n###input(\"?\")\r\n\r\n\r\n##for i in range(0,len(genepool[bestjourneyno])):\r\n## print(i,stops[genepool[bestjourneyno][i]]) # \r\n## path_screen[\"stop\"][0][i]=stops[genepool[bestjourneyno][i]] # \r\n##\r\n##for i in range(0,no_of_stops):\r\n## path_screen[\"stop\"][0][i]=stop_test[i] # \r\n##\r\n##\r\n##print(path_screen)\r\n##input(\"?\")\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##\r\n##x_as_bytes = pickle.dumps(path_screen)\r\n##print(x_as_bytes)\r\n##print(type(x_as_bytes))\r\n##\r\n##y = pickle.loads(x_as_bytes)\r\n##print(y)\r\n##\r\n##\r\n##\r\n##print(y[\"message\"][0].decode(\"utf-8\"))\r\n##print(y[\"redraw\"][0])\r\n##print(y[\"pid\"][0])\r\n##print(y[\"stop\"][0])\r\n##\r\n##y['stop'][0][1]=[55,66]\r\n##y['message'][0]=\"Hello, world! more\" #[1,2,3]\r\n##\r\n###print(path_scree)\r\n###input(\"?\")\r\n##y['stop'][0][1][0]=8\r\n##print(y)\r\n##print(y[\"message\"][0].decode(\"utf-8\"))\r\n##print(y[\"redraw\"][0])\r\n##print(y[\"pid\"][0])\r\n##print(y[\"stop\"][0])\r\n##\r\n##print(y)\r\n###input(\"?\")\r\n##\r\n###print(y.names)\r\n###print(y.fields)\r\n##input(\"?\")\r\n##\r\n","sub_path":"multiplexer_string_v1.py","file_name":"multiplexer_string_v1.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"89782123","text":"from django.db import models\nfrom apartment.models import Apartment\nfrom django.contrib.auth.models import User\n\n\nclass Order(models.Model):\n customer = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='order')\n apartment = models.ForeignKey(Apartment, on_delete=models.DO_NOTHING, related_name='order')\n phone_number = models.CharField(max_length=14)\n text = models.CharField(max_length=300)\n is_active = models.BooleanField(default=True)\n date = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.customer.__str__() + \" | \" + self.apartment.__str__() + \" | \" + self.date.__str__()[:19]\n","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"146614705","text":"import os\r\nimport sys\r\nimport struct\r\n\r\ndef LzssUnc(buff,outlen):\r\n uncompr=bytearray(outlen)\r\n win=bytearray(0x1000)\r\n iWin=0xfee\r\n iSrc=0\r\n iDest=0\r\n while iSrc>i) & 1:\r\n if iDest>=outlen: break\r\n uncompr[iDest]=buff[iSrc]\r\n win[iWin]=buff[iSrc]\r\n iSrc+=1\r\n iDest+=1\r\n iWin=(iWin+1)&0xfff\r\n else:\r\n if iSrc+1>=len(buff): break\r\n count=(buff[iSrc+1] & 0xF)+3\r\n pos=(buff[iSrc]) | ((buff[iSrc+1]&0xf0)<<4)\r\n iSrc+=2\r\n for j in range(count):\r\n d=win[(pos+j)&0xfff]\r\n if iDest>=outlen: return uncompr\r\n uncompr[iDest]=d\r\n win[iWin]=d\r\n iDest+=1\r\n iWin=(iWin+1)&0xfff\r\n return uncompr\r\n\r\ndef lzss_uncompress(compr, comprlen, uncomprlen):\r\n\tact_uncomprlen = 0\r\n\tcurbit = 0\r\n\tnCurWindowByte = 0xfee\r\n\twin = ['\\0']*4096\r\n\tflag = 0\r\n\tuncompr = []\r\n\tcomprlen += compr.tell()\r\n\twhile compr.tell() < comprlen:\r\n\t\tflag >>= 1\r\n\t\tif (compr.tell() >= comprlen or len(uncompr)>=uncomprlen): break\r\n\t\tif not(flag & 0x0100):\r\n\t\t\tflag = ord(compr.read(1)) | 0xff00\r\n\t\t\tprint('%.1f%%\\r' % (len(uncompr)*100./uncomprlen),)\r\n\t\tif flag & 1:\r\n\t\t\tdata = compr.read(1)\r\n\t\t\tuncompr.append(data)\r\n\t\t\twin[nCurWindowByte&0xFFF]=data\r\n\t\t\tnCurWindowByte+=1\r\n\t\telse:\r\n\t\t\twin_offset = ord(compr.read(1))\r\n\t\t\tcopy_bytes = ord(compr.read(1))\r\n\t\t\twin_offset |= (copy_bytes & 0xf0) << 4\r\n\t\t\tcopy_bytes = (copy_bytes&0x0f)+3\r\n\t\t\tfor i in range(copy_bytes):\r\n\t\t\t\tdata = win[(win_offset + i) & 0xFFF]\r\n\t\t\t\tuncompr.append(data)\r\n\t\t\t\twin[nCurWindowByte&0xFFF] = data\r\n\t\t\t\tnCurWindowByte+=1\r\n\treturn ''.join(uncompr)\r\n\r\ndef UnpPAK():\r\n\tfiletype, filename, d, d, offset, filesize = range(6) #FileInfo\r\n\tPAK=open(sys.argv[1],'rb')\r\n\tif PAK.read(4)!=b'KCAP':\r\n\t\tprint('Only support KCAP Pak.')\r\n\t\tsys.exit()\r\n\tunknown, off, famount = struct.unpack('III', PAK.read(12))\r\n\tFileInfos = [struct.unpack('I24sIIII',PAK.read(0x2C)) \\\r\n for n in range(famount)]\r\n\tPath=os.path.splitext(sys.argv[1])[0]\r\n\tif not os.path.isdir(Path): os.mkdir(Path)\r\n\tPath+='\\\\'\r\n\tfor FileInfo in FileInfos:\r\n\t\tprint(FileInfo[filename].strip(b'\\0').decode('932'))\r\n\t#sys.exit()\r\n\tfor FileInfo in FileInfos:\r\n\t\tPAK.seek(FileInfo[offset])\r\n\t\tif FileInfo[filetype]==1:\r\n\t\t\tcomprlen, uncomprlen = struct.unpack('II', PAK.read(8))\r\n\t\t\tData = LzssUnc(PAK.read(comprlen), uncomprlen)\r\n\t\telif FileInfo[filetype]==0:\r\n\t\t\tData = PAK.read(FileInfo[filesize])\r\n\t\tprint(FileInfo[filename].strip(b'\\0').decode('932'))\r\n\t\topen(Path+FileInfo[filename].strip(b'\\0').decode('932'),'wb').write(Data)\r\n\r\ndef PckPAK():\r\n\tif(len(sys.argv)>2):\r\n\t\toutfile = sys.argv[2]\r\n\telse:\r\n\t\toutfile = sys.argv[1]+'.out.pak'\r\n\tFileList=[]\r\n\tfor n in os.listdir(sys.argv[1]):\r\n\t\tif os.path.isfile(sys.argv[1]+'\\\\'+n): FileList.append(n)\r\n\tHdr=['KCAP\\xcd\\xe8\\xbb\\xa7\\xba\\xda\\0\\0'+struct.pack('I', len(FileList))]\r\n\toffset=0x2c*len(FileList)+16\r\n\tfor n in FileList:\r\n\t\tCmprFlag='\\0\\0\\0\\0'\r\n\t\tFileName = n\r\n\t\tif os.path.splitext(n)[1].lower() in ['.uci', '.zgb', '.zgf']:\r\n\t\t\tFileName=os.path.splitext(n)[0]+'.tga'\r\n\t\t\tCmprFlag='\\1\\0\\0\\0'\r\n\t\tFileSize=os.path.getsize(sys.argv[1]+'\\\\'+n)\r\n\t\tFileName=FileName.decode('gbk').encode('shiftjis').lower()+'\\0'*(24-len(FileName))\r\n\t\tHdr.append(CmprFlag+FileName+'\\xcd\\xe8\\xbb\\xa7\\xba\\xda\\0\\0'+struct.pack('II', offset, FileSize))\r\n\t\toffset+=FileSize\r\n\tPAK=open(outfile,'wb')\r\n\tPAK.write(''.join(Hdr))\r\n\tfor n in FileList:\r\n\t\tPAK.write(open(sys.argv[1]+'\\\\'+n,'rb').read())\r\n\tprint(outfile+' created')\r\n\r\nsys.argv.append(r'D:\\wa2\\fnt.pak')\r\nUnpPAK()\r\n##if len(sys.argv)<2:\r\n##\tprint \"LEAF KCAP 3.0 Packer v0.1\\nUsage: %s \\nNotice: This tool only pack all the file but directory in specified DIR.\" % os.path.split(sys.argv[0])[1]\r\n##\tsys.exit()\r\n##PckPAK()\r\n","sub_path":"zeas/WA2/WorkSpace/32kcaPack.py","file_name":"32kcaPack.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"383400495","text":"import base64\nimport hashlib\nimport logging\nimport magic\nimport os\nimport pdfkit\nimport tempfile\nimport uuid\nfrom io import BytesIO\nfrom typing import List, Dict\nfrom PyPDF2 import PdfFileMerger\nfrom PyPDF2.utils import PdfReadError\nfrom threading import Thread\n\nTHREADS_LIMIT = 5\n\ndef merge(pdf_base64_encoded_list: List[str]=None) -> str:\n\n merger = PdfFileMerger(strict=False)\n files = {}\n pdf_threads = []\n output = BytesIO()\n\n for key, value in enumerate(pdf_base64_encoded_list):\n content = base64.b64decode(value)\n\n pdf_obj = BytesIO()\n pdf_obj.write(content)\n\n mime_type = magic.from_buffer(pdf_obj.getvalue(), mime=True)\n\n if mime_type != 'application/pdf':\n t = Thread(\n target=threaded_generate_pdf,\n args=(key, content.decode(), files)\n )\n t.start()\n pdf_threads.append(t)\n join_threads_routine(pdf_threads)\n else:\n files[key] = pdf_obj\n\n for t in pdf_threads:\n t.join()\n\n for f in files.values():\n merge_pdf(merger, f)\n\n merger.write(output)\n\n return base64.urlsafe_b64encode(output.getvalue())\n\ndef join_threads_routine(threads: List[Thread]):\n if len(threads) >= THREADS_LIMIT:\n while len(threads):\n threads.pop().join()\n\ndef generate_filename(content: str) -> str:\n m = hashlib.md5()\n m.update(content.encode())\n\n return \"{:s}/{:s}.pdf\".format(\n tempfile.gettempdir(),\n m.hexdigest()\n )\n\ndef generate_pdf(content: str) -> BytesIO:\n filename = generate_filename(content)\n output = BytesIO()\n\n if not os.path.isfile(filename):\n try:\n pdfkit.from_string(content, filename, options={\n 'quiet': '',\n 'encoding': 'utf-8'\n })\n except OSError:\n pass\n except Exception as err:\n raise err\n\n if not os.path.isfile(filename):\n raise FileNotFoundError('No PDF file generated for the following content: {:s}'.format(content))\n\n with open(filename, 'rb') as pdf:\n pdf_content = pdf.read()\n\n if len(pdf_content) == 0:\n raise ValueError('Defective PDF output for the following content: {:s}'.format(content))\n\n output.write(pdf_content)\n\n return output\n\ndef threaded_generate_pdf(id: int, content: str, files: Dict[int, BytesIO]):\n pdf_obj = generate_pdf(content)\n files[id] = pdf_obj\n\ndef merge_pdf(merger: PdfFileMerger, stream: BytesIO):\n try:\n merger.append(stream, import_bookmarks=False)\n except PdfReadError as err:\n if str(err) != \"EOF marker not found\":\n raise err\n\n stream.seek(0)\n fix_stream = BytesIO(stream.read() + b'%%EOF')\n merger.append(fix_stream, import_bookmarks=False)\n","sub_path":"app/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"409676647","text":"a = []\r\n\r\nmax = 0\r\n\r\nflag = False\r\nwhile flag == False:\r\n num = int(input('Ingrese un valor: '))\r\n if num != -1:\r\n a.append(num)\r\n\r\n if len(a) >= 2:\r\n for j in range(len(a) - 1):\r\n for i in range(len(a) - 1):\r\n if a[i] > a[i+1]:\r\n a[i], a[i+1] = a[i + 1], a[i]\r\n else:\r\n flag = True\r\n\r\nprint(f'El valor máximo de la lista {a} es {a[len(a)-1]}')\r\n","sub_path":"Facultad Fundamentos/TP6/ejer6ordenando.py","file_name":"ejer6ordenando.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"351439191","text":"class Setting():\n\tdef __init__(self):\n\t\tself.width = 800\n\t\tself.height = 600\n\t\tself.bg_color = (0x10,0x4e,0x8b) #104E8B\n\t\t\n\t\tself.ship_speed = 0.5\n\t\tself.ship_limit = 2\n\t\t\n\t\tself.bullet_speed = 1\n\t\tself.bullet_width = 3\n\t\tself.bullet_height = 15\n\t\tself.bullet_color = (255,255,0)\n\t\tself.max_bullet_number=3\n\t\t\n\t\tself.alien_speed = 0.5\n\t\tself.fleet_dir = -1\n\t\tself.fleet_drop_speed = 10\n\t\t\n\t\tself.debug_count = 0\n\t\t\n\t\tself.speedup_scale = 2#1.1\n\t\t\n\t\tself.alien_point = 50\n\t\t\n\t\tself.level = 1\n\t\t#self.init_dynamic_setting()\n\t\n\tdef reset(self):\n\t\tself.alien_speed = 0.5\n\t\tself.ship_speed = 0.5\n\t\tself.bullet_speed =1\n\t\tself.alien_point = 50\n\t\tself.level = 1\n\t\t\n\tdef level_up(self):\n\t\tself.alien_speed *= self.speedup_scale\n\t\tself.ship_speed *= self.speedup_scale\n\t\tself.bullet_speed *= self.speedup_scale\n\t\tself.alien_point = int(self.alien_point *self.speedup_scale)\n\t\tself.level += 1\n","sub_path":"game/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"205123061","text":"# -*- coding: utf-8 -*-\nimport fractions, random, os\nclass Key():\n def __init__(self, name):\n self.name = name\n self.public = []\n self.private = []\n def start(self):\n files = [self.name + \"/\" + self.name + \"_n.rsa\", self.name + \"/\" + self.name + \"_public.rsa\", self.name + \"/\" + self.name + \"_private.rsa\"]\n with open(files[0], \"r\") as nVal:\n with open(files[1], \"r\") as e:\n nv = int(nVal.read())\n self.public = [int(e.read()), nv]\n with open(files[2], \"r\") as d:\n self.private = [int(d.read()), nv]\n def generate(self):\n self.public = []\n self.private = []\n self.p = 61 # one prime\n self.q = 53 # another prime\n self.n = (self.p)*(self.q) # the modulo\n self.totient = (self.p-1)*(self.q-1) # totient\n self.e = 2\n while True:\n if fractions.gcd(self.e, self.totient)==1: # if coprime\n break\n else:\n self.e = random.randint(2, self.totient) # continue to pick a random number in the range 1 < e < totient\n self.d = 2\n while True:\n if (self.d)*(self.e)%self.totient==1: # if modulo of de == 1\n break\n else:\n self.d = random.randint(2, self.n)\n self.public = [self.e, self.n]\n self.private = [self.d, self.n]\n files = [self.name + \"/\" + self.name + \"_n.rsa\", self.name + \"/\" + self.name + \"_public.rsa\", self.name + \"/\" + self.name + \"_private.rsa\"]\n values = [self.n, self.e, self.d]\n for x in range(len(files)):\n with open(files[x], \"w\") as xFile:\n xFile.write(str(values[x]))\n return True\n def getPublic(self):\n return self.public\n def getPrivate(self):\n return self.private\n\nclass Change():\n def __init__(self, public, private):\n self.public = public\n self.private = private\n def encrypt(self, file):\n with open(file, \"r\", encoding=\"utf-8\") as xFile:\n self.contents = xFile.read()\n open(file, \"w\", encoding=\"utf-8\").close()\n with open(file, \"r\", encoding=\"utf-8\") as xFile:\n for x in range(len(self.contents)):\n encr = ord(self.contents[x])**self.public[0]%self.public[1]\n xFile.write(chr(encr))\n def decrypt(self, file):\n with open(file, \"r\", encoding=\"utf-8\") as xFile:\n self.contents = xFile.read()\n open(file, \"w\", encoding=\"utf-8\").close()\n with open(file, \"w\", encoding=\"utf-8\") as xFile:\n for x in range(len(self.contents)):\n encr = ord(self.contents[x])**self.private[0]%self.private[1]\n xFile.write(chr(encr))\nmyKey = Key(\"hey\")\nnewpath = myKey.name\nif os.path.exists(newpath):\n myKey.start()\n x = Change(myKey.getPublic(), myKey.getPrivate())\n plaintext = \"hey world\"\n print(\"plaintext: \" + str(plaintext))\n encrypt = x.encrypt(plaintext)\n decrypt = x.decrypt(x.encrypt(plaintext))\n print(\"encrypted: \", end=\"\")\n for x in range(len(encrypt)):\n print(encrypt[x], end=\"\")\n print()\n print(\"decrypted: \", end=\"\")\n for x in range(len(decrypt)):\n print(decrypt[x], end=\"\")\nelse:\n os.makedirs(newpath)\n if myKey.generate() == True:\n print(\"Key generation \" + newpath + \" successful.\")","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"254225679","text":"######################################################################\r\n# Array Processor #\r\n# This program sorts arrays and searches for values #\r\n# Author: Martin Vu and Sean Cheong #\r\n# Date: 13/5/2020 #\r\n# Version number 1.11.0 #\r\n######################################################################\r\n\r\n\r\nimport tkinter as tk\r\nfrom tkinter import font as tkfont\r\nfrom tkinter import messagebox\r\n\r\n\r\nclass app(tk.Tk): # inherits functions of tkinter within class\r\n\r\n def __init__(self, *args, **kwargs): # when class main is called fucntion is initialized\r\n tk.Tk.__init__(self, *args, **kwargs) # initialises tkinter\r\n # args (arguments) passes unlimited amount of variables\r\n # kwargs (keyword arguemnts) passes dictionaries\r\n\r\n self.title_font = tkfont.Font(family='arial', size=18, weight=\"bold\", slant=\"italic\")\r\n\r\n container = tk.Frame(self) # creates frame for container\r\n container.pack(side=\"top\", fill=\"both\", expand=True)# fills empty space within pack\r\n container.grid_rowconfigure(0, weight=1)\r\n container.grid_columnconfigure(0, weight=1)\r\n\r\n self.frames = {}\r\n for F in (Home, Search, Sort): # loop for the pages\r\n page_name = F.__name__\r\n frame = F(parent=container, controller=self)\r\n self.frames[page_name] = frame\r\n\r\n frame.grid(row=0, column=0, sticky=\"nsew\")# stretches everything in frame to nsew\r\n\r\n self.show_frame(\"Home\")\r\n\r\n def show_frame(self, page_name): # Shows a frame for the given page name\r\n frame = self.frames[page_name]\r\n frame.tkraise() # raises the given frame to the top fo the stack which is the visible one\r\n\r\n\r\nclass Home(tk.Frame): # home page, inherits everthing from frame\r\n\r\n def __init__(self, parent, controller): # parent main class\r\n tk.Frame.__init__(self, parent)\r\n self.controller = controller\r\n label = tk.Label(self, text=\"Array Processor\",font=controller.title_font) #Title\r\n label.pack(side=\"top\", fill=\"x\", pady=10)\r\n label = tk.Label(self, text=\"Choose either Search or Sort: \", font='arial')# Choosing sort label\r\n label.pack(side=\"top\", fill=\"x\", pady=10)\r\n\r\n SearchB = tk.Button(self, text=\"Search\",command=lambda: controller.show_frame(\"Search\")) # search button\r\n SortB = tk.Button(self, text=\"Sort\",command=lambda: controller.show_frame(\"Sort\")) # sort button\r\n SearchB.pack(pady=5)\r\n SortB.pack()\r\n\r\n\r\nclass Search(tk.Frame):\r\n\r\n def __init__(self, parent, controller):\r\n def LinearB(): # Linear Search ouput button\r\n while True:\r\n try:\r\n array = inputA.get() # saves the input to array\r\n array = array.split(\" \")\r\n map_object = map(int, array) # converts each element into integers\r\n array = list(map_object) # saves each element to the array\r\n target = int(inputT.get()) # saves the input to target\r\n \r\n break\r\n except ValueError:\r\n messagebox.showerror(title=\"Error\", message=\"Enter a numeric value\")\r\n app.mainloop()\r\n\r\n Result = Linear_search(array, target)# calls linear search subprogram\r\n Output.config(state=\"normal\")# allows the output box to be interacted with\r\n Output.delete(0.0, \"end\") \r\n Output.insert(\"insert\", Result)# inserts the variable Result\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def Linear_search(array, target): # Linear Search algorithm\r\n index = 0 # defines index\r\n found = False # defines found\r\n while index < len(array) and found == False: #post test loop; array isnt transversed and target isnt found\r\n if int(array[index]) == target: #tests if pointer is on target\r\n return \"Found at postion \"+(str(index+1)) #returns to LinearB()\r\n else:\r\n index += 1 #increments index\r\n if found == False:\r\n return \"Not Found\" #returns to LinearB()\r\n\r\n def BinaryB(): # Binary Search output button\r\n while True:\r\n try:\r\n array = inputA.get() # saves the input to array\r\n array = array.split(\" \") # splits the string into elements\r\n map_object = map(int, array) # converts each element into integer\r\n target = int(inputT.get()) # saves the input to target\r\n array = list(map_object) # saves each element to the array\r\n array = sorted(array) #sorts the array \r\n break\r\n except ValueError:\r\n messagebox.showerror(title=\"Error\", message=\"Enter a numeric value\")\r\n app.mainloop()\r\n\r\n Result = Binary_search(array, target) # calls binary search\r\n Output.config(state=\"normal\")# allows the output box to be interacted with\r\n Output.delete(0.0, \"end\")\r\n Output.insert(\"insert\", Result)# insert the variable Result\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def Binary_search(array, target): # Binary search algorithm\r\n found = False #defines found\r\n low = 0 #defines low\r\n high = len(array)-1 #defines high as n-1 as list referencing starts at 0\r\n while high >= low: #post test loop; stops searching if valid search area is vialated\r\n mid = ((high + low)//2) #defines and finds mid\r\n if target < int(array[mid]): # compares target to mid\r\n high = mid - 1 #makes high of new search area the mid-1 of old search area\r\n elif target == int(array[mid]): #checks if target is at mid\r\n return \"Found at postion \"+(str(mid+1)) #returns to BinaryB()\r\n else: # only other possibility is target > array[mid]\r\n low = mid + 1 #makes low of new search area the mid+1 of old search area\r\n return \"Not Found\" #returns to BinaryB()\r\n\r\n def clear(): # Clear button subprogram\r\n inputA.delete(0, \"end\") # clears input inside array\r\n inputT.delete(0, \"end\") # clears input inside target\r\n Output.config(state=\"normal\")# allows the output box to be interacted with\r\n Output.delete(1.0, \"end\")\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def Help(): # Help button subprogram\r\n messagebox.showinfo(\"Help\", \"Search Array\\n\" # output for the message box\r\n \"\\n\"\r\n \"Input the array and input a value that you want to be searched\\n\"\r\n \"Select the type of search:\\n\"\r\n \"Linear or Binary\\n\"\r\n \"\\n\"\r\n \"Note if you select binary the array is sorted first and the target is in the new position of the array\\n\")\r\n\r\n tk.Frame.__init__(self, parent)\r\n self.controller = controller\r\n label = tk.Label(self, text=\"Search\", font=controller.title_font)# Title for Search\r\n label.grid(row=1, column=2)\r\n\r\n seperator1 = tk.Frame(self, height=2, bd=1) # Creates space in the GUI\r\n seperator1.grid(padx=10, pady=10, sticky=\"we\")\r\n\r\n arrayL = tk.Label(self, text=\"Array: \") # Label for Array\r\n arrayL.grid(row=3, column=1)\r\n inputframe = tk.Frame(self) # input frame for array\r\n inputframe.grid(row=3, column=2)\r\n inputA = tk.Entry(inputframe, width=35) # Input box for the array\r\n inputA.grid()\r\n\r\n target = tk.Label(self, text=\"Target: \") # Label for Target\r\n target.grid(row=4, column=1)\r\n inputframe = tk.Frame(self) # input frame target\r\n inputframe.grid(row=4, column=2)\r\n inputT = tk.Entry(inputframe, width=35) # Input box for the target\r\n inputT.grid()\r\n\r\n seperator1 = tk.Frame(self, height=5, bd=1) # Creates space in the GUI\r\n seperator1.grid(padx=10, pady=10, sticky=\"we\")\r\n\r\n LinearB = tk.Button(self, text=\"Linear\", padx=20, command=LinearB) # Button for linear search\r\n LinearB.grid(row=5, column=1, columnspan=2, sticky=\"es\", pady=10)\r\n BinaryB = tk.Button(self, text=\"Binary\", padx=20, command=BinaryB) # Button for binary search\r\n BinaryB.grid(row=5, column=1, columnspan=2, sticky=\"s\", pady=10)\r\n\r\n seperator2 = tk.Frame(self, height=2, bd=1) # Creates space in the GUI\r\n seperator2.grid(padx=10, pady=10, sticky=\"we\")\r\n\r\n OutputL = tk.Label(self, text=\"Result: \") # Result label\r\n OutputL.grid(row=9, column=1)\r\n outputframe = tk.Frame(self) # output frame for the result\r\n outputframe.grid(row=9, column=2)\r\n Output = tk.Text(outputframe, state=\"disabled\", height=1,width=25) # Output box for the Result\r\n Output.grid()\r\n\r\n # Button for clearing the inputs and outputs\r\n ClearB = tk.Button(self, text=\"Clear\", padx=20, command=clear)\r\n ClearB.grid(row=23, column=1, columnspan=2, sticky=\"es\", pady=10)\r\n\r\n HelpB = tk.Button(self, text=\"Help\", padx=20,command=Help) # Help button label\r\n HelpB.grid(row=23, column=1, columnspan=2, sticky=\"s\", pady=10)\r\n\r\n HomeB = tk.Button(self, text=\"Home\", command=lambda: controller.show_frame(\"Home\")) # Home button\r\n HomeB.grid(column=2)\r\n\r\n\r\nclass Sort(tk.Frame):\r\n\r\n def __init__(self, parent, controller):\r\n\r\n def BubbleB():\r\n while True:\r\n try:\r\n array = inputA.get() # input for the array\r\n array = array.split(\" \") # splits the array with commas\r\n map_object = map(int, array) # makes elements in arrray integers\r\n array = list(map_object) # saves the int elements to array\r\n break\r\n except ValueError:\r\n messagebox.showerror(title=\"Error\", message=\"Enter a numeric value\")\r\n app.mainloop()\r\n if options_value.get() == 1: # calls bubble ascending when ascending radio button is selected\r\n Result = BubbleA_sort(array)\r\n else: # calls bubble descending when descending radio button is selected\r\n Result = BubbleD_sort(array)\r\n Output.config(state=\"normal\")# allows the output box to be interacted with\r\n Output.delete(0.0, \"end\")# inserts variable Result into output\r\n Output.insert(\"insert\", Result)\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def BubbleA_sort(array):\r\n for index in range(len(array)): # transverses the array\r\n for index in range(len(array)-1): #transverses the array n-1 times\r\n if array[index] > array[index+1]: #compares paired elements\r\n array[index], array[index +1] = array[index+1], array[index] #swaps so larger element is to the right\r\n return array #returns to BubbleB()\r\n\r\n def BubbleD_sort(array):\r\n for index in range(len(array)): # transverses the array\r\n for index in range(len(array)-1): #transverses the array n-1 times\r\n if array[index] < array[index+1]: #compares paired elements\r\n array[index], array[index +1] = array[index+1], array[index] #swaps so larger element is to the right\r\n return array #returns to BubbleB()\r\n\r\n def SelectionB():\r\n while True:\r\n try:\r\n array = inputA.get() # input for the array\r\n array = array.split(\" \") # splits the array with commas\r\n map_object = map(int, array) # makes elements in arrray integers\r\n array = list(map_object) # saves the int elements to array\r\n break\r\n except ValueError:\r\n messagebox.showerror(title=\"Error\", message=\"Enter a numeric value\")\r\n app.mainloop()\r\n if options_value.get() == 1: # calls selection ascending when ascending radio button is selected\r\n Result = SelectionA_sort(array)\r\n else: # calls selection descending when descending radio button is selected\r\n Result = SelectionD_sort(array)\r\n Output.config(state=\"normal\") # allows the output box to be interacted with\r\n Output.delete(0.0, \"end\")\r\n Output.insert(\"insert\", Result) # inserts variable Result into output\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def SelectionA_sort(array):\r\n for index in range(len(array)): #transverses the array\r\n Min = index #declares pointer of the sorted part of the array(assuming the first element is sorted)\r\n for unsorted in range(index+1, len(array)): #transverses through unsorted part of the array\r\n if array[Min] > array[unsorted]: #compares unsorted element with sorted element\r\n Min = unsorted #places the unsorted element in the sorted part\r\n array[Min], array[index] = array[index], array[Min] #swaps elements\r\n return array #returns to SelectionB()\r\n\r\n def SelectionD_sort(array):\r\n for index in range(len(array)): #transverses the array\r\n Min = index #declares pointer of the sorted part of the array(assuming the first element is sorted)\r\n for unsorted in range(index+1, len(array)): #transverses through unsorted part of the array\r\n if array[Min] < array[unsorted]: #compares unsorted element with sorted element\r\n Min = unsorted #places the unsorted element in the sorted part\r\n array[Min], array[index] = array[index], array[Min] #swaps elements\r\n return array #returns to SelectionB()\r\n\r\n def InsertionB():\r\n while True:\r\n try:\r\n array = inputA.get() # input for the array\r\n array = array.split(\" \") # splits the array with commas\r\n map_object = map(int, array) # makes elements in arrray integers\r\n array = list(map_object) # saves the int elements to array\r\n break\r\n except ValueError:\r\n messagebox.showerror(title=\"Error\", message=\"Enter a numeric value\")\r\n app.mainloop()\r\n if options_value.get() == 1: # calls insertion ascending when ascending radio button is selected\r\n Result = InsertionA_sort(array)\r\n else: # calls insertion descending when descending radio button is selected\r\n Result = InsertionD_sort(array)\r\n Output.config(state=\"normal\")# allows the output box to be interacted with\r\n Output.delete(0.0, \"end\")\r\n Output.insert(\"insert\", Result) # inserts Result into output\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def InsertionA_sort(array):\r\n for posofnext in range(1, len(array)): #transverses the array, note 1 assumes first element as sorted\r\n Next = array[posofnext] #saves value of unsorted element to be inserted\r\n current = posofnext-1 #defines position of sorted element\r\n while current >= 0 and Next < array[current]: #post test loop; keeps current within range, compares an unsorted and a sorted element\r\n array[current + 1] = array[current] #makes space\r\n current -= 1 #decrements current\r\n array[current + 1] = Next #inserts element in the correct position in the sorted part of the array\r\n return array #returns to InsertionB()\r\n\r\n def InsertionD_sort(array):\r\n for posofnext in range(1, len(array)): #transverses the array, note 1 assumes first element as sorted\r\n Next = array[posofnext] #saves value of unsorted element to be inserted\r\n current = posofnext-1 #defines position of sorted element\r\n while current >= 0 and Next > array[current]: #post test loop; keeps current within range, compares an unsorted and a sorted element\r\n array[current + 1] = array[current] #makes space\r\n current -= 1 #decrements current\r\n array[current + 1] = Next #inserts element in the correct position in the sorted part of the array\r\n return array #returns to InsertionB()\r\n\r\n def clear(): # clear button subprogram\r\n inputA.delete(0, \"end\") # clears array inside input box\r\n Output.config(state=\"normal\")# allows the output box to be interacted with\r\n Output.delete(1.0, \"end\")\r\n Output.config(state=\"disabled\") # Output cannot be interacted with\r\n\r\n def Help(): # Help button subprogram\r\n messagebox.showinfo(\"Help\", \"Sorting Array\\n\" # output for message box\r\n \"\\n\"\r\n \"Select Ascending if you want your array to be sorted in ascending order\\n\"\r\n \"or select Desending if you want your array to be sorted in descending order\\n\"\r\n \"\\n\"\r\n \"Input the array you want to be sorted\\n\"\r\n \"\\n\"\r\n \"Select a type sort:\\n\"\r\n \"Bubble, Selection or Insertion\")\r\n\r\n tk.Frame.__init__(self, parent)\r\n # Title for sort\r\n label = tk.Label(self, text=\"Sort\", font=controller.title_font)\r\n label.grid(row=1, column=1, columnspan=2)\r\n\r\n seperator1 = tk.Frame(self, height=2, bd=1) # Creates space in the GUI\r\n seperator1.grid(padx=10, pady=10, sticky=\"we\")\r\n\r\n # Label for Ascending or Descending\r\n options_label = tk.Label(self, text='Ascending or Descending: ')\r\n options_label.grid(row=3, column=1, columnspan=2)\r\n options_value = tk.IntVar()\r\n\r\n Ascending = tk.Radiobutton(self, text='Ascending', variable=options_value, value=1) # Radiobutton for Ascending\r\n Descending = tk.Radiobutton(self, text='Descending', variable=options_value, value=2) # Radio button for Ascending\r\n Ascending.grid(row=5, column=1, columnspan=2)\r\n Descending.grid(row=6, column=1, columnspan=2)\r\n options_value.set(1) # makes the default radiobutton ascending\r\n\r\n LArray = tk.Label(self, text=\"Array: \") # Label for Array\r\n LArray.grid(row=8, column=1)\r\n inputframe = tk.Frame(self) # input frame for input\r\n inputframe.grid(row=8, column=2)\r\n inputA = tk.Entry(inputframe, width=35) # input box for array\r\n inputA.grid()\r\n\r\n seperator2 = tk.Frame(self, height=2, bd=2) # Creates space in the GUI\r\n seperator2.grid(padx=5, pady=5, sticky=\"we\")\r\n\r\n BubbleB = tk.Button(self, text=\"Bubble\", padx=20,command=BubbleB) # Button for binary sort\r\n BubbleB.grid(row=11, column=1, sticky=\"es\")\r\n SelectionB = tk.Button(self, text=\"Selection\", padx=20, command=SelectionB) # Button for selection sort\r\n SelectionB.grid(row=11, column=2, sticky=\"s\")\r\n InsertionB = tk.Button(self, text=\"Insertion\", padx=20, command=InsertionB) # Button for insertion sort\r\n InsertionB.grid(row=11, column=3, sticky=\"s\")\r\n\r\n seperator3 = tk.Frame(self, height=2, bd=1) # Creates space in the GUI\r\n seperator3.grid(padx=5, pady=5, sticky=\"we\")\r\n\r\n LOutput = tk.Label(self, text=\"Sorted Array: \")# Label for Sorted Array\r\n LOutput.grid(row=14, column=2, rowspan=3)\r\n outputframe = tk.Frame(self) # output frame for sorted array\r\n outputframe.grid(row=19, column=2, rowspan=3)\r\n Output = tk.Text(outputframe, state=\"disabled\", height=1,width=25) # output box for sorted array\r\n Output.grid()\r\n\r\n seperator4 = tk.Frame(self, height=2, bd=1) # Creates Space in the GUI\r\n seperator4.grid(padx=5, pady=5, sticky=\"we\")\r\n\r\n ClearB = tk.Button(self, text=\"Clear\", padx=20,\r\n command=clear) # Clear button\r\n ClearB.grid(row=23, column=1, columnspan=2, sticky=\"es\", pady=10)\r\n\r\n HelpB = tk.Button(self, text=\"Help\", padx=20,command=Help) # Help Button\r\n HelpB.grid(row=23, column=1, columnspan=2, sticky=\"s\", pady=10)\r\n\r\n HomeB = tk.Button(self, text=\"Home\",command=lambda: controller.show_frame(\"Home\")) # help button\r\n HomeB.grid(column=2)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = app()\r\n app.mainloop()\r\n","sub_path":"array processor v1.11.0.py","file_name":"array processor v1.11.0.py","file_ext":"py","file_size_in_byte":21306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"178883177","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\nfrom flask_mail import Mail\nfrom config import Config\n\napp = Flask(__name__, instance_relative_config=False)\n\ndb = SQLAlchemy()\nbcrypt = Bcrypt(app)\n\napp.config['MAIL_SERVER'] = 'smtp.googlemail.com'\napp.config['MAIL_PORT'] = 587\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USERNAME'] = 'bensdrive89@gmail.com'\napp.config['MAIL_PASSWORD'] = '335Benben'\nSQLALCHEMY_TRACK_MODIFICATIONS = True\n\nmail = Mail(app)\n\ndef create_app():\n\tapp = Flask(__name__, instance_relative_config=False)\n\tapp.config.from_object('config.Config')\n\tdb.init_app(app)\n\twith app.app_context():\n\t\tfrom . import routes\n\n\t\tapp.register_blueprint(routes.main_bp)\n\t\t#db.create_all()\n\t\n\t\treturn app\n\nfrom app import routes","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"485919329","text":"import json\n\n\n\nif __name__ == \"__main__\":\n with open(\"news_data.json\", \"r\") as f:\n data = json.load(f)\n with open(\"news_classifier.json\", \"r\") as f:\n classifier = json.load(f)\n res = {}\n for date in data:\n tags = []\n for news in data[date]:\n cut = news[\"news_cut\"]\n flag = [0 for _ in range(2)]\n for key in classifier:\n if flag[classifier[key]-1]:\n continue\n if key in cut:\n flag[classifier[key]-1] = 1\n tags.append(2 * flag[1] + flag[0])\n res[date] = tags\n\n with open(\"news_classify.json\", \"w\") as f:\n json.dump(res, f)","sub_path":"proj/news_classify.py","file_name":"news_classify.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"268663351","text":"from sklearn import svm\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\n\nfrom predict_utils import *\n\n\ndef pca(batch_size, vgg_layer, component=None):\n '''\n Takes a VGG16 layer and returns a transformed PCA version.\n \n Parameters:\n - batch_size: int representing the total number of images\n - vgg_layer: numpy array representing a vgg16 layer\n - component: int representing the component to use\n \n Returns:\n - X_pca: numpy array \n '''\n X = vgg_layer.reshape((batch_size, -1))\n\n pca = PCA(n_components=component) # n_components = min(component, n_samples)\n pca.fit(X)\n X_pca = pca.fit_transform(X)\n\n # return pca.explained_variance_ratio_ # UTILIZE FOR VARIANCE EXPLAINED\n\n return X_pca if not component else X_pca[:,:component]\n\ndef run_svm(layer, labels, num_trials, leave_out, cross_val=5):\n '''\n Runs SVM on the given layer over the number of trials and returns\n the accuracy of each trial\n\n Parameters:\n - layer: numpy array of NN layer\n - labels: numpy array of labels associated with each image (index)\n - num_trials: int representing the number of trials to run on layer\n - leave_out: bool representing whether or not to use leave_n_out\n - cross_val: int representing the number of cross validation folds\n\n Returns:\n - accuracy: list of accuracy (float) for each trial (length=num_trials)\n ''' \n accuracy = []\n\n for i in range(num_trials):\n if leave_out:\n train_layer, test_layer, y_train, y_test = leave_n_out(layer, labels, 2, 4)\n else:\n train_layer, test_layer, y_train, y_test = train_test_split(layer, labels, test_size=0.2)\n\n X_train = train_layer.reshape((train_layer.shape[0], -1))\n X_test = test_layer.reshape((test_layer.shape[0], -1))\n y_train, y_test = np.array(y_train), np.array(y_test)\n\n clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)\n # scores = cross_val_score(clf, X_imgs, y_labs, cv=cross_val)\n accuracy.append(clf.score(X_test, y_test))\n\n return accuracy\n\n\ndef main(directory, img_paths, vgg_layers_path=None, num_trials=1, \n use_pca=False, component_used=None, leave_out=False, cross_val=5):\n '''\n Parameters:\n - directory: str representing the path to the directory where the images are\n - img_paths: str represnting the txt file where each line has the file name of each image\n - vgg_layers_path: str representing the path to the directory \n where the layers are (or should be saved)\n - num_trials: int representing the number of trials to run on layer\n - use_pca: bool representing whether or not to use PCA\n - component_used: int representing the component to use for PCA\n - leave_out: bool representing whether or not to use leave_n_out\n - cross_val: int representing the number of cross validation folds\n\n Returns:\n None\n '''\n output_file, plot_title, fig_name = build_names(num_trials, use_pca, component_used, leave_out)\n\n batch, batch_size, labels = loadImages(directory, img_paths)\n\n layers = getLayers(batch, batch_size, vgg_layers_path)\n\n\n\n variance_explained = {}\n\n \n results = {}\n for layer_name, layer in layers.items():\n\n if use_pca:\n \n layer = pca(batch_size, layer, component_used)\n\n # variance_explained[layer_name] = np.asarray(layer, dtype=float)\n\n \n\n accuracy = run_svm(layer, labels, num_trials, leave_out)\n results[layer_name] = accuracy\n\n\n # write_accuracies(output_file, variance_explained)\n\n write_accuracies(output_file, results)\n\n make_error_bar_plot(results, plot_title, fig_name)\n\n\ndef plot_from_npy(filename, filename2):\n\n after_mat = np.load(filename)\n after_mat2 = np.load(filename2)\n\n make_error_bar_plot_two(after_mat, after_mat2, \"VGG-16 with top 50 components\", \"vgg_pca50.png\")\n \n\n t_test_layer(after_mat)\n\n\n print('HOLD OUT')\n\n t_test_layer(after_mat2)\n\n\nif __name__ == '__main__':\n # MAKE SURE ALL PATHS ARE CORRECT\n directory = '/om/user/eeastman/interaction_images/'\n img_paths = directory + 'interaction_imgs.txt' # TEXT FILE WITH LIST OF IMAGE NAMES AND LABELS\n # WHERE EACH LINE HAS \"name_of_image.ext label\"\n vgg_layers_path = '/om/user/eeastman/layers/vgg-ft/'\n \n # PARAMETERS\n num_trials = 1\n use_pca = True\n pca_component_used = 49\n leave_out = False\n\n #plot_from_npy('output_files/vgg_ft_random_pca50.npy', 'output_files/vgg_ft_hold-out_pca50.npy')\n main(directory, img_paths, vgg_layers_path, num_trials, use_pca, pca_component_used, leave_out)\n\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"178598152","text":"import re\nimport sys\nimport json\nfrom utils.db import TwitterDBUtil\nfrom utils.foursquare import RateLimitExceeded\nfrom tasks.harvester import FSHarvester\n\ndef harvest(mode=1):\n harvester = FSHarvester()\n db_util = TwitterDBUtil()\n con = db_util.get_connection()\n con2 = db_util.get_connection()\n return_code = -1\n \n try:\n counter = 0\n print ('Selecting tweets.')\n tweets = db_util.list_latest_changed_tweets(con2)\n print ('Done.')\n total = tweets.__len__()\n for tweet in tweets:\n counter += 1\n metadata_old = json.loads(tweet['metadata'])\n if mode == 1:\n if metadata_old:\n urls = re.findall(r'(https?://\\S+)', tweet['text'])\n for url in urls:\n metadata = harvester.get_checkin_metadata(url)\n if metadata:\n if (metadata['checkin']['venue']['id'] != metadata_old['checkin']['venue']['id']):\n msg = db_util.save_metadata(con, tweet_id=tweet['tweet_id'], metadata=metadata)\n print ('Metadata updated: ' + msg + ' -- ' + str(counter) + '/' + str(total) + '.')\n return_code = 0\n else:\n msg = db_util.refresh_metadata(con, tweet_id=tweet['tweet_id'])\n print ('Checkin update unnecessary: ' + ' -- ' + str(counter) + '/' + str(total) + '.')\n return_code = 0\n break\n else:\n print ('Empty metadata: ' + ' -- ' + str(counter) + '/' + str(total) + '.')\n elif mode == 2:\n if metadata_old:\n venue = harvester.get_venue(metadata_old['checkin']['venue']['id'], {})\n if venue and venue['venue']['categories']:\n if venue['venue']['categories'] != metadata_old['venue']['categories']:\n metadata_old.update(venue)\n msg = db_util.save_metadata(con, tweet_id=tweet['tweet_id'], metadata=metadata_old)\n print ('Venue updated: ' + msg + ' -- ' + str(counter) + '/' + str(total) + '.')\n return_code = 0\n else:\n msg = db_util.refresh_metadata(con, tweet_id=tweet['tweet_id'])\n print ('Venue update unnecessary: ' + ' -- ' + str(counter) + '/' + str(total) + '.')\n return_code = 0\n else:\n print ('Empty metadata: ' + ' -- ' + str(counter) + '/' + str(total) + '.')\n elif mode == 3:\n if metadata_old and not metadata_old['venue']['categories']:\n venue = harvester.get_venue(metadata_old['checkin']['venue']['id'], {})\n if venue and venue['venue']['categories']:\n if venue['venue']['categories'] != metadata_old['venue']['categories']:\n metadata_old.update(venue)\n msg = db_util.save_metadata(con, tweet_id=tweet['tweet_id'], metadata=metadata_old)\n print ('Venue updated: ' + msg + ' -- ' + str(counter) + '/' + str(total) + '.')\n return_code = 0\n else:\n msg = db_util.refresh_metadata(con, tweet_id=tweet['tweet_id'])\n print ('Venue update unnecessary: ' + ' -- ' + str(counter) + '/' + str(total) + '.')\n return_code = 0\n else:\n print ('Empty metadata: ' + ' -- ' + str(counter) + '/' + str(total) + '.')\n \n \n print('Program terminated.')\n sys.exit(1)\n except RateLimitExceeded:\n pass\n finally:\n db_util.close_connection(con2)\n db_util.close_connection(con)\n \n return return_code\n\nif __name__ == '__main__':\n from utils import run\n # from utils.db.schema import cat_wrapper\n # cat_wrapper.refresh_categories()\n run(harvest, mode=3)\n run(harvest, mode=2)\n","sub_path":"MyTwitter/src/tasks/harvester/1_1_refresh_metadata.py","file_name":"1_1_refresh_metadata.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"197355191","text":"'''\nThe main loop of the program\n'''\n#import modules\nfrom serial_con import *\nfrom task import *\nfrom dim import *\nfrom calibrate_dist import *\nfrom navigate import *\n#from block_pickup import *\nfrom block_detect2 import *\nfrom drop_payload import *\nfrom park import *\nfrom test_servos import *\n\n#create board object\nboard = establish_serial(find_usb_port())\n\nprint('board')\n\n#initialise dimension object\nDim = Dim()\n\n#initialise tasks\nPark = Park(Dim)\nDrop_Payload = Drop_Payload(Dim)\nBlock_Detect = Block_Detect(Dim)\nCalibrate_Dist = Calibrate_Dist(Dim)\nNavigate = Navigate(Dim)\nTest_Servos = Test_Servos(Dim)\n\n\n#create list of tasks\ntasks = [Calibrate_Dist,Navigate,Block_Detect,Drop_Payload,Park,Test_Servos]\n#create dict of tasks\ntasks_dict = {\n 'Park':Park,\n 'Calibrate_Dist':Calibrate_Dist,\n 'Navigate':Navigate,\n 'Block_Detect':Block_Detect,\n 'Drop_Payload':Drop_Payload\n}\n#Activate correct tasks\nPark.active = 0\nCalibrate_Dist.active = 0\nNavigate.active = 1\nBlock_Detect.active = 1\nDrop_Payload.active = 0\nTest_Servos.active = 0\n#Initialise tasks in correct state\nNavigate.state = 0\n\n#main loop\nwhile True:\n #get serial input\n serial_in = read_next_line(board,decode=True,strip=True)\n\n #print serial input\n if serial_in != None:\n print(serial_in)\n\n #pass input into all tasks\n for Task in tasks:\n if Task.active == 1:\n #feed line into task object\n try:\n Task.get_instructions(Task.triggers[serial_in][Task.state])\n except:\n #print('var1 probably not defined')\n pass\n\n '''\n try:\n #adds responses to arduino interrupts to output\n Calibrate.get_instructions(Calibrate.triggers[serial_in][Calibrate.state])\n #catch error if no line has been read\n except KeyError:\n print('No Key found')\n '''\n\n #writes output of processing onto output\n Task.update()\n\n #write outputs onto serial (in order!)\n for output in Task.output:\n write_serial(output,board)\n\n #turn any tasks on/off\n for control in Task.task_control:\n task_to_control = tasks_dict[control[0]]\n task_to_control.activate(control[1],control[2])\n\n #clear output\n Task.output = []\n Task.task_control = []\n\n #reset serial\n serial_in = ''\n","sub_path":"final_code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"466909044","text":"#인터프리터 아나콘다를 설치 후 (환경 변수 설정+) 프로젝트와 연동\n#conda install selenium\nfrom urllib.parse import quote_plus\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\n\ndriver = webdriver.Chrome('/Users/ekxm2/PycharmProjects/chromedriver.exe')\n#사용자 구글드라이브 경로에 따라 변경\ndriver.implicitly_wait(3)\n\nbaseUrl = 'https://www.google.com/search?q='\nplusUrl = input('무엇을 검색할까요? : ')\nurl = baseUrl + quote_plus(plusUrl)\n\n\ndriver.get(url)\ndriver.implicitly_wait(3)\n\nhtml = driver.page_source\nsoup = BeautifulSoup(html, 'html.parser')\nv = soup.select('.yuRUbf')\nfor i in v:\n print(i.select_one('.LC20lb.DKV0Md').text)\n print(i.a.attrs['href'])\n print()\n\ndriver.close()\n","sub_path":"seTest01.py","file_name":"seTest01.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"580585631","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 2019年1月3日\n@author: Irony\n@site: https://pyqt5.com https://github.com/892768447\n@email: 892768447@qq.com\n@file: Utils.CommonUtil\n@description: 公共工具类\n\"\"\"\nimport hashlib\nimport logging\nimport os\n\nfrom Utils.Constants import LogName, LogFormatterDebug, LogFormatter\n\n__Author__ = \"\"\"By: Irony\nQQ: 892768447\nEmail: 892768447@qq.com\"\"\"\n__Copyright__ = \"Copyright (c) 2019 Irony\"\n__Version__ = \"Version 1.0\"\n\n\ndef qBound(miv, cv, mxv):\n return max(min(cv, mxv), miv)\n\n\ndef git_blob_hash(path):\n \"\"\"git方式计算文件sha1\n :param path: file path\n \"\"\"\n data = open(path, 'rb').read().replace(b'\\r\\n', b'\\n')\n data = b'blob ' + str(len(data)).encode() + b'\\0' + data\n return hashlib.sha1(data).hexdigest()\n\n\ndef initLog(name, file=None, level=logging.DEBUG, formatter=None):\n \"\"\"初始化日志记录配置\n :param name: log name\n :param file: log file\n :param level: log level\n :param formatter: log formatter\n \"\"\"\n\n formatter = formatter or logging.Formatter(\n LogFormatterDebug if level == logging.DEBUG else LogFormatter)\n\n logger = logging.getLogger(name)\n logger.setLevel(level)\n\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n logger.addHandler(stream_handler)\n\n file = os.path.abspath(str(file))\n if file and os.path.exists(file):\n file_handler = logging.FileHandler(file, mode='w', encoding='utf-8')\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n\nAppLog = logging.getLogger(LogName)\n","sub_path":"Utils/CommonUtil.py","file_name":"CommonUtil.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"309620368","text":"## TEST SPLINE FITTING\n# Given a set of 2D points, fits spline then plots\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom scipy.interpolate import interp1d\nimport dubins\n\n\n# Vehicle Constants (same as common.py)\nx_lim = [-10, 10]\ny_lim = [-10, 10]\ntheta_lim = [-np.pi, np.pi]\nnum_waypoints = 10\nwaypoint_tol = 0.2\n\nwheelbase = 0.335\nmax_acc = 3\nmax_steering_angle = 0.5\n\n# Generate random waypoints (same as waypoint_publisher.py)\nwaypoints = np.random.rand(num_waypoints, 3)\nwaypoints[:, 0] = (x_lim[1] - x_lim[0]) * waypoints[:, 0] + x_lim[0]\nwaypoints[:, 1] = (y_lim[1] - y_lim[0]) * waypoints[:, 1] + y_lim[0]\nwaypoints[:, 2] = (theta_lim[1] - theta_lim[0]) * waypoints[:, 2] + theta_lim[0]\n\n# # Linear length along the line:\n# # (https://stackoverflow.com/questions/52014197/how-to-interpolate-a-2d-curve-in-python)\n# distance = np.cumsum( np.sqrt(np.sum( np.diff(waypoints[:,:2], axis=0)**2, axis=1 )) )\n# distance = np.insert(distance, 0, 0)/distance[-1]\n\n# # Interpolation for different methods:\n# # Either quadratic or cubic works best\n# interpolations_methods = ['slinear', 'quadratic', 'cubic']\n# alpha = np.linspace(0, 1, 100)\n\n# interpolated_points = {}\n# for method in interpolations_methods:\n# interpolator = interp1d(distance, waypoints, kind=method, axis=0)\n# interpolated_points[method] = interpolator(alpha)\n\nturning_radius = 10 \nq0 = (waypoints[0,0], waypoints[0,1], waypoints[0,2])\nq1 = (waypoints[1,0], waypoints[1,1], waypoints[1,2])\nstep_size = 0.5\npath = dubins.shortest_path(q0, q1, turning_radius)\nconfigurations, _ = path.sample_many(step_size)\nconfigurations = np.array(configurations)\n\nplt.plot(configurations[:,0], configurations[:,1])\n## Plotting\n# Plot splines\n# for method_name, curve in interpolated_points.items():\n# # print(curve)\n# plt.plot(curve[:,0], curve[:,1], '-', label=method_name)\n\n \n# Plot waypoints and associated index\nplt.plot(waypoints[:,0], waypoints[:,1],'.')\nfor i in range(num_waypoints):\n plt.text(waypoints[i,0]+0.05, waypoints[i,1], str(i))\n plt.arrow(waypoints[i,0], waypoints[i,1], 0.2 * np.cos(waypoints[i,2]), 0.2* np.sin(waypoints[i,2]), head_width=0.2)\nplt.legend()\nplt.show()\n","sub_path":"ocrl/playground/testSpline.py","file_name":"testSpline.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"226465539","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n\ndef get_data1():\n\n mean2 = [0,0]\n cov2 = [[1,-0.8],[-0.8,1]]\n mean1 = [1,1]\n cov1 = [[1,0.0],[0.0,1]]\n\n x1,x2 = np.random.multivariate_normal(mean1, cov1, 100).T\n y = [0]*100\n\n\n x12,x22 = np.random.multivariate_normal(mean2, cov2, 150).T\n x1 = list(x1)\n x2 = list(x2)\n x1.extend(list(x12))\n x2.extend(list(x22))\n y.extend([1]*150)\n y = list(y)\n\n data = np.array([x1,x2,y]).T\n\n df = pd.DataFrame(data, columns=['x1', 'x2', 'y'])\n\n df = df.sample(frac=1).reset_index(drop=True)\n\n return df\n\n\n\ndef plot_2d(X,Y):\n return 1\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"224312939","text":"def calc(i):\r\n\tx = list(i)\r\n\tif len(x) == 1:\r\n\t\tif x[0] == '-':\r\n\t\t\treturn 1\r\n\t\telse:\r\n\t\t\treturn 0\r\n\telse:\r\n\t\ta = x[0]\r\n\t\tc = 0;\r\n\t\tfor b in x[1:]:\r\n\t\t\tif a != b:\r\n\t\t\t\tc=c+1\r\n\t\t\t\ta = b\r\n\t\tif x[-1] == '-':\r\n\t\t\tc = c+1\r\n\t\treturn c\r\n\t\t\t\r\n\t\t\r\n\r\nt = int(raw_input())\r\nfor i in xrange(1,t+1):\r\n\tprint(\"Case #{}: {}\").format(i,calc(raw_input()))\r\n\t\r\n","sub_path":"codes/CodeJamCrawler/16_0_2/shashankkn/pancake.py","file_name":"pancake.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289002142","text":"import functools\nimport operator\n\nimport data\nimport numpy as np\nimport results\nimport termcolor\nimport tqdm\n\n\nclass NaiveBayesClassifier:\n \"\"\"A class that treats a Naive Bayes classifier as programming primitive\n that has properties (nFeatures, params, priors) and behaviors (train,\n test, predict).\n \"\"\"\n\n def __init__(self, nFeatures: int):\n \"\"\"Creates a Naive Bayes Classifier with a given number of features.\"\"\"\n self.lastfile = termcolor.colored(\"not trained yet\", \"red\")\n self.nFeatures = nFeatures\n self.param_counts = np.zeros((nFeatures, 2, 2))\n self.prior_counts = np.zeros(2, dtype=\"float16\")\n\n def __str__(self):\n \"\"\"Reports status of classifier: num features, last file trained on.\"\"\"\n string = termcolor.colored(\"[Naive Bayes Classifier]\\n\", \"blue\")\n string += f\"Last File Trained On: {self.lastfile}\\n\"\n string += f\"Num Features: {self.nFeatures}\\n\"\n return string\n\n def __repr__(self):\n string = str(self)\n string += f\"Parameters:\\n{self.params}\\n\"\n string += f\"Priors:\\n {self.priors}\"\n return string\n\n @property\n def params(self):\n \"\"\"Returns a numpy array of parameters with shape (nFeatures, 2, 2)\n by normalizing counts obtained during training into probabilities.\n \"\"\"\n parameters = np.copy(self.param_counts)\n for feature_index in range(len(parameters)):\n feature_counts = parameters[feature_index]\n for label_index in range(len(feature_counts)):\n denom = sum(parameters[feature_index, label_index])\n parameters[feature_index, label_index] /= denom\n return parameters\n\n @property\n def priors(self):\n \"\"\"Returns a numpy array of priors with shape (2,) by normalizing\n counts obtained during training into probabilities.\n \"\"\"\n return self.prior_counts / sum(self.prior_counts)\n\n def train(self, data: data.Data, smoothing=False, restart=True):\n \"\"\"Given a data object, updates the internal counts for each of the\n input feaures.\"\"\"\n if restart and not smoothing:\n self.param_counts = np.zeros_like(self.param_counts)\n elif smoothing:\n self.param_counts = np.ones_like(self.param_counts)\n self.lastfile = data.filename\n for record in tqdm.tqdm(data.records, \"Training\"):\n y = record.pop()\n self.prior_counts[y] += 1\n for index, value in enumerate(record):\n self.param_counts[index, y, value] += 1\n record.append(y)\n\n def predict(self, vector):\n \"\"\"Takes in a list or numpy array representing an input feature vector\n and outputs a class prediction.\n \"\"\"\n probs = np.zeros(2)\n for label in (0, 1):\n prob_features = map(\n lambda tup: self.params[tup[0], label, tup[1]], enumerate(vector)\n )\n probs[label] = functools.reduce(\n operator.mul, prob_features, self.priors[label]\n )\n return 0 if probs[0] > probs[1] else 1\n\n def test(self, data: data.Data, name: str):\n \"\"\"Given a data object populated with attributes \"records\" that's a\n list of features + labels, runs the classifier on these training\n examples and collates the accuracy results.\n \"\"\"\n res = results.Results(name)\n for record in tqdm.tqdm(data.records, \"Testing\"):\n label = record.pop()\n pred = self.predict(record)\n res.add(pred, label)\n record.append(label)\n print(res)\n","sub_path":"probability/code/classifiers/naivebayes.py","file_name":"naivebayes.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"269560189","text":"# Write a program that asks the answer for a mathematical expression, checks whether the user is right or wrong,\n# and then responds with a message accordingly.\n\nfrom random import randint\n\nkeyWord = 'y'\nwhile keyWord.lower() == 'y':\n # генерируем переменную для математической операции\n mathSign_1 = randint(0, 1) # 0 - деление, 1 - умножение\n mathSign_2 = randint(0, 1) # 0 - вычитание, 1 = сложение\n\n number_1 = randint(1000, 10001)\n number_2 = randint(2, 5)\n number_3 = randint(1, 200)\n\n counter_of_attempts = 3\n while counter_of_attempts != 0:\n print('Type in the answer for the following mathematical expression (must be rounded of): ')\n # производим математические расчеты и вывод выражения\n # в зависимости от сгенерированных ранее \"математических знаков\"\n if mathSign_1 == 0:\n result = number_1 / number_2\n if mathSign_2 == 0:\n result -= number_3\n print(f'{number_1} / {number_2} - {number_3}')\n else:\n result += number_3\n print(f'{number_1} / {number_2} + {number_3}')\n else:\n result = number_1 * number_2\n if mathSign_2 == 0:\n result -= number_3\n print(f'{number_1} * {number_2} - {number_3}')\n else:\n result += number_3\n print(f'{number_1} * {number_2} + {number_3}')\n\n # блок с вводом данных пользователем\n while True:\n answer = input('Answer: ')\n if not answer.isdigit():\n print('Invalid number!')\n continue\n answer = int(answer)\n break\n\n # блок с проверкой введенных данных\n if answer == round(result):\n print('You are right!')\n break\n else:\n counter_of_attempts -= 1\n print(f'Incorrect answer. You have {counter_of_attempts} more attempts')\n keyWord = input('Would you like to play again? (y - yes, n - no): ')\n","sub_path":"task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"111998695","text":"from sklearn.externals import joblib\nfrom weasyprint import HTML\nfrom jinja2 import Environment, FileSystemLoader\nimport pandas as pd\nfrom models import Base, User, HeartTest\nfrom flask import Flask, jsonify, request, url_for, abort, g, render_template,make_response, send_file, make_response,send_from_directory\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, sessionmaker\nfrom sqlalchemy import create_engine\nfrom flask.ext.httpauth import HTTPBasicAuth\nimport json\nfrom oauth2client.client import flow_from_clientsecrets, FlowExchangeError\nimport httplib2\nimport requests\n\nauth = HTTPBasicAuth()\n\n\nengine = create_engine('sqlite:///medic.db')\n\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\napp = Flask(__name__)\n\n\n\n@auth.verify_password\ndef verify_password(username_or_token, password):\n #Try to see if it's a token first\n user_id = User.verify_auth_token(username_or_token)\n if user_id:\n user = session.query(User).filter_by(id = user_id).one()\n else:\n user = session.query(User).filter_by(username = username_or_token).first()\n if not user or not user.verify_password(password):\n return False\n g.user = user\n return True\n\n@app.route('/')\ndef start():\n return render_template('index1.html')\n\n\n@app.route('/token')\n@auth.login_required\ndef get_auth_token():\n token = g.user.generate_auth_token()\n return jsonify({'token': token.decode('ascii')})\n\n\n\n@app.route('/users', methods = ['POST'])\ndef new_user():\n username = request.json.get('username')\n password = request.json.get('password')\n if username is None or password is None:\n print (\"missing arguments\")\n abort(400)\n\n if session.query(User).filter_by(username = username).first() is not None:\n print (\"existing user\")\n user = session.query(User).filter_by(username=username).first()\n return jsonify({'message':'user already exists'}), 200#, {'Location': url_for('get_user', id = user.id, _external = True)}\n\n user = User(username = username)\n user.hash_password(password)\n session.add(user)\n session.commit()\n return jsonify({ 'username': user.username }), 201#, {'Location': url_for('get_user', id = user.id, _external = True)}\n\n@app.route('/api/v1/users/')\ndef get_user(username):\n user = session.query(User).filter_by(username = username).first()\n if not user:\n jsonify({'AuthenticationError': username})\n return jsonify({ 'id':user.id, 'username': user.username })\n\n@app.route('/api/v1/hearttests', methods = ['GET', 'POST'])\n@auth.login_required\ndef showAllHeartTests():\n if request.method == 'GET':\n hearttests = session.query(HeartTest).filter_by(user_id = g.user.id).all()\n return jsonify(hearttests = [h.serialize for h in hearttests])\n if request.method == 'POST':\n firstname = request.json.get('firstname')\n lastname = request.json.get('lastname')\n patientno = request.json.get('patientno')\n age = request.json.get('age')\n sex = request.json.get('sex')\n cp = request.json.get('cp')\n trestbps = request.json.get('trestbps')\n chol = request.json.get('chol')\n fbs = request.json.get('fbs')\n restecg = request.json.get('restecg')\n thalach = request.json.get('thalach')\n exang = request.json.get('exang')\n oldpeak = request.json.get('oldpeak')\n slope = request.json.get('slope')\n ca = request.json.get('ca')\n thal = request.json.get('thal')\n heart_test = {'age':age,'sex':sex, 'cp':cp,'trestbps':trestbps,'chol':chol,'fbs':fbs,'restecg':restecg, \\\n 'thalach':thalach,'exang':exang,'oldpeak':oldpeak,'slope':slope, 'ca':ca,'thal':thal}\n heart_test = pd.Series(heart_test)\n heart_test = heart_test.reshape(1,-1)\n result = joblib.load('VotingClassifier.pkl').predict(heart_test)\n result = float(result[0])\n heartTest = HeartTest(firstname = firstname,lastname = lastname,patientno = patientno,age = age,sex = sex,cp = cp, \\\n trestbps = trestbps,chol = chol,fbs = fbs, restecg = restecg,thalach = thalach,exang = exang,oldpeak = oldpeak,slope = slope,ca = ca, \\\n thal = thal, result = result, user_id = g.user.id)\n session.add(heartTest)\n session.commit()\n return jsonify(heartTest.serialize)\n\n\n\n@app.route('/api/v1/hearttests/', methods = ['GET', 'DELETE'])\n@auth.login_required\ndef getHeartTest(id):\n heartTest = session.query(HeartTest).filter_by(id = id,user_id=g.user.id).first()\n if request.method == 'GET':\n heartTest = jsonify(heartTest.serialize)\n return heartTest\n if request.method == 'DELETE':\n session.delete(heartTest)\n session.commit()\n return jsonify({'message':'HeartTest Successfully deleted'})\n\n\t\t\n@app.route('/api/v1/download/hearttests/', methods = ['GET'])\n@auth.login_required\ndef downloadHeartTest(id):\n heartTest = session.query(HeartTest).filter_by(id = id,user_id=g.user.id).first()\n env = Environment(loader=FileSystemLoader('templates'))\n template = env.get_template(\"report.html\")\n template_vars = {\"hearttest\": heartTest, 'cp': {1:'Typical angina',2:'Atypical angina',3:'Non-anginal pain',4:'Asymptomatic'}, \n 'thal': {3:'Normal',6:'Fixed Defect',7:'Reversable Defect'},\n 'restecg': {0:\"Normal\",1:\"Having ST-T wave abnormality\",2:\"Showing probable or definite left ventricular hypertrophy by Estes' criteria\"}, \n 'slope' : {1:'Upsloping',2:'Flat',3:'Downsloping'}}\n html_out = template.render(template_vars)\n HTML(string=html_out).write_pdf(\"report.pdf\")\n return send_from_directory('','report.pdf', as_attachment=True, mimetype='application/octet-stream')\n\n\nif __name__ == '__main__':\n app.debug = True\n #app.config['SECRET_KEY'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32))\n app.run(host='0.0.0.0', port=5002)\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"318758271","text":"from django.contrib.auth.models import Permission, User,AbstractBaseUser,BaseUserManager\nfrom django.db import models\n# for validatrions\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\nimport time\nlocaltime = time.localtime(time.time())\n\ndef validate_image(value):\n s=str(value)\n s=s.lower()\n l=s.split('.')\n if not(l.__contains__('jpg')) and not(l.__contains__('png')) and not(l.__contains__('gif')) and not(l.__contains__('ico')) and not(l.__contains__('bmp')):\n raise ValidationError(\n _('Image must be in following format : jpg,png,ico,bmp,gif')\n )\n\ndef validate_audio(value):\n s=str(value)\n s = s.lower()\n l=s.split('.')\n if not(l.__contains__('mp3')) and not(l.__contains__('mp4'))and not(l.__contains__('avi')) :\n raise ValidationError(\n _('Audio file must be in following format : mp3,mp4,avi')\n )\n\ndef validate_year(value):\n if value >int(localtime[0]) or value <=1800:\n raise ValidationError(\n _('Published Year must be in range of 1800 -'+str(localtime[0]))\n )\n\ndef user_song_relationship_genrator(s):\n all_user = User.objects.all()\n # song = Song.objects.filter(pk=str(songid))\n for user in all_user:\n obj = UserSongRelationship(user_id=user.id,song=s)\n obj.save()\ndef csv_generatore():\n all_users = User.objects.all()\n all_usersongrelationship = UserSongRelationship.objects.all()\n all_profile = Profile.objects.all()\n #songs.csv\n all_songs = Song.objects.all()\n with open('songs.csv','w') as new_file:\n new_file.write('song_id,album_id,song_title,artist,genre\\n')\n for song in all_songs:\n delimiter=','\n line=str(song.id)+delimiter+str(song.album.id)+delimiter+str(song.song_title)+delimiter+str(song.artist)+delimiter+str(song.genre)+str('\\n')\n new_file.write(line)\n\n\n # albums.csv\n all_albums = Album.objects.all()\n with open('albums.csv','w') as new_file:\n new_file.write('album_id,album_title,pub_year\\n')\n for album in all_albums:\n delimiter=','\n line=str(album.id)+delimiter+str(album.album_title)+delimiter+str(album.pub_year)+str('\\n')\n new_file.write(line)\n\n\n # users.csv\n all_users = Profile.objects.all()\n with open('users.csv', 'w') as new_file:\n new_file.write('user_id,username,email,gender,city,date_of_birth\\n')\n for user in all_users:\n delimiter = ','\n line =str(user.user.id)+delimiter+ str(user.user.username) + delimiter + str(user.user.email) + delimiter + str(user.gender)+ delimiter + str(user.city)+ delimiter + str(user.date_of_birth)+ str(\n '\\n')\n new_file.write(line)\n\n\n # usersongrelationships.csv\n all_userssongs = UserSongRelationship.objects.all()\n with open('usersongrelationships.csv', 'w') as new_file:\n new_file.write('user_id,song_id,is_favorite,is_added_to_playlist,listen_count\\n')\n for userssong in all_userssongs:\n delimiter = ','\n line = str(userssong.user.id)+delimiter+str(userssong.song.id)+delimiter+ str(userssong.is_favorite) + delimiter + str(userssong.is_added_to_playlist) + delimiter + str(\n userssong.listen_count) + str(\n '\\n')\n new_file.write(line)\n\n\n\n\nclass Album(models.Model):\n album_title = models.CharField(max_length=500,unique=True)\n album_logo = models.ImageField(upload_to='static/album_logo/',verbose_name=album_title,validators=[validate_image])\n pub_year = models.IntegerField(validators=[validate_year],default=localtime[0])\n def __str__(self):\n return self.album_title+' '+str(self.pub_year)\n def __repr__(self):\n return self.album_title+' '+str(self.pub_year)\n\nclass Song(models.Model):\n album = models.ForeignKey(Album, on_delete=models.CASCADE)\n song_title = models.CharField(max_length=250,unique=True)\n artist = models.CharField(max_length=250)\n audio_file = models.FileField(upload_to='static/songs/',validators=[validate_audio])\n genre_list = (('Bollywood','Bollywood'),('Dance','Dance'),('English','English'),('Hindi','Hindi'),('Hip-Hop','Hip-Hop'),('Love','Love'),('Pop','Pop'),('Punjabi','Punjabi'),('Remix','Remix'),('Rock','Rock'),('Soundtrack','Soundtrack'))\n genre= models.CharField(max_length=20,choices=genre_list,default='Bollywood',)\n\n def __str__(self):\n return self.song_title\n def save(self, *args,**kwargs):\n\n super(Song,self).save(*args,**kwargs)\n try:\n user_song_relationship_genrator(self)\n except:\n print('entgrity on song saving due to user_song_relationship_genrator ')\n finally:\n print(\"UserSong relastionship created\")\n\nclass UserSongRelationship(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE,)\n song=models.ForeignKey(Song, on_delete=models.CASCADE)\n is_favorite = models.BooleanField(default=False)\n is_added_to_playlist= models.BooleanField(default=False)\n listen_count=models.IntegerField(default=0)\n def __str__(self):\n return str(self.user)+\" \"+str(self.song)\n\n def save(self, *args,**kwargs):\n super(UserSongRelationship,self).save(*args,**kwargs)\n csv_generatore()\n\n class Meta:\n unique_together = (\"user\",\"song\" )\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n gender = models.CharField(max_length=20, choices=(('Male', 'Male'), ('Female', 'Female')), default='Male', )\n date_of_birth = models.DateField(default='2012-12-12')\n city = models.CharField(max_length=20, default='Gurgaon' )\n\n\n\n def __str__(self):\n return str(self.user)+' '+str(self.gender)\n\n\nclass Contact(models.Model):\n name=models.CharField(max_length=100)\n email=models.EmailField()\n city=models.CharField(max_length=100)\n message=models.TextField(max_length=1000)\n def __str__(self):\n return str(self.name)+' '+str(self.message)\n\n","sub_path":"music/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"511331238","text":"import re\nfrom operator import itemgetter\nfrom pyramid.renderers import get_renderer\nfrom docutils.core import publish_parts\n\nfrom pyramid.httpexceptions import (\n HTTPFound,\n HTTPNotFound,\n )\n\nfrom pyramid.view import (\n view_config,\n forbidden_view_config,\n )\n\nfrom pyramid.security import (\n remember,\n forget,\n authenticated_userid,\n )\n\nfrom codenamefun.views import site_layout\n\nfrom codenamefun.models import (\n DBSession,\n Page,\n User,\n Role,\n )\n\n@view_config(route_name='admin', renderer='codenamefun:templates/admin/admin.pt', permission='edit')\ndef admin(request):\n users = DBSession.query(User).order_by(User.name).all()\n result = DBSession.query(Page.id, Page.name, Page.data, Page.status).all()\n user = User();\n roles = DBSession.query(Role).all()\n col_names = ['id','name','data', 'status']\n posts = map(lambda row: dict(zip(col_names, row)), result)\n reversedPosts = reversed(sorted(posts, key=lambda k: k['id']))\n return {'posts': reversedPosts, 'users': users, 'user': user, 'roles': roles, 'layout': site_layout(), 'logged_in': authenticated_userid(request)}","sub_path":"codenamefun/views/admin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606950833","text":"import torch\nimport torch.nn.functional as F\nfrom torch.nn import Linear, Conv1d\nfrom torch import nn\nfrom tqdm import tqdm\n\nclass AttentionGraphModel(nn.Module):\n\n def __init__(self, g, n_layers, n_head, input_size, hidden_size, output_size, nonlinearity, device):\n \"\"\"\n Highly inspired from https://arxiv.org/pdf/1710.10903.pdf\n \"\"\"\n super().__init__()\n\n self.n_head = n_head\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n self.device = device\n self.g = g\n self.activation = nonlinearity\n self.linears = nn.ModuleList()\n self.attn_layers = nn.ModuleList()\n self.layers = [] # So that train still works, basically what we say is that we don't use dgl GraphConv\n\n self.add_attention_layer(input_size, hidden_size, n_head)\n\n for i in range(n_layers - 1):\n self.add_attention_layer(hidden_size*n_head, hidden_size, n_head)\n\n self.add_attention_layer(hidden_size*n_head, output_size, n_head)\n \n def add_attention_layer(self, n_features, n_hidden_features, n_head):\n linear = Linear(n_features, n_hidden_features)\n attn_layer = Conv1d(n_hidden_features*2*n_head, n_head, kernel_size=1, groups=n_head)\n \n self.linears.append(linear)\n self.attn_layers.append(attn_layer)\n\n def forward(self, inputs):\n outputs = inputs\n for i, (linear, attn_layer) in enumerate(zip(self.linears, self.attn_layers)):\n outputs = self.forward_attention(outputs, linear, attn_layer, final_layer=(i==self.n_layers))\n return outputs\n\n def get_h2(self, attn_layer, h, indices, adjacency_list):\n \"\"\"\n h2 is of size (n_nodes,n_hidden_features,n_head)\n \"\"\"\n n_nodes, n_features = h.shape\n n_edges = len(indices[0])\n\n # values = torch.zeros(n_edges, self.n_head, device=self.device)\n h_conv = h.repeat(1,self.n_head).view(n_nodes,1,n_features*self.n_head,1)\n h_concat = torch.cat([torch.cat((h_conv[i],h_conv[j]), dim=1) for (i,j) in zip(indices[0], indices[1])], dim=0)\n values = attn_layer(h_concat).view(n_edges, -1)\n \n # for k, (i,j) in enumerate(zip(indices[0], indices[1])):\n # values[k,:] = attn_layer(torch.cat((h_conv[i],h_conv[j]), dim=1)).view(-1)\n e = torch.sparse_coo_tensor(indices,values)\n\n alpha = torch.sparse.softmax(e, dim=1).coalesce()\n values = alpha.values()\n \n \n h2 = torch.zeros(n_nodes, n_features, self.n_head, device=self.device)\n for i,j,v in zip(indices[0], indices[1], values):\n h2[i,:,:] += h[j,:].unsqueeze(-1) @ v.unsqueeze(0)\n # t = time()\n # h2 = torch.zeros(n_nodes, n_features, self.n_head, device=self.device)\n # h = h.unsqueeze(2) # (n_nodes, n_features, 1)\n # values = values.unsqueeze(1) # (n_edges, 1, n_head)\n # for i in range(n_nodes):\n # h_neigh = torch.cat([h[j,:] for j in adjacency_list[i]], dim=1)\n # values_neigh = torch.cat([values[j,:] for j in adjacency_list[i]], dim=0)\n # h2[i] = h_neigh @ values_neigh\n # print(time()-t)\n\n return h2\n\n def forward_attention(self, x, linear, attn_layer, final_layer=False):\n h = F.leaky_relu(linear(x), negative_slope=0.2)\n\n indices, adjacency_list = self.get_graph_structure()\n\n h2 = self.get_h2(attn_layer, h, indices, adjacency_list)\n \n if final_layer:\n return self.activation(h2.mean(dim=-1))\n else:\n return self.activation(h2.view(h2.size(0),-1))\n\n\n def get_graph_structure(self):\n adjacency_matrix = self.g.adjacency_matrix().coalesce().to(self.device)\n indices = adjacency_matrix.indices()\n n_nodes = self.g.num_nodes()\n\n adjacency_list = [[]] * n_nodes\n for (i,j) in zip(indices[0], indices[1]):\n adjacency_list[i].append(j)\n\n return indices, adjacency_list","sub_path":"gat.py","file_name":"gat.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"271590128","text":"\"\"\"\nLet's do another example with the Rosenbrock problem that we just solved.\n\nLet's try adding a constraint to the problem that we previously solved. Recall that the unconstrained optimum that we\nfound occured at (x, y) == (1, 1).\n\nWhat if we want to know the minimum function value that is still within the unit circle. Clearly, (1,\n1) is not inside the unit circle, so we expect to find a different answer.\n\nLet's see what we get:\n\n\"\"\"\nimport aerosandbox as asb\n\nopti = asb.Opti()\n\n# Define optimization variables\nx = opti.variable(init_guess=1) # Let's change our initial guess to the value we found before, (1, 1).\ny = opti.variable(init_guess=1) # As above, change 0 -> 1\n\n# Define objective\nf = (1 - x) ** 2 + 100 * (y - x ** 2) ** 2\nopti.minimize(f)\n\n# Define constraint\nr = (x ** 2 + y ** 2) ** 0.5 # r is the distance from the origin\nopti.subject_to(\n r <= 1 # Constrain the distance from the origin to be less than or equal to 1.\n)\n\n\"\"\"\nNote that in continuous optimization, there is no difference between \"less than\" and \"less than or equal to\". (At \nleast, not when we solve them numerically on a computer - contrived counterexamples can be made.) So, use < or <=, \nwhatever feels best to you.\n\"\"\"\n\n# Optimize\nsol = opti.solve()\n\n# Extract values at the optimum\nx_opt = sol.value(x)\ny_opt = sol.value(y)\n\n# Print values\nprint(f\"x = {x_opt}\")\nprint(f\"y = {y_opt}\")\n\n\"\"\"\nNow, we've found a new optimum that lies on the unit circle.\n\nThe point that we've found is (0.786, 0.618). Let's check that it lies on the unit circle.\n\"\"\"\n\nr_opt = sol.value(r) # Note that sol.value() can be used to evaluate any object, not just design variables.\nprint(f\"r = {r_opt}\")\n\n\"\"\"\nThis prints out 1, so we're satisfied that the point indeed lies within (in this case, on, the unit circle).\n\nIf we look close, the value isn't exactly 1 - mine says `r = 1.0000000099588466`; yours may be different. This is due\nto convergence error and isn't a big deal.\n\n\"\"\"\n","sub_path":"tutorial/1 - Optimization and Math/2 - 2D Rosenbrock, constrained.py","file_name":"2 - 2D Rosenbrock, constrained.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"555622682","text":"import time\nfrom threading import Thread, Event\n\n\nstop_event = Event()\n\n\ndef thread_1(timeout=20):\n start = int(time.time())\n stopTime = start\n while stopTime - start <= timeout:\n print(f\"Thread 1 is running at {stopTime - start}\")\n time.sleep(5)\n stopTime = int(time.time())\n # print(f\"Thread 1 stopped at {stopTime - start}\")\n\n\ndef thread_2(timeout=20):\n start = int(time.time())\n stop = start\n while True:\n print(f\"Thread 2 is running at {stop - start}\")\n time.sleep(5)\n stop = int(time.time())\n\n\ndef thread_3(timeout=38):\n start = int(time.time())\n stop_time = start\n while stop_time - start <= timeout:\n print(f\"Thread 3 is running at {stop_time - start}\")\n time.sleep(5)\n stop_time = int(time.time())\n # print(f\"Thread 3 stopped\")\n\n\nth1 = Thread(target=thread_1)\nth2 = Thread(target=thread_2)\nth3 = Thread(target=thread_3)\n\n# starting the thread 1 and thread 3\nth1.start()\nth3.start()\nth1.join(timeout=20)\nstop_event.set()\n\n# starting thread 2 after 20 secs\nth2.start()\nth3.join(timeout=18)\nstop_event.set()\nth3.join()\nth1 = Thread(target=thread_1)\nth1.start()","sub_path":"assignment/mutithreading.py","file_name":"mutithreading.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"385882501","text":"from keras.datasets import fashion_mnist\n\nimport numpy as np\nfrom keras.utils import to_categorical\nimport matplotlib.pyplot as plt\n\nimport os\nos.environ['TF_CPP_LOG_LEVEL']='5'\n\n\n# Load fashion mnist data\n(train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data()\nprint('Training data shape : ', train_X.shape, train_Y.shape)\nprint('Testing data shape : ', test_X.shape, test_Y.shape)\n\n# Find the unique numbers from the train labels\nclasses = np.unique(train_Y)\nnClasses = len(classes)\nprint('Total number of outputs : ', nClasses)\nprint('Output classes : ', classes)\n\n# Draw example with matplotlib\nplt.figure(figsize=[5,5])\n\nplt.subplot(121)\nplt.imshow(train_X[0,:,:], cmap='gray')\nplt.title(\"Ground Truth : {}\".format(train_Y[0]))\n\nplt.subplot(122)\nplt.imshow(test_X[0,:,:], cmap='gray')\nplt.title(\"Ground Truth : {}\".format(test_Y[0]))\n\nplt.savefig('fig_1.png')\n#plt.show()\n\n\n# Convert example to [img_num, row, col, color_ch]\ntrain_X = train_X.reshape(-1, 28,28, 1)\ntest_X = test_X.reshape(-1, 28,28, 1)\ntrain_X.shape, test_X.shape\n\n# Convert example from uint8 to float32\ntrain_X = train_X.astype('float32')\ntest_X = test_X.astype('float32')\n\n# Rescale example from 0-255 to 0-1\ntrain_X = train_X / 255.\ntest_X = test_X / 255.\ntrain_X_bk = train_X\n\n\n# Convert label to 1-hot vector\ntrain_Y_1h = to_categorical(train_Y)\ntest_Y_1h = to_categorical(test_Y)\nprint('Original label:', train_Y[0])\nprint('After conversion to one-hot:', train_Y_1h[0])\n\n\n# Split training data to 80% train, 20% test\n# Input : 28x28x1\n# 1st_stage: Conv2D 32 nodes output, kernel 3x3\n# LeakyReLU\n# MaxPooling2D\n# 2nd_stage: Conv2D 64 nodes output, kernel 3x3\n# LeakyReLU\n# MaxPooling2D\n# 3rd_stage: Conv2D 128 nodes output, kernel 3x3\n# LeakyReLU\n# MaxPooling2D\n# Flatten : convert data to array\n# Dense : neural layer 128 nodes output\n# LeakyReLU: activation function\n# Dense : neural layer 10 nodes output with softmax\n\nfrom sklearn.model_selection import train_test_split\n\ntrain_X,valid_X,train_label,valid_label = train_test_split(train_X, train_Y_1h, test_size=0.1, train_size=0.2, random_state=13)\n\n# Build training model with keras\nimport keras\nfrom keras.models import Sequential,Input,Model,load_model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tqdm import tqdm\nfrom keras.optimizers import SGD\n\nbatch_size = 64\nepochs = 20\nnum_classes = 10\n\n\nmodel = Sequential()\n#model.add(Conv2D(32, kernel_size=(3,3), activation='linear', padding='same', input_shape=(28,28,1)))\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2), padding='same'))\n#model.add(Dropout(0.25))\n#model.add(Conv2D(64, (3,3), activation='linear', padding='same'))\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2),padding='same'))\n#model.add(Dropout(0.25))\n#model.add(Conv2D(128,(3,3),activation='linear',padding='same'))\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2),padding='same'))\n#model.add(Dropout(0.4))\n#model.add(Flatten())\n#model.add(Dense(128,activation='linear'))\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Dropout(0.3))\n#model.add(Dense(num_classes, activation='softmax'))\n\nmodel.add(Conv2D(32, kernel_size=(3,3), activation='linear', padding='same', input_shape=(28,28,1)))\nmodel.add(LeakyReLU(alpha=0.1))\nmodel.add(MaxPooling2D((2,2), padding='same'))\nmodel.add(Conv2D(64, (3,3), activation='linear', padding='same'))\nmodel.add(LeakyReLU(alpha=0.1))\nmodel.add(MaxPooling2D((2,2),padding='same'))\nmodel.add(Conv2D(128,(3,3),activation='linear',padding='same'))\nmodel.add(LeakyReLU(alpha=0.1))\nmodel.add(MaxPooling2D((2,2),padding='same'))\nmodel.add(Conv2D(128,(3,3),activation='linear',padding='same'))\nmodel.add(LeakyReLU(alpha=0.1))\nmodel.add(MaxPooling2D((2,2),padding='same'))\nmodel.add(Flatten())\nmodel.add(Dense(4096,activation='linear'))\nmodel.add(LeakyReLU(alpha=0.1))\nmodel.add(Dense(4096,activation='linear'))\nmodel.add(LeakyReLU(alpha=0.1))\nmodel.add(Dense(num_classes, activation='softmax'))\n\n\n## VGG16\n#model.add(Conv2D(64, kernel_size=(3,3), activation='linear', padding='same', input_shape=(28,28,1)))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(64, (3,3), activation='linear', padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2), padding='same'))\n##model.add(Dropout(0.25))\n#\n#model.add(Conv2D(128, (3,3), activation='linear', padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(128, (3,3), activation='linear', padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2),padding='same'))\n##model.add(Dropout(0.25))\n#\n#model.add(Conv2D(256,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(256,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(256,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2),padding='same'))\n##model.add(Dropout(0.25))\n#\n#model.add(Conv2D(512,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(512,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(512,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2),padding='same'))\n##model.add(Dropout(0.25))\n#\n#model.add(Conv2D(512,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(512,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(Conv2D(512,(3,3),activation='linear',padding='same'))\n##model.add(BatchNormalization())\n#model.add(LeakyReLU(alpha=0.1))\n#model.add(MaxPooling2D((2,2),padding='same'))\n##model.add(Dropout(0.25))\n#\n#model.add(Flatten())\n#model.add(Dense(4096,activation='linear'))\n#model.add(LeakyReLU(alpha=0.1))\n##model.add(Dropout(0.3))\n#model.add(Dense(4096,activation='linear'))\n#model.add(LeakyReLU(alpha=0.1))\n##model.add(Dropout(0.3))\n#model.add(Dense(num_classes, activation='softmax'))\n\n\n# Chọn loss function, giải thuật optimize, độ đo hội tụ\nsgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd,metrics=['accuracy'])\n\n## In ra thông số model\n#model.summary()\n\n#del model\n#model = load_model('fashion_mnist.h5')\n#\n#datagen = ImageDataGenerator(\n# featurewise_center=True,\n# featurewise_std_normalization=True,\n# rotation_range=20,\n# width_shift_range=0.2,\n# height_shift_range=0.2,\n# horizontal_flip=True)\n# \n#datagen.fit(train_X)\n\n#train = model.fit_generator(datagen.flow(train_X, train_label, batch_size=batch_size), epochs=epochs,verbose=1,validation_data=(valid_X, valid_label))\n \n\n# Train model với data train, mỗi batch 16 ex, 20 epochs và data CV\ntrain = model.fit(train_X, train_label, batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label))\n\n#train = model.fit_generator(datagen.flow(train_X, train_label), batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label))\n\nmodel.save('fashion_mnist.h5')\n\n# Eval model\ntest_eval = model.evaluate(test_X, test_Y_1h, verbose=1)\nprint('Test loss:', test_eval[0])\nprint('Test accuracy:', test_eval[1])\n\ntest_eval = model.evaluate(train_X_bk, train_Y_1h, verbose=1)\nprint('Train loss:', test_eval[0])\nprint('Train accuracy:', test_eval[1])\n\n\n\n\n\n\n\n\n\n\n","sub_path":"vgg16.py","file_name":"vgg16.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"424852882","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nfrom zope.viewlet import viewlet\nfrom zope.app.pagetemplate import ViewPageTemplateFile\nfrom zope.security.proxy import removeSecurityProxy\n\nfrom bungeni.ui.i18n import _\nimport bungeni.ui.utils as ui_utils\n\nclass LibraryViewlet (viewlet.ViewletBase):\n render = ViewPageTemplateFile ('templates/attached-files.pt')\n form_name = _(u\"attached files\")\n for_display = True\n def __init__( self, context, request, view, manager ):\n trusted = removeSecurityProxy(context)\n self.context = trusted.attached_files\n self.request = request\n self.__parent__= context\n self.manager = manager\n self.query = None\n self.for_display = len(self.context) > 0\n\n def results(self):\n return self.context\n \nclass VersionLibraryViewlet(LibraryViewlet):\n render = ViewPageTemplateFile ('templates/version-attached-files.pt')\n def results(self):\n rl = []\n rd = {}\n url = ui_utils.url.absoluteURL(\n self.__parent__.__parent__.__parent__, self.request)\n for result in self.context:\n rd[\"file_title\"] = result.file_title\n rd[\"url\"] = url + \"/files/obj-%i/versions/obj-%i\" % (result.content_id,\n result.version_id)\n rd[\"file_name\"] = result.file_name\n rd[\"file_mimetype\"] = result.file_mimetype\n rl.append(rd)\n rd= {}\n return rl\n","sub_path":"bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/forms/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"510151178","text":"# импортируем нужные библиотеки\r\n\r\nfrom transformers import BertTokenizer, BertForSequenceClassification\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom transformers import AdamW, get_linear_schedule_with_warmup\r\nfrom torch.utils.data import Dataset\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport json\r\n\r\n\r\nclass BertClassifier:\r\n \"\"\" класс для инициализации и получения предсказаний дообученной ruBert модели \"\"\"\r\n def __init__(self, model_path):\r\n \"\"\"\r\n model_path: путь до весов предобученной модели;\r\n \"\"\"\r\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n if torch.cuda.is_available():\r\n self.model = torch.load(model_path)\r\n else:\r\n self.model = torch.load(model_path, map_location=\"cpu\")\r\n\r\n self.tokenizer = BertTokenizer.from_pretrained('cointegrated/rubert-tiny')\r\n self.max_len = 512\r\n self.class_decoder = {0: \"спорт\", 1: \"музыка\", 2: \"литература\", 3: \"животные\"}\r\n \r\n def predict(self, text: str) -> int:\r\n \"\"\" \r\n метод для получения предсказания модели на тексте\r\n Принимает на вход: str, текст;\r\n Возвращает: str, предсказанный класс.\r\n \"\"\"\r\n text = \" \".join(text.split(\" \")[:min(len(text), 513)]) # обрежим текст до первых 512 слов\r\n encoding = self.tokenizer.encode_plus(\r\n text,\r\n add_special_tokens=True,\r\n max_length=self.max_len,\r\n return_token_type_ids=False,\r\n truncation=True,\r\n padding='max_length',\r\n return_attention_mask=True,\r\n return_tensors='pt',\r\n )\r\n \r\n out = {\r\n 'text': text,\r\n 'input_ids': encoding['input_ids'].flatten(),\r\n 'attention_mask': encoding['attention_mask'].flatten()\r\n }\r\n \r\n input_ids = out[\"input_ids\"].to(self.device)\r\n attention_mask = out[\"attention_mask\"].to(self.device)\r\n \r\n outputs = self.model(\r\n input_ids=input_ids.unsqueeze(0),\r\n attention_mask=attention_mask.unsqueeze(0)\r\n )\r\n\r\n accuracy = torch.nn.functional.softmax(outputs.logits, dim=1).max().item()\r\n prediction = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]\r\n\r\n return self.class_decoder[prediction], accuracy\r\n","sub_path":"classify_theme.py","file_name":"classify_theme.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"336938711","text":"import serial, time, re\nimport game_state\n\n\nrgx_index = re.compile('\\\\+CMTI.*,([0-9]+)')\nrgx_defuse = re.compile(\"defuse\", re.I)\n\nport = serial.Serial(\"/dev/serial0\", baudrate=115000, timeout=10.0)\nenter = b\"\\n\"\n\ndef sms_reader():\n port.write(b\"AT+CPIN=2401\" + enter)\n time.sleep(0.3)\n if port.read(10).decode(\"utf-8\") == \"ERROR\":\n raise ValueError(\"CAN'T ENTER PIN\")\n\n # Disable Echo\n port.write(b'ATE0' + enter)\n time.sleep(0.3)\n\n # clear any misleading bytes in the buffer\n port.reset_output_buffer()\n\n while not game_state.sms_done:\n event = port.read(100)\n # port outputs bytes, regex needs string, commands need bytes\n event = event.decode(\"utf-8\")\n #print(event)\n match_object = rgx_index.search(event)\n if match_object is not None:\n sms_index = match_object.group(1)\n sms_index = str.encode(sms_index)\n print(sms_index)\n receive_message(sms_index)\n time.sleep(0.1)\n return True\n\ndef receive_message(sms_index):\n # text mode\n port.write(b\"AT+CMGF=1\" + enter)\n time.sleep(0.3)\n # read sms at index\n port.write(b\"AT+CMGR=\" + sms_index + enter)\n time.sleep(0.3)\n sms = port.read(1000)\n sms = sms.decode(\"utf-8\")\n #print(sms)\n match_object = rgx_defuse.search(sms)\n\n if match_object is not None:\n game_state.sms_done = True\n else:\n game_state.strike()\n","sub_path":"sms_reader.py","file_name":"sms_reader.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"486313038","text":"## put your questions & messages here and any pertinent comments\n\nauto_seed_warning = \"## !! DO NOT CHANGE THIS FILE UNLESS YOU KNOW SPECIFICALLY WHAT YOU ARE DOING !!\\n \\\n## Changes should be made in user seed only !!\"\n\nbase_sys_msg = \"Choose from these available systems.\\n\\\nThese are the only supported systems at this time.\"\n\nbase_type_msg = \"Choose the source of the new live-media iso file.\\n\\\n*(Currently not working)\"\n\nbase_type_list = [\"Backup: use an already installed system, back it up to live mdiea.\",\\\n\"ISO : Use an existing iso file.\",\\\n\"Custom: Bootstrap a new custom system to chroot into.\"]\n## splitting these to coordinate with seed files\nbackup_list = [\"from Backup : Use an already installed system, back it up to live media.\"]\niso_list = [\"*from ISO : Use an existing iso file.\"]\ncustom_list = [\"*from Bootstrap: Install a new custom system to chroot into.\"]\n\ncreate_new_dir_msg = \"PyneCone needs to make some directories.\\n \\\nProceed to create directory %s?\"\n\ndebian_type = \"Would you like [S]table, [T]esting, or [X]unstable base?\"\n\nlevel_list = ['Existing: Use a pre-configured build file (usually auto_seed).', \\\n'New : Create a new build file manually.']\n\nlevel_msg = 'Choose to use Existing to use a pre-configured automatic seed file\\n \\\nor New to proceed with live-media creation.'\n\nmode_msg = \"Choose Wizard if this is your first run or\\n \\\nExpert to go straight to rsync, chroot, or build-iso. \" + \"*(Currently not working)\"\n\nmode_list = [\"Wizard mode: Q & A\", \\\n\"*Expert mode: If you already have a base and need to make adjustments.\"]\n\nmount_msg = \"PyneCone needs to mount file systems before chroot.\\n \\\nProceed?\"\n\nnot_working_msg = \"(Currently not working)\"\n\nnew_auto_seed_msg = \"PyneCone did not detect an auto-seed file.\\n\\\nThis is ok, the auso-seed will be created while running the Wizard.\\n\\\n(Auto-seed creation is not working at this time, this is a placeholder.\\n\\\nProceed?\"\n\npython_ver = \"PyneCone requires Python 3.0 or greater, exiting!\"\n\nquit_help_list = ['Help', 'Quit']\n\nroot_msg = \"You need to be root or have root privilages to run PyneCone!\"\n\nsource_paks_msg = \"PyneCone needs to check your system for required software and install what is needed.\\n \\\nProceed?\"\n\nstart_rsync_msg = \"PyneCone is now ready to backup your system.\\n \\\nProceed?\"\n\nuser_source_system = \"What system are you running PyneCone in now?\\n\\n\"\n\nos_probe_fail = \"You indicated your system wasn't %s.\"\n\nwelcome_msg = \"Welcome to PyneCone\\n \\\n\\n Type the number next to your choice.\"\n\nwhich_system = \"PyneCone has determined that your source system is %s .\\n \\\nIs this correct?\"\n\nwhich_user_msg = \"Choose which users settings to keep, or 'None'\"\n\nyes_no_list = ['Yes', 'No']\n\n## help for user, 'How do I' 'which do I choose'\nlevel_help = \"\"\n","sub_path":"pyconeQ.py","file_name":"pyconeQ.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"34650703","text":"#!/usr/bin/env python3\n'''Animates distances and measurment quality'''\nfrom rplidar import RPLidar\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.animation as animation\nimport RPi.GPIO as GPIO\nimport time\n\nimport pygame\nfrom freenect import sync_get_depth as get_depth\nimport numpy as np\nimport sys\nimport cv2\n\n#setup for importing data from kinect\n\npath = 12\nPORT_NAME = '/dev/ttyUSB0'\nDMAX = 4000\nIMIN = 0\nIMAX = 50\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\nGPIO.setup(path, GPIO.OUT)\npwm = GPIO.PWM(path, 50)\nincrement = 5\n\ndef make_gamma():\n \"\"\"\n Create a gamma table\n \"\"\"\n num_pix =2048 # there's 2048 different possible depth values\n npf = float(num_pix)\n _gamma = np.empty((num_pix, 3), dtype=np.uint16)\n for i in range(num_pix):\n v = i / npf\n v = pow(v, 3) * 6\n pval = int(v * 6 * 256)\n lb = pval & 0xff\n pval >>= 8\n if pval == 0:\n a = np.array([255, 255 - lb, 255 - lb], dtype=np.uint8)\n elif pval == 1:\n a = np.array([255, lb, 0], dtype=np.uint8)\n elif pval == 2:\n a = np.array([255 - lb, lb, 0], dtype=np.uint8)\n elif pval == 3:\n a = np.array([255 - lb, 255, 0], dtype=np.uint8)\n elif pval == 4:\n a = np.array([0, 255 - lb, 255], dtype=np.uint8)\n elif pval == 5:\n a = np.array([0, 0, 255 - lb], dtype=np.uint8)\n else:\n a = np.array([0, 0, 0], dtype=np.uint8)\n\n _gamma[i] = a\n return _gamma\n\n\ngamma = make_gamma()\n\ndef findMaxDist(depth):\n depth[depth == 2047] = 0\n dst = cv2.GaussianBlur(depth, (11,11), 0)\n val = np.amax(dst)\n\n #print(\"Max X Coord: \", int(np.mean(np.where(dst == val)[0])))\n #print(\"var X Coord: \", int(np.sqrt(np.var(np.where(dst > (val-50))[0]))))\n\n #print(\"val at that place\", depth[int(np.mean(np.where(dst == val)[0]))][np.where(dst == val)[1][0]])\n\n return int(np.mean(np.where(dst==val)[0])),int(np.sqrt(np.var(np.where(dst == val)[0])))\n\ndef pwmDir(x):\n # 58.5 x 46.6 degrees field of view\n # about 5 x 5 pixels per degree\n # when heading is the same as maxAngle, dc = 50%\n # 640 x 480 pixels\n \n # kinect will only send out ~42 pwm to 58 pwm\n # left is greater than 50, right is less than 50\n # convert std of index to angle\n #print('kinect std: ', x[1])\n kinCert = x[1]/640 * 58.5\n dc = (x[0] / 640) * 17/2 + 50\n #print ('kinect dc: ', dc)\n #print ('kin Cert: ', kinCert)\n return dc, kinCert\n\ndef update_line(num, iterator, line):\n scan = next(iterator)\n offsets = np.array([(np.radians(meas[1]), meas[2]) for meas in scan])\n line.set_offsets(offsets)\n intens = np.array([meas[0] for meas in scan])\n line.set_array(intens)\n return line,\n\ndef led(maxAngle, rollAvg, maxDist, kinpwm, findMaxDist):\n # when heading is the same as maxAngle, dc = 50%\n #cerfact = std/size of array * 360\n lidstd = int(np.sqrt(np.var(np.where(rollAvg > (maxDist - 50)))))\n lidCert = lidstd/len(rollAvg) * 360\n liddc = (maxAngle / 360) * 100\n\n kinstd = findMaxDist[1]\n kinCert = kinpwm[1]\n kindc = kinpwm[0]\n\n print('kin std: ', kinstd)\n print ('kin Cert: ', kinCert)\n print ('kin dc: ', kindc)\n \n print('lid std: ', lidstd)\n print ('lidar Cert: ', lidCert)\n print ('lidar dc: ', liddc)\n\n if(kinCert*10 > lidCert):\n pwm.ChangeDutyCycle(kindc)\n print('output kindc: ', kindc)\n else:\n pwm.ChangeDutyCycle(liddc)\n print('output liddc: ', liddc)\n \ndef obstacle(obDist, obAngle):\n if(obAngle <= 180):\n print (\"obstacle to right\")\n else:\n print (\"obstacle to left\")\n \ndef run():\n lidar = RPLidar(PORT_NAME)\n while(True):\n iterator = lidar.iter_scans(max_buf_meas=4000)\n scan = next(iterator)\n # clockwise rotation\n while(scan):\n # rolling average to find the most open space\n maxDist = -1\n maxAngle = -1\n minDist = 500\n minAngle = 500\n avg = 0\n avgAngle = 0\n multA = 10 \n multB = 1\n rollAvg = np.array([])\n \n # average the first 10 samples \n for i in range(increment):\n avg += scan[i][2]\n avgAngle += scan[i][1]\n avg /= increment\n avgAngle /= increment\n\n rollAvg = np.append(rollAvg, avg)\n\n for i in range(increment, len(scan)):\n avg = ((avg * multA) + (scan[i][2] * multB)) / (multA + multB)\n avgAngle = ((avgAngle * multA) + (scan[i][1] * multB)) / (multA + multB)\n rollAvg = np.append(rollAvg, avg)\n if(avg > maxDist):\n maxDist = avg\n maxAngle = avgAngle\n if(avg < minDist):\n minAngle = avgAngle\n\n depth = np.rot90(get_depth()[0]) # get the depth readinngs from the camera\n #pwmDir(findMaxDist(depth))\n print('maxDist: ', maxDist, \" maxAngle: \", maxAngle)\n #print('minDist: ', minDist, \" minAngle: \", minAngle)\n led(maxAngle, rollAvg, maxDist, pwmDir(findMaxDist(depth)), findMaxDist(depth))\n #obstacle(minDist, minAngle)\n scan = next(iterator)\n lidar.stop()\n lidar.disconnect()\n\nif __name__ == '__main__':\n try: \n dc = 50\n pwm.start(dc)\n run()\n except KeyboardInterrupt: # IF CTRL+C is pressed, exit cleanly:\n print('quitting')\n finally:\n GPIO.cleanup() # Clean up GPIO\n \n","sub_path":"examples/scandata.py","file_name":"scandata.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"589377943","text":"import math\nimport numpy as np\nimport random\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nfrom collections import OrderedDict\n\nmap_width = 100\nmap_height = 100\ndiagonal = map_height * math.sqrt(2)\nnum_aircraft = 1 # How many aircrafts showing up in the map (list length)\nn_closest = 0\nrwy_degree = 0\nrwy_degree_sigma = math.radians(45)\n\nscale = 60 # 1 pixel = 30 meters\nmin_speed = 80/scale\nmax_speed = 350/scale\nspeed_sigma = 0/scale\nd_speed = 5/scale\nd_heading = math.radians(5)\nheading_sigma = math.radians(0)\n\ngoal_radius = 3 # larger will get more goals, small value: agent lands accurately\ntime_interval_lower = 60\ntime_interval_upper = 120\nconflict_coeff = 0.005\nminimum_separation = 4\nNMAC_dist = 150/scale\n\n\nclass AirTrafficGym(gym.Env):\n\n def __init__(self, seed):\n self.airport = Airport(position = np.array([50., 50.]))\n self.own_state_size = 8\n self.int_state_size = 0\n self.observation_space = (self.own_state_size + n_closest * self.int_state_size,)\n self.position_range = spaces.Box(low=np.array([0, 0]),\n high=np.array([map_width, map_height]),\n dtype=np.float32)\n # discrete action space: -1, 0, 1\n self.action_space = spaces.Discrete(3)\n\n # continuous action space: [-1, 1]\n # spaces.Box(low=-1, high=1, shape=(2,), dtype=np.float)\n\n self.conflicts = 0\n np.random.seed(seed)\n self.np_random, seed = seeding.np_random(seed)\n\n def reset(self):\n self.aircraft_dict = AC_ActionDict()\n self.id_tracker = 0\n self.conflicts = 0\n self.goals = 0\n self.NMACs = 0\n return self._get_obs()\n\n def _get_obs(self):\n s = []\n id = []\n for key, aircraft in self.aircraft_dict.ac_dict.items():\n # if self.aircraft_dict.ac_dict.items is empty (after reset()), this for loop will not be implemented\n own_s = []\n own_s.append(aircraft.position[0]/ map_width)\n own_s.append(aircraft.position[1]/ map_height)\n own_s.append((aircraft.speed - min_speed) / (max_speed - min_speed))\n own_s.append(aircraft.heading/ (2 * math.pi))\n own_s.append((0.5 * NMAC_dist)/ diagonal)\n own_s.append(self.airport.position[0]/ map_width)\n own_s.append(self.airport.position[1]/ map_height)\n own_s.append(aircraft.prev_a)\n\n # dist_array, id_array = self.dist_to_all_aircraft(aircraft)\n # closest_ac = np.argsort(dist_array)\n '''\n for j in range(n_closest):\n try:\n aircraft = self.aircraft_dict.ac_dict[id_array[closest_ac[j]]]\n own_s.append(aircraft.position[0]/ map_width)\n own_s.append(aircraft.position[1]/ map_height)\n own_s.append((aircraft.speed - min_speed) / (max_speed - min_speed))\n own_s.append(aircraft.heading/ (2 * math.pi))\n own_s.append(dist_array[closest_ac[j]]/ diagonal)\n own_s.append((0.5 * NMAC_dist)/ diagonal)\n own_s.append(NMAC_dist/ diagonal)\n own_s.append(aircraft.prev_a)\n\n except:\n for k in range(self.int_state_size):\n own_s.append(0)\n\n '''\n s.append(own_s)\n id.append(key)\n return np.reshape(s, (len(s), self.own_state_size+self.int_state_size* n_closest)), id\n\n def step(self, a, last_ob):\n for id, aircraft in self.aircraft_dict.ac_dict.items():\n try:\n aircraft.step(a[id]) # Will not implement when aircraft_dict is empty\n except:\n pass\n\n self.airport.step()\n '''\n dist_array, id_array = self.dist_to_all_aircraft(aircraft) # will return empty list when aircraft_dict is empty\n min_dist = min(dist_array) if dist_array.shape[0] > 0 else 9999\n if min_dist > 3 * minimum_separation and self.aircraft_dict.num_aircraft < num_aircraft:\n self.aircraft_dict.add(aircraft)\n self.id_tracker += 1\n\n self.airport.generate_interval()\n '''\n if self.aircraft_dict.num_aircraft < num_aircraft:\n aircraft = Aircraft(id = self.id_tracker,\n position = self.random_pos(),\n speed = self.random_speed(),\n heading = self.random_heading(),\n goal_pos = self.airport.position)\n self.aircraft_dict.add(aircraft)\n self.id_tracker += 1\n self.airport.generate_interval()\n\n\n reward, terminal, info = self._terminal_reward()\n obs = self._get_obs()\n\n return obs, reward, terminal, info\n\n def _terminal_reward(self):\n reward = {}\n dones = {}\n info = {}\n info_dist_list = []\n aircraft_to_remove = []\n for id, aircraft in self.aircraft_dict.ac_dict.items():\n dist_array, id_array = self.dist_to_all_aircraft(aircraft)\n min_dist = min(dist_array) if dist_array.shape[0] > 0 else 9999\n dist_goal = self.dist_2pt(aircraft.position, self.airport.position)\n aircraft.reward = 0\n conflict = False\n aircraft.lifespan -= 1\n\n # Conflict: aircraft will NOT be removed\n for id_, dist in zip(id_array, dist_array):\n if dist >= minimum_separation:\n aircraft.conflict_id_set.discard(id_)\n else: # conflict!!\n conflict = True\n if id_ not in aircraft.conflict_id_set:\n self.conflicts += 1\n aircraft.conflict_id_set.add(id_)\n if dist == min_dist:\n aircraft.reward = -0.1 + conflict_coeff * dist\n\n # NMAC: remove\n if min_dist < NMAC_dist:\n aircraft.reward = -1\n aircraft_to_remove.append(aircraft)\n dones[id] = True\n info[id] = 'n'\n self.NMACs += 1\n\n # Out of map: remove\n elif not self.position_range.contains(np.array(aircraft.position)):\n aircraft.reward = -1\n if aircraft not in aircraft_to_remove:\n aircraft_to_remove.append(aircraft)\n dones[id] = True\n info[id] = 'w'\n\n # Goal: remove\n elif (dist_goal < goal_radius) and (self.airport.clock_counter <= self.airport.time_next_aircraft) \\\n and (((aircraft.heading >= rwy_degree - rwy_degree_sigma) & (aircraft.heading <= rwy_degree + rwy_degree_sigma)) \\\n or((aircraft.heading >= rwy_degree + math.radians(180) - rwy_degree_sigma) & (aircraft.heading <= rwy_degree + math.radians(180)+ rwy_degree_sigma))):\n aircraft.reward = 1\n self.goals += 1\n if aircraft not in aircraft_to_remove:\n dones[id] = True\n aircraft_to_remove.append(aircraft)\n info[id] = 'g'\n\n elif aircraft.lifespan == 0:\n aircraft.reward = -1\n aircraft_to_remove.append(aircraft)\n dones[id] = True\n info[id] = 'f'\n # Taking more steps to land has penalty\n elif not conflict:\n aircraft.reward = -0.001\n\n reward[id] = aircraft.reward\n if aircraft not in aircraft_to_remove:\n dones[id] = False\n info[id] = 't'\n\n for aircraft in aircraft_to_remove:\n self.aircraft_dict.remove(aircraft)\n\n return reward, dones, info\n\n def dist_to_all_aircraft(self, aircraft):\n id_list = []\n dist_list = []\n for id, intruder in self.aircraft_dict.ac_dict.items():\n if id != aircraft.id:\n id_list.append(id)\n dist_list.append(self.dist_2pt(aircraft.position, intruder.position))\n return np.array(dist_list), np.array(id_list)\n\n def dist_2pt(self, pos1, pos2):\n dx = pos1[0] - pos2[0]\n dy = pos1[1] - pos2[1]\n return math.sqrt(dx ** 2 + dy ** 2)\n\n def random_pos(self):\n return np.random.uniform(low=np.array([0, 0]), high=np.array([map_width, map_height]))\n\n def random_speed(self):\n return np.random.uniform(low = min_speed, high = max_speed)\n\n def random_heading(self):\n return np.random.uniform(low=0, high=2 * math.pi)\n\n def build_observation_space(self):\n s = spaces.Dict({\n 'pos_x': spaces.Box(low=0, high = map_width, shape=(1,), dtype=np.float32),\n 'pos_y': spaces.Box(low=0, high = map_height, shape=(1,), dtype=np.float32),\n 'vel_x': spaces.Box(low = -max_speed, high = max_speed, shape=(1,), dtype=np.float32),\n 'vel_y': spaces.Box(low = -max_speed, high = max_speed, shape=(1,), dtype=np.float32),\n 'speed': spaces.Box(low = min_speed, high = max_speed, shape=(1,), dtype=np.float32),\n 'heading': spaces.Box(low=0, high=2 * math.pi, shape=(1,), dtype=np.float32),\n 'goal_x': spaces.Box(low=0, high = map_width, shape=(1,), dtype=np.float32),\n 'goal_y': spaces.Box(low=0, high = map_height, shape=(1,), dtype=np.float32),\n })\n\n return spaces.Tuple((s,) * num_aircraft)\n\nclass AC_ActionDict:\n def __init__(self):\n self.ac_dict = OrderedDict()\n\n @property\n def num_aircraft(self):\n return len(self.ac_dict)\n\n def add(self, aircraft):\n self.ac_dict[aircraft.id] = aircraft\n\n def remove(self, aircraft):\n try:\n del self.ac_dict[aircraft.id]\n except KeyError:\n pass\n\n def get_aircraft_by_id(self, aircraft_id):\n return self.ac_dict[aircraft_id]\n\n\nclass AircraftList:\n def __init__(self):\n self.ac_list = []\n self.id_list = []\n\n @property\n def num_aircraft(self):\n return len(self.ac_list)\n\n def add(self, aircraft):\n self.ac_list.append(aircraft)\n self.id_list.append(aircraft.id)\n unique, count = np.unique(np.array(self.id_list), return_counts=True)\n\n def remove(self, aircraft):\n try:\n self.ac_list.remove(aircraft)\n self.id_list.remove(aircraft.id)\n except ValueError:\n pass\n\n def get_aircraft_by_id(self, aircraft_id):\n index = np.where(np.array(self.id_list) == aircraft_id)[0]\n return self.ac_list[int(index)]\n\n for aircraft in self.buffer_list:\n if aircraft.id == aircraft_id:\n return aircraft\n\n\nclass Aircraft:\n def __init__(self, id, position, speed, heading, goal_pos):\n self.id = id\n self.position = np.array(position, dtype=np.float32)\n self.speed = speed\n self.heading = heading # rad\n vx = self.speed * math.cos(self.heading)\n vy = self.speed * math.sin(self.heading)\n self.velocity = np.array([vx, vy], dtype=np.float32)\n\n self.prev_a = 0\n # self.prev_a = np.array([0, 0])\n self.reward = 0\n dx, dy = goal_pos - self.position\n self.heading = math.atan2(dy, dx)\n\n self.conflict_id_set = set()\n self.lifespan = 1000\n\n def step(self, a):\n # self.speed += d_speed * a[1]\n self.speed = max(min_speed, min(self.speed, max_speed))\n self.speed += np.random.normal(0, speed_sigma)\n\n self.heading += d_heading * a\n # self.heading += d_heading * a[0]\n self.heading += np.random.normal(0, heading_sigma)\n\n vx = self.speed * math.cos(self.heading)\n vy = self.speed * math.sin(self.heading)\n self.velocity = np.array([vx, vy])\n self.position += self.velocity\n self.prev_a = a\n\nclass Airport:\n def __init__(self, position):\n self.position = np.array(position)\n self.clock_counter = 0\n self.time_next_aircraft = np.random.uniform(0, 60)\n\n def generate_interval(self):\n self.time_next_aircraft = np.random.uniform(time_interval_lower, time_interval_upper)\n self.clock_counter = 0\n\n def step(self):\n self.clock_counter += 1\n","sub_path":"multi_env.py","file_name":"multi_env.py","file_ext":"py","file_size_in_byte":12359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"654139362","text":"from __future__ import unicode_literals\nimport codecs\nimport sys\nimport json\nimport os\nimport xml.etree.ElementTree as ET\nimport re\nimport requests\nfrom requests_oauthlib.oauth1_auth import OAuth1\nimport time\nimport datetime\nimport math\nimport indicoio\n\nsys.path.insert(0, os.path.abspath('..'))\n\n############################################### BEGIN OF CRAWLER ###############################################\n\nREQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\nAUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize\"\nACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n\nCONSUMER_KEY = \"zfbpBDWaCP928z48JybTnw\"\nCONSUMER_SECRET = \"iWZbH0lRqabem9soA0nR76eMe4cwVOfUSm8DcjP2uiY\"\n\nOAUTH_TOKEN = \"72264591-NROFktZG6uXQoCXELYDTLdWNVCaMlsAizJdJubOau\"\nOAUTH_TOKEN_SECRET = \"SdslnFRiDai0vFYQoIPm8GQIzpF070CnMvdozTZdcMkho\"\n\ndef get_oauth():\n oauth = OAuth1(CONSUMER_KEY,client_secret=CONSUMER_SECRET,resource_owner_key=OAUTH_TOKEN,resource_owner_secret=OAUTH_TOKEN_SECRET)\n return oauth\n\n###############################################\ndef serialize_json_list(json_list, tagname, tabs=1):\n # opening tag with possible attributes\n output = \" \"*tabs + \"<\" + tagname + \">\\n\"\n \n # child nodes\n key = 'item'\n for value in json_list:\n if isinstance(value, list):\n output += serialize_json_list(value, key, tabs=tabs+1)\n elif isinstance(value, dict):\n output += serialize_json_dict(value, key, tabs=tabs+1)\n else:\n output += serialize_json_attr(value, key, tabs=tabs+1)\n \n # closing tag\n output += \" \"*tabs + \"\\n\"\n return output\n\ndef serialize_json_dict(json_dict, tagname, attributes={}, tabs=1):\n # opening tag with possible attributes\n output = \" \"*tabs + \"<\" + tagname \n output += \" \" if len(attributes) > 0 else \"\"\n output += \" \".join(key + '=\"' + str(value) + '\"' for (key, value) in attributes.items()) \n output += \">\\n\"\n \n # child nodes\n for key, value in json_dict.items():\n \n if isinstance(value, list):\n output += serialize_json_list(value, key, tabs=tabs+1)\n elif isinstance(value, dict):\n output += serialize_json_dict(value, key, tabs=tabs+1)\n else:\n output += serialize_json_attr(value, key, tabs=tabs+1)\n \n # closing tag\n output += \" \"*tabs + \"\\n\"\n return output\n\ndef serialize_json_attr(json_attr, tagname, tabs=1):\n output = \" \"*tabs + \"<\" + tagname + \">\" + str(json_attr) + \"\\n\" \n return output\n\ndef get_xml_from_json(json_data):\n output = \"\\n\"\n for ix, tweet in enumerate(json_data):\n output += serialize_json_dict(tweet, \"tweet\", {\"number\": ix+1})\n output += \"\\n\"\n return output\n###############################################\n\nif __name__ == \"__main__\":\n oauth = get_oauth() \n url = \"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=moerafaat&count=4\" \n r = requests.get(url, auth=oauth)\n result = r.json()\n \n with codecs.open(\"res.json\",'w','utf-8') as f:\n f.write(json.dumps(result))\n xml=get_xml_from_json(result)\n with codecs.open(\"result.xml\",'w','utf-8') as f: \n f.write(xml)\n\n filtered=codecs.open(\"fresult.xml\",'w','utf8') # new file to write xml without letter '&'.\n \n f=codecs.open(\"result.xml\", 'r', 'utf-8')\n r=f.readlines()\n \n for line in r:\n l= [item for item in re.split('&',line) if item] # to remove the character '&' as it raises an error when parsing xml file.\n for word in l:\n filtered.write(word +\" \")\n \n filtered.close()\n fi=codecs.open(\"fresult.xml\",'r')\n file1 = codecs.open(\"tweets.txt\",'w','utf8')\n tree = ET.parse(fi)\n root = tree.getroot()\n \n for tweet in root.findall('tweet'):\n data=tweet.find('text').text\n f2 = data.split()\n for line in f2:\n cleanedline=line.strip() # to remove empty lines inside tweets text.\n if cleanedline:\n file1.write(cleanedline)\n file1.write(\" \")\n file1.write(\"\\n\") \n data= tweet.find('created_at').text\n file1.write(data)\n file1.write(\"\\n\")\n \n f.close()\n fi.close()\n file1.close()\n os.remove(\"res.json\")\n os.remove(\"fresult.xml\")\n os.remove(\"result.xml\")\n \n ############################################### END OF CRAWLER ###############################################\n \n ############################################### BEGIN OF SENTIMENTS ###############################################\n \n indicoio.config.api_key = \"8c342644b232b62792927678523256fc\"\n \n # Filter posts and emotion analysis.\n tweets_file = open(\"tweets.txt\", 'r')\n tweets_lines = tweets_file.readlines()\n for i in range(0, len(tweets_lines)):\n tweets_lines[i]=tweets_lines[i].strip() # removes the \\n from entries.\n posts = []\n current_time = datetime.datetime.now()\n delta_time = []\n for i in range(0, len(tweets_lines), 2):\n time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweets_lines[i+1],'%a %b %d %H:%M:%S +0000 %Y'))\n date_time = datetime.datetime.strptime(time_stamp, \"%Y-%m-%d %H:%M:%S\") + datetime.timedelta(hours = 2)\n difference = (current_time - date_time).total_seconds()\n if(difference <= 3600): # Get posts within an hour.\n posts.append(tweets_lines[i]) # creating tweets array.\n delta_time.append(difference / 3600)\n #print(posts)\n \n # Emotion analysis.\n emotion_file = open(\"text_emotion.txt\", 'w')\n size = len(posts)\n if(size > 0):\n weight_latest = 0.45\n weight_entropy = 0.55\n normalized_time = delta_time\n normalized_entropy = []\n #print(\"Normalized Time\", normalized_time)\n \n emotions = indicoio.emotion(posts)\n max_entropy = -0.2 * math.log(0.2, 2) * 5\n for i in range(0, size):\n entropy = 0\n #print(\"*****\")\n #print(\"Probabilities:\")\n for emotion, prob in emotions[i].items():\n entropy = entropy - (prob * math.log(prob, 2))\n #print(emotion, prob)\n entropy = entropy / max_entropy\n normalized_entropy.append(entropy)\n #print(\"#####\")\n #print(\"Entropy\", entropy)\n #print(\"*****\")\n \n rank_final = []\n min_rank = 1000\n min_post = 1000\n for i in range(0, size):\n weight = weight_latest * normalized_time[i] + weight_entropy * normalized_entropy[i]\n rank_final.append((weight, i))\n if(weight < min_rank):\n min_rank = weight\n min_post = i\n #print(\"Rank Final\", rank_final)\n #print(\"Winner Post\", min_post)\n json.dump(emotions[min_post], emotion_file)\n \n ############################################### END OF SENTIMENTS ###############################################","sub_path":"Affect_SocialMed/bin/x64/Debug/emotion_analyser.py","file_name":"emotion_analyser.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"617643299","text":"#############################\n# Author:\n# Xiaowei Jiang(368441)\n# Xi Yang (368236)\n# date:19.06.2016\n#############################\nimport numpy as np\n#############################\n# Assignment 1: SMO for SVMs\n#############################\nclass svm_smo():\n\tdef __init__(self,kernel,C,kernelparameter=None):\n\t\tif not(kernel in ['linear','polynomial','gaussian']):\n\t\t\traise ValueError(\"Please choose a string from {'linear','polynomial','gaussian'}\")\n\t\tself.kernel = kernel\n\t\tif kernelparameter:\n\t\t\tself.kernelparameter = kernelparameter\n\t\tself.regularization = C\n\tdef _compute_box_constraints(self,i,j,Y,alpha,C):\t\t\n\t\tif Y[i]==Y[j]:\n\t\t\tL = max(0,alpha[i]+alpha[j])\n\t\t\tH = min(C,alpha[i]+alpha[j])\n\t\telse:\n\t\t\tL = max(0,alpha[j]-alpha[i])\n\t\t\tH = min(C,C+alpha[j]-alpha[i])\n\t\treturn L,H\n\tdef _compute_updated_b(self,E_i,E_j,i,j,K,Y,alpha_old,alpha_new,b_old,C):\n '''\n [Input]:\n K: kernel matrix\n Ei,Ej: prediction error\n Y: labels {-1,+1}\n [Output]\n returns updated new_b\n '''\n b1 = b_old+E_i+Y[i]*(alpha_new[i]-alpha_old[i])*K[i,i]+Y[j]*(alpha_new[j]-alpha_old[j])*K[i,j]\n b2 = b_old+E_j+Y[i]*(alpha_new[i]-alpha_old[i])*K[i,j]+Y[j]*(alpha_new[j]-alpha_old[j])*K[j,j]\n new_b = b_old\n if alpha_new[i]>0 and alpha_new[i]0 and alpha_new[j]=0:\n\t\t\treturn alpha,b,False\n\t\tnew_alpha = alpha\n\t\tnew_alpha[j] = alpha[j]-Y[j]*(E_i-E_j)/ka\n\t\tif new_alpha[j]>H:\n\t\t\tnew_alpha[j] = H\n\t\tif new_alpha[j]tol and alpha[i]>0):\n\t\t\t\t\tj = np.random.choice(range(n).remove(i))\n\t\t\t\t\tE_j = self.predict(X[j])-y[j]\n\t\t\t\t\talpha,b,updated = self._update_parameters(E_i,E_j,i,j,K,y,alpha,b,C)\n\t\t\t\tif updated:\n\t\t\t\t\ta = a + 1\n\t\t\tif a==0:\n\t\t\t\tp = p + 1\n\t\t\telse:\n\t\t\t\tp = 0\n\t\tself.alpha = alpha\n\t\tself.b = b\n\t\tself.sprt_vec = X[alpha!=0]\n\tdef predict(X):\n\t\ttmp = self.Xtr*self.ytr*self.alpha\n\t\tif self.kernel == 'linear':\n\t\t\tK = tmp.dot(X.T)\n\t\tif self.kernel == 'polynomial':\n\t\t\tK = (tmp.dot(X.T)+1)**self.kernelparameter\n\t\tif self.kernel == 'gaussian':\n\t\t\tK = np.exp((-cdist(tmp,X)**2)/(2*self.kernelparameter**2))\n\t\tself.pred = np.sum(K,axis=0)-self.b\t\t\n\t\treturn self.ypred\n#############################\n# Assignment 2:svm plot util\n#############################\ndef plot_svm_2d(X,y,model):\n\tn = X.shape[0]\n\tsupport_vec = model.sprt_vec\n\tplt.figure(figsize=(8,8))\n\tplt.scatter(X[y==1][0],X[y==1][1],c='b',marker='o')\n\tplt.scatter(X[y==-1][0],X[y==-1][1],c='r',marker='o')\n\t# plot support vectors:\n\tplt.scatter(support_vec[:,0],support_vec[:,1],marker='+')\n\t#plot separating hyperplane:\n\t# TODO plot contour line\n\tplt.show()\n###############################\n# Assignment 3:svm_qp(QP ver.)\n###############################\nclass svm_qp:\n\tdef __init__(self,kernel,C,kernelparameter=None):\n if not(kernel in ['linear','polynomial','gaussian']):\n raise ValueError(\"Please choose a string from {'linear','polynomial','gaussian'}\")\n self.kernel = kernel\n if kernelparameter:\n self.kernelparameter = kernelparameter\n self.regularization = C\n\n\tdef fit(X,y):\n ''' \n y: labels, take values from {-1,+1}\n save support vectors\n '''\n self.support_vectors = []\n\tdef predict(X):\n\t\treturn 0\n","sub_path":"04/code/sheet4.py","file_name":"sheet4.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"504026960","text":"class Node:\n def __init__(self,data):\n self.data=data\n self.next=None\n\nclass linkedlist:\n def __init__(self):\n self.head=None\n\n def append(self,x):\n node=Node(x)\n node.next=self.head\n self.head=node\n\n def reverse(self):\n prev=None\n current=self.head\n while(current):\n next=current.next\n current.next=prev\n prev=current\n current=next\n self.head=prev\n\n def print_ll(self):\n temp=self.head\n while(temp):\n print(temp.data,end=\" \")\n temp=temp.next\n print()\nl = linkedlist()\nmy_list = list(map(int,input().split()))\nfor i in range(len(my_list)):\n l.append(my_list[i])\nl.print_ll()\nl.reverse()\nl.print_ll()\n","sub_path":"450/Ratndeep/reverse a linkedlist.py","file_name":"reverse a linkedlist.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"435609031","text":"\"\"\"\ntyphoon.rest module\n\"\"\"\nimport json\nimport logging\nimport re\nfrom functools import wraps\n\nimport tornado.ioloop\n\nfrom . import __version__\nfrom .settings import settings\nfrom .status import INTERNAL_SERVER_ERROR, OK, UNAUTHORIZED\nfrom .util import camel_to_snake, get_banner, json_camel_to_snake, json_snake_to_camel\nfrom .web import Application, RequestHandler, run_in_executor\n\nlogger = logging.getLogger(__name__)\n\n\nclass RestCallback(object):\n \"\"\"\n Callback object.\n\n Parameters\n ----------\n func_name : str\n name of func to call. should be a method of controller's.\n args : tuple, optional\n args, by default None\n kwargs : dict, optional\n kwargs, by default None\n \"\"\"\n\n def __init__(self, func_name, args=None, kwargs=None):\n self.__func_name = func_name\n self.__args = args or ()\n self.__kwargs = kwargs or {}\n\n @property\n def func_name(self):\n \"\"\"\n func_name\n \"\"\"\n return self.__func_name\n\n @property\n def args(self):\n \"\"\"\n args\n \"\"\"\n return self.__args\n\n @property\n def kwargs(self):\n \"\"\"\n kwargs\n \"\"\"\n return self.__kwargs\n\n\nclass RestResult(object):\n \"\"\"\n RestResult object.\n\n Parameters\n ----------\n status : int, optional\n HTTP status, by default 200\n content : Union[str, dict], optional\n response content, by default None\n callback : RestCallback, optional\n RestCallback object, by default None\n \"\"\"\n\n def __init__(self, status=OK, content=None, callback=None):\n self.__status = status\n self.__content = content\n self.__callback = callback\n\n @property\n def status(self):\n \"\"\"\n status\n \"\"\"\n return self.__status\n\n @property\n def content(self):\n \"\"\"\n content\n \"\"\"\n return self.__content\n\n @property\n def callback(self):\n \"\"\"\n callback\n \"\"\"\n return self.__callback\n\n\nclass RestHandler(RequestHandler):\n \"\"\"\n RestHandler object.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(RestHandler, self).__init__(*args, **kwargs)\n self.params: dict\n\n def prepare(self):\n url_params = {}\n if settings.convert_case:\n for key in self.request.arguments:\n url_params[camel_to_snake(key)] = self.get_argument(name=key)\n\n try:\n camel_json = self.decode_argument(self.request.body)\n snake_json = json_camel_to_snake(camel_json)\n body_params = json.loads(snake_json)\n except:\n body_params = {}\n else:\n for key in self.request.arguments:\n url_params[key] = self.get_argument(name=key)\n try:\n body_json = self.decode_argument(self.request.body)\n body_params = json.loads(body_json)\n except:\n body_params = {}\n\n self.params = {**url_params, **body_params}\n\n @staticmethod\n def serialize(content):\n if isinstance(content, str):\n return content\n content_json = json.dumps(content)\n if settings.convert_case:\n return json_snake_to_camel(content_json)\n return content_json\n\n @run_in_executor\n def process(self, *args, **kwargs):\n return self.application._process(*args, **kwargs)\n\n async def handle(self, _func, *args, **kwargs):\n kwargs = {**kwargs, **self.params}\n result = await self.process(_func, *args, **kwargs)\n\n status = result.status\n self.set_status(status)\n\n content = result.content\n if content:\n self.write(self.serialize(content))\n self.finish()\n\n callback = result.callback\n if callback:\n await self.process(callback.func_name, *callback.args, **callback.kwargs)\n\n def compute_etag(self):\n return None\n\n def data_received(self, chunk):\n pass\n\n\n_HANDLERS = {}\n\n\ndef route(uri, method='get', auth_required=False):\n \"\"\"\n Decorator for methods of RestController.\n\n Typhoon will generate a RequestHandler for each distinct uri, and\n create a http method as specified which is binded to the decorated method.\n\n Parameters\n ----------\n uri : str\n Endpoint of the api.\n method : str, optional\n HTTP method, by default 'get'\n auth_required : bool, optional\n whether authorization is required, by default False\n \"\"\"\n method = method.lower()\n assert method in ('get', 'post', 'put', 'patch',\n 'delete', 'head', 'options')\n\n def decorator(func):\n func_name = func.__name__\n hdlr_name = '%s_handler' % '_'.join(re.split(r'[^\\w]', uri))\n\n if uri not in _HANDLERS:\n _HANDLERS[uri] = type(hdlr_name, (RestHandler,), dict())\n\n async def method_body(self, *args, **kwargs):\n authorized = True\n if auth_required:\n auth_header = self.request.headers.get('Authorization')\n authorized = await self.process(_func='authorize', auth_header=auth_header)\n if authorized:\n await self.handle(func_name, *args, **kwargs)\n else:\n self.set_status(UNAUTHORIZED)\n content = {'error': 'authorization is required for this method.'}\n self.write(self.serialize(content))\n\n setattr(_HANDLERS[uri], method, method_body)\n\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n try:\n result = func(self, *args, **kwargs)\n except Exception as e:\n logger.error('%s', e, exc_info=True)\n result = RestResult(\n status=INTERNAL_SERVER_ERROR,\n content={'error': f'{e}'}\n )\n return result\n return wrapper\n return decorator\n\n\nclass RestController(object):\n \"\"\"\n RestController object.\n \"\"\"\n\n def __init__(self):\n banner = get_banner(__version__)\n logger.info(banner)\n\n def authorize(self, auth_header):\n \"\"\"\n override this method to check authorization.\n\n Parameters\n ----------\n auth_header : Union[dict, None]\n Authorization header of the request.\n \"\"\"\n raise NotImplementedError\n\n @route(uri=r'/typhoon/banner', method='get')\n def _get_typhoon_banner(self):\n return RestResult(content=f'
{get_banner(__version__)}')\n\n    @route(uri=r'/typhoon/version', method='get')\n    def _get_typhoon_version(self):\n        return RestResult(\n            content={\n                'typhoon': __version__,\n                'tornado': tornado.version\n            }\n        )\n\n\nclass RestApplication(Application):\n    \"\"\"\n    RestApplication object.\n    \"\"\"\n\n    def __init__(self, controller: RestController) -> None:\n        handlers = []\n        for uri in _HANDLERS:\n            handlers.append((uri, _HANDLERS[uri]))\n\n        super(RestApplication, self).__init__(handlers=handlers)\n\n        self._controller = controller\n\n    def _process(self, _func, *args, **kwargs):\n        return getattr(self._controller, _func)(*args, **kwargs)\n\n\ndef start_server(controller: RestController, port: int = 9999) -> None:\n    \"\"\"\n    start a HTTP server.\n\n    Parameters\n    ----------\n    controller : RestController\n        controller.\n    port : int, optional\n        port to listen to, by default 9999\n    \"\"\"\n    try:\n        app = RestApplication(controller=controller)\n        app.listen(port)\n        tornado.ioloop.IOLoop().current().start()\n    except:\n        logger.error('oops! server crashed...', exc_info=True)\n","sub_path":"typhoon/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"201763302","text":"# coding=utf-8\n\nimport sickbeard\n\nfrom datetime import date\nfrom sickbeard.common import Quality, SKIPPED, WANTED\nfrom sickbeard.db import DBConnection\nfrom sickrage.helper.exceptions import CantRefreshShowException, CantRemoveShowException, ex\nfrom sickrage.helper.exceptions import MultipleShowObjectsException\n\n\nclass Show(object):\n    def __init__(self):\n        pass\n\n    @staticmethod\n    def delete(indexer_id, remove_files=False):\n        \"\"\"\n        Try to delete a show\n        :param indexer_id: The unique id of the show to delete\n        :param remove_files: ``True`` to remove the files associated with the show, ``False`` otherwise\n        :return: A tuple containing:\n         - an error message if the show could not be deleted, ``None`` otherwise\n         - the show object that was deleted, if it exists, ``None`` otherwise\n        \"\"\"\n\n        error, show = Show._validate_indexer_id(indexer_id)\n\n        if error is not None:\n            return error, show\n\n        if show:\n            try:\n                sickbeard.showQueueScheduler.action.removeShow(show, bool(remove_files))\n            except CantRemoveShowException as exception:\n                return ex(exception), show\n\n        return None, show\n\n    @staticmethod\n    def find(shows, indexer_id):\n        \"\"\"\n        Find a show by its indexer id in the provided list of shows\n        :param shows: The list of shows to search in\n        :param indexer_id: The indexer id of the desired show\n        :return: The desired show if found, ``None`` if not found\n        :throw: ``MultipleShowObjectsException`` if multiple shows match the provided ``indexer_id``\n        \"\"\"\n\n        if indexer_id is None or shows is None or len(shows) == 0:\n            return None\n\n        indexer_ids = [indexer_id] if not isinstance(indexer_id, list) else indexer_id\n        results = [show for show in shows if show.indexerid in indexer_ids]\n\n        if not results:\n            return None\n\n        if len(results) == 1:\n            return results[0]\n\n        raise MultipleShowObjectsException()\n\n    @staticmethod\n    def overall_stats():\n        db = DBConnection()\n        shows = sickbeard.showList\n        today = str(date.today().toordinal())\n\n        downloaded_status = Quality.DOWNLOADED + Quality.ARCHIVED\n        snatched_status = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_BEST\n        total_status = [SKIPPED, WANTED]\n\n        results = db.select(\n            'SELECT airdate, status '\n            'FROM tv_episodes '\n            'WHERE season > 0 '\n            'AND episode > 0 '\n            'AND airdate > 1'\n        )\n\n        stats = {\n            'episodes': {\n                'downloaded': 0,\n                'snatched': 0,\n                'total': 0,\n            },\n            'shows': {\n                'active': len([show for show in shows if show.paused == 0 and show.status == 'Continuing']),\n                'total': len(shows),\n            },\n        }\n\n        for result in results:\n            if result['status'] in downloaded_status:\n                stats['episodes']['downloaded'] += 1\n                stats['episodes']['total'] += 1\n            elif result['status'] in snatched_status:\n                stats['episodes']['snatched'] += 1\n                stats['episodes']['total'] += 1\n            elif result['airdate'] <= today and result['status'] in total_status:\n                stats['episodes']['total'] += 1\n\n        return stats\n\n    @staticmethod\n    def pause(indexer_id, pause=None):\n        \"\"\"\n        Change the pause state of a show\n        :param indexer_id: The unique id of the show to update\n        :param pause: ``True`` to pause the show, ``False`` to resume the show, ``None`` to toggle the pause state\n        :return: A tuple containing:\n         - an error message if the pause state could not be changed, ``None`` otherwise\n         - the show object that was updated, if it exists, ``None`` otherwise\n        \"\"\"\n\n        error, show = Show._validate_indexer_id(indexer_id)\n\n        if error is not None:\n            return error, show\n\n        if pause is None:\n            show.paused = not show.paused\n        else:\n            show.paused = pause\n\n        show.saveToDB()\n\n        return None, show\n\n    @staticmethod\n    def refresh(indexer_id):\n        \"\"\"\n        Try to refresh a show\n        :param indexer_id: The unique id of the show to refresh\n        :return: A tuple containing:\n         - an error message if the show could not be refreshed, ``None`` otherwise\n         - the show object that was refreshed, if it exists, ``None`` otherwise\n        \"\"\"\n\n        error, show = Show._validate_indexer_id(indexer_id)\n\n        if error is not None:\n            return error, show\n\n        try:\n            sickbeard.showQueueScheduler.action.refreshShow(show)\n        except CantRefreshShowException as exception:\n            return ex(exception), show\n\n        return None, show\n\n    @staticmethod\n    def _validate_indexer_id(indexer_id):\n        \"\"\"\n        Check that the provided indexer_id is valid and corresponds with a known show\n        :param indexer_id: The indexer id to check\n        :return: A tuple containing:\n         - an error message if the indexer id is not correct, ``None`` otherwise\n         - the show object corresponding to ``indexer_id`` if it exists, ``None`` otherwise\n        \"\"\"\n\n        try:\n            indexer_id = int(indexer_id)\n        except (TypeError, ValueError):\n            return 'Invalid show ID', None\n\n        try:\n            show = Show.find(sickbeard.showList, indexer_id)\n        except MultipleShowObjectsException:\n            return 'Unable to find the specified show', None\n\n        return None, show\n","sub_path":"sickrage/show/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"616715523","text":"import contextlib\nimport shutil\nimport tempfile\nimport unittest\n\nimport mock\n\n\nclass CommonTest(unittest.TestCase):\n    \"\"\"\n    A sub-class of :class:`unittest.TestCase` that provides common\n    testing functionality.\n\n    \"\"\"\n    def _remove_testcase_patches(self):\n        \"\"\"Helper to remove per-testcase patches installed by :meth:`patch`.\"\"\"\n        # Remove all patches made, ignoring errors.\n        for p in self.testcase_patches:\n            p.stop()\n        # Reset per-test patch control variable.\n        self.testcase_patches.clear()\n\n    def patch(self, *args, **kwargs):\n        \"\"\"\n        Install a mock.patch, to be removed after the current test.\n\n        The patch is created with mock.patch(*args, **kwargs).\n\n        Returns:\n            The substitute object returned by patch.start().\n\n        For example::\n\n            mock_call = self.patch('module.Class.call', return_value=1)\n            module_Class_instance.call(3, 4)\n            self.assertEqual(mock_call.call_args_list, [mock.call(3, 4)])\n\n        \"\"\"\n        # Make the new patch and start it.\n        patch = mock.patch(*args, **kwargs)\n        start_result = patch.start()\n\n        # Create the per-testcases control variable if it does not exist.\n        # NOTE: this mimics a setUp method, but continues to work when a\n        # subclass defines its own setUp.\n        if not hasattr(self, 'testcase_patches'):\n            self.testcase_patches = {}\n\n        # When installing the first patch, schedule remove-all at cleanup.\n        if not self.testcase_patches:\n            self.addCleanup(self._remove_testcase_patches)\n\n        # Record the new patch and start object for reference.\n        self.testcase_patches[patch] = start_result\n\n        # Return patch replacement object.\n        return start_result\n\n    @contextlib.contextmanager\n    def temp_dir(self, suffix='', prefix='tmp', dir=None):\n        dname = tempfile.mkdtemp(suffix=suffix,\n                                 prefix=prefix,\n                                 dir=dir)\n        try:\n            yield dname\n        finally:\n            shutil.rmtree(dname) \n","sub_path":"conda_rpms/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"583238304","text":"from threading import Timer\nfrom core.jsr223.scope import events\nfrom core.jsr223.scope import itemRegistry \nfrom core.log import log_traceback, add_logger\nfrom personal import config\nimport org.eclipse.smarthome.core.items.GroupItem as GroupItem\n\n\"\"\"\nTimer classes for openHAB jython rules\n\"\"\"\n\n@add_logger\nclass BaseTimer(object):\n    \"\"\" Base class for timers\"\"\"\n\n    _timers={}\n\n    def __init__(self, function=None, args=[], kwargs={}):\n        self.function = function\n        self.args = args\n        self.kwargs = kwargs\n\n    def start(self, interval=60, item=None):\n        if item.name not in self._timers:\n            self._timers[item.name] = None\n        self.interval = interval\n        self.items = item\n        self.start_timer(item.name)\n\n    @log_traceback\n    def start_timer(self, name):\n        \"\"\" Start or reschedule timer \"\"\"\n        timer = self._timers[name]\n        if not timer or not timer.isAlive():\n            timer = Timer(self.interval, self.function, self.args, self.kwargs)\n            timer.start()\n            self.log.debug(\"Timer \\\"{}\\\" started\".format(name))\n        elif timer and timer.isAlive():\n            timer.cancel()\n            timer = Timer(self.interval, self.function, self.args, self.kwargs)\n            timer.start()\n            self.log.debug(\"Timer \\\"{}\\\" rescheduled\".format(name))\n        self._timers[name] = timer\n\n    def run(self):\n        \"\"\" function that runs when timer expires or is stopped \"\"\" \n        pass\n\n    def stop(self):\n        \"\"\" Stop the timer and run function\"\"\"\n        if self.timer:\n            self.timer.cancel()\n            self.timer = None\n            self.run()\n\n@add_logger\nclass OffTimer(BaseTimer):\n    \"\"\" Off timer \"\"\"\n    def __init__(self):\n        BaseTimer.__init__(self, self.run)\n\n    def run(self):\n        if isinstance(self.items, list):\n            for item in self.items:\n                events.sendCommand(item, \"OFF\")\n        elif isinstance(self.items, GroupItem):\n            group_members = itemRegistry.getItem(self.items.name).members\n            for member in group_members:\n                events.sendCommand(member, \"OFF\")\n        else:\n            events.sendCommand(self.items, \"OFF\")\n\n@add_logger\nclass CommandTimer(BaseTimer):\n    def __init__(self):\n        BaseTimer.__init__(self, self.run)\n\n    def run(self):\n        if isinstance(self.items, list):\n            for item in self.items:\n                events.sendCommand(item, \"OFF\")\n        elif isinstance(self.items, GroupItem):\n            group_members = itemRegistry.getItem(self.items.name).members\n            for member in group_members:\n                events.sendCommand(member, \"OFF\")\n        else:\n            events.sendCommand(self.items, \"OFF\")","sub_path":"automation/lib/python/personal/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"47664685","text":"from urllib import request\r\nimport string\r\nimport os\r\nimport sys\r\nimport json\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nfrom urllib.parse import unquote\r\nfrom urllib.parse import quote\r\nfrom urllib import request\r\nfrom urllib.parse import urlparse\r\nimport http.client\r\nfrom urllib.parse import urljoin\r\nfrom urllib.error import HTTPError\r\nimport logging\r\nimport re\r\nimport posixpath\r\n\r\n#USER AGENT\r\nhdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\r\n           'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\r\n           'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\r\n           'Accept-Encoding': 'none',\r\n           'Accept-Language': 'en-US,en;q=0.8',\r\n           'Connection': 'keep-alive'}\r\n\r\n\r\n\r\n\r\npageObjectCache = {}\r\nlog = logging.getLogger()\r\nlogging.basicConfig()\r\nlog.setLevel(logging.INFO)\r\n\r\n\r\n#print(urljoin(\"http://www.test.com/folder/file.html\",\".\"))\r\n#print(urljoin(\"http://www.test.com/folder/file.html\",\"image.png\"))\r\n#print(urljoin(\"http://www.test.com/folder/file.html\",\"image.png\"))\r\n#print(urljoin(\"http://www.test.com/folder/file.html\",\"./image.png\"))\r\n#print(urljoin(\"http://www.test.com/folder/file.html\",\"/image.png\"))\r\n#print(urljoin(\"http://www.test.com/folder/file.html\",\"../image.png\"))\r\n#log.critical(\"critical\")\r\n#log.error(\"error\")\r\n#log.warning(\"warning\")\r\n#log.info(\"info\")\r\n#log.debug(\"debug\")\r\n\r\n\r\n\r\n#url -> page object\r\n\r\ndef getPage(url):\r\n    '''get a page object using a URL as input'''\r\n    log.debug(\"getPage \" + url)\r\n    #if (url[-1] != \"/\"): url += \"/\"\r\n    if (url in pageObjectCache):\r\n        #print(\">>>getPage CACHE PAGE HIT \" + url)\r\n        return pageObjectCache[url]\r\n    #print(\">>>getPage CACHE PAGE MISS \" + url)\r\n    p = Page(url)\r\n    pageObjectCache[url] = p\r\n    return p\r\n\r\ndef savePageObject(p):\r\n    if (p.isValid()):\r\n        #IO.mkdir(p.getHost() + \"/\" + p.getFolderPath())\r\n        d = {}\r\n        links = p.getLinksInPage()\r\n        \r\n        for link in links:\r\n            try:\r\n                local = URL.toLocalURL(p.getOriginalURL(), link)\r\n                d[link] = local\r\n            except: \r\n                d[link] = \"javascript:;\" #empty link\r\n           \r\n        fixed = Utility.multiReplace(p.getText(), d)\r\n        \r\n        IO.mkdir(os.path.dirname(p.getCompletePath()))\r\n        IO.writeStringToFile(fixed, p.getCompletePath())\r\n        log.info(\"savePageObject \" + p.getOriginalURL() + \" completed\")\r\n    else: log.error(\"savePageObject \" + p.getOriginalURL() + \" is not valid\")\r\n\r\n\r\nclass Page(object):\r\n    '''this class represents a page, content is cached'''\r\n    \r\n    url = None\r\n    pageContent = None\r\n    internalPath = None\r\n    pages = None\r\n    valid = False\r\n    headers = None\r\n    init = False\r\n    text = None\r\n    host = None\r\n    fileName = None\r\n    links = None\r\n    \r\n    def __init__(self,url):\r\n        '''init a page using a url'''\r\n        self.url = url\r\n        \r\n    def getContent(self):\r\n        self.init = True\r\n        self.internalPath = urlparse(self.url).path\r\n        log.debug(\"internalPath \" + self.internalPath)\r\n        \r\n        \r\n        self.internalPath = self.internalPath.replace(\"/\", os.path.sep)\r\n        #don't join together\r\n        \r\n        #if no path, it is root\r\n        #add heading and trailing /s to path\r\n        #self.internalPath = os.path.sep + self.internalPath + os.path.sep\r\n        \r\n\r\n        \r\n        splitted = self.internalPath.split(os.path.sep)\r\n        self.internalPath = os.path.sep.join(splitted[:-1])\r\n        log.debug(\"internalPathFixed \" + self.internalPath)\r\n        self.fileName = splitted[-1]\r\n        log.debug(\"internalFileName \" + self.fileName)\r\n        if (self.fileName == None or len(self.fileName) == 0):\r\n                self.fileName = \"index\"\r\n            \r\n        try:\r\n            log.debug(\"getContent -> getting rawdata and headers\")\r\n            self.pageContent,self.headers,self.host = Network.getRawData( self.url)\r\n            log.debug(\"getContent -> reading headers\")\r\n            \r\n            ext = \"html\"\r\n            try: \r\n                ext = self.headers['Accept'].split(\",\")[0].split(os.path.sep)[1]\r\n                self.fileName += \".\" + ext\r\n            except: \r\n                log.warning(\"getContent -> can't get extension name, setting default to .html\")\r\n            self.fileName += \".\" + ext\r\n            if (self.pageContent == None):\r\n                self.valid = False\r\n                return None\r\n            try:\r\n                self.text = self.pageContent.decode('utf-8')\r\n            except UnicodeDecodeError:\r\n                self.text = \"UnicodeDecodeError\"\r\n        #if true error or page error\r\n        except HTTPError as error:\r\n            print(\"getContent -> HTTPError \" + str(error.status))\r\n            \r\n            try: \r\n                self.pageContent = error.read()\r\n                log.debug(\"getContent good after HTTPError\")\r\n                self.valid = True\r\n            #if true error\r\n            except HTTPError as trueerror: \r\n                log.error(\"getContent -> TRUE ERROR\")\r\n                log.error(\"getContent -> \" + str(trueerror.status))\r\n                self.valid = False\r\n                return None\r\n            \r\n            self.text = self.pageContent.decode('utf-8')\r\n            return self.pageContent\r\n        except HTTPError as trueerror:\r\n            log.error(\"getContent -> TRUE ERROR DIRECT\")\r\n            log.error(\"getContent -> \" + str(trueerror.status))\r\n            self.valid = False\r\n            return None\r\n        self.valid = True\r\n        return self.pageContent\r\n    \r\n    def invalidateCache(self):\r\n        '''invalidates the cached page'''\r\n        self.init = False\r\n        \r\n    def getCompletePath(self):\r\n        '''get local path file'''\r\n        if (self.init == False):\r\n            self.getContent()\r\n        return os.path.normpath(self.host + os.path.sep + self.internalPath + os.path.sep + self.fileName)\r\n    \r\n    def getFileName(self):\r\n        if (self.init == False):\r\n            self.getContent()\r\n        return self.fileName\r\n    \r\n    def getFolderPath(self):\r\n        if (self.init == False):\r\n            self.getContent()\r\n        return os.path.normpath(self.internalPath)\r\n\r\n    def getHost(self):\r\n        return self.host\r\n        \r\n    def getLinksInPage(self):\r\n        '''get all links'''\r\n        if (self.init == False):\r\n            self.getContent()\r\n        self.links = []\r\n        if (self.pageContent == None): return self.pages\r\n        for link in HTML.getAllLinks(self.text):      \r\n            self.links.append(link)\r\n        return self.links\r\n    \r\n    def getAbsoluteLinks(self):\r\n        '''get all links'''\r\n        if (self.init == False):\r\n            self.getContent()\r\n        self.links = []\r\n        if (self.pageContent == None): return self.pages\r\n        for link in HTML.getAllLinks(self.pageContent.decode('utf-8')):      \r\n            self.links.append(urljoin(self.url,link))\r\n        return self.links\r\n    \r\n    def getPages(self):\r\n        '''get pages linked in this one'''\r\n        links = self.getAbsoluteLinks()\r\n        self.pages = []\r\n        for link in links:\r\n            self.pages.append(getPage(link))\r\n        return self.pages\r\n    \r\n    def getOriginalURL(self):\r\n        if (self.init == False):\r\n            self.getContent()\r\n        '''get the original input URL'''\r\n        return self.url\r\n    \r\n    def getText(self):\r\n        return self.text\r\n    \r\n    def fixLinks(self):\r\n        if (self.init == False):\r\n            self.getContent()\r\n        l = self.getLinks()\r\n        \r\n    \r\n    #def getRedirectURL(self):\r\n    #    if (self.init == False):\r\n    #        self.getContent()\r\n    #        if (self.valid): return self.redirect\r\n    #        else:return self.url\r\n    #    '''get a different URL if the original one is a redirect'''\r\n    #    return self.redirect\r\n    \r\n    def isValid(self):\r\n        if (self.init == False):\r\n            self.getContent()\r\n        '''returns True if the page isn't a 400 or 404 bad request'''\r\n        return self.valid\r\n    \r\n    def __str__(self):\r\n        if (self.init == False):\r\n            self.getContent()\r\n        return \"\"\r\n    \r\n    \r\n\r\n\r\nclass Network(object):\r\n\r\n\r\n\r\n    @staticmethod\r\n    def getRawData(url):\r\n        '''downloads and returns a raw page data, tuple (rawdata,headers)'''\r\n        log.debug(\"getRawData -> \" + url)\r\n        req = request.Request(url, headers=hdr)\r\n        try:\r\n            page = request.urlopen(req)\r\n        except Exception as e:\r\n            log.error(\"getRawData SUPERERROR \" + str(e.status))\r\n            return (None,None,None)\r\n        return (page.read(),req.headers,req.host)\r\n\r\n    @staticmethod\r\n    def getPageInfo(url):\r\n        '''downloads and returns a page tuple (host,selector,links)'''\r\n        req = request.Request(url, headers=hdr)\r\n        page = request.urlopen(req)\r\n        data = urlparse(url)\r\n        return (data.netloc,data.path,HTML.getAllLinks(page.read().decode('utf-8')))\r\n\r\n    @staticmethod\r\n    def getRawPage(url):\r\n        '''downloads and returns a raw html page'''\r\n        return Network.getRawData(url).decode('utf-8')\r\n\r\n\r\n\r\nclass Utility(object):\r\n    \r\n    @staticmethod\r\n    def find_between( s, first, last ):\r\n        try:\r\n            start = s.index( first ) + len( first )\r\n            end = s.index( last, start )\r\n            return s[start:end]\r\n        except ValueError:\r\n            return \"\"\r\n        \r\n    @staticmethod\r\n    def multiReplace(text,rep):\r\n        #rep = {\"condition1\": \"\", \"condition2\": \"text\"} # define desired replacements here\r\n        # use these three lines to do the replacement\r\n        #rep = dict((re.escape(k), v) for k, v in rep.iteritems())\r\n        #pattern = re.compile(\"|\".join(rep.keys()))\r\n        #text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)\r\n        for oldlink,newlink in rep.items():\r\n            log.debug(\"replacing \" + oldlink + \" -> \" + newlink)\r\n            text = text.replace(oldlink,newlink)\r\n        log.debug(\"replacing done\")\r\n        return text\r\n\r\nclass IO(object):\r\n    \r\n    @staticmethod\r\n    def fixFileName(filename):\r\n        '''remove invalid chars from filename'''\r\n        invalid_chars = \"\\//:*?\\\"<>|\"\r\n        temp = \"\"\r\n        for b in filename:\r\n            if (b not in invalid_chars): temp += b\r\n            else: temp += \"_\"\r\n        return temp\r\n\r\n    @staticmethod\r\n    def writeStringToFile(string,filename):\r\n        f = open(filename, 'w',encoding='utf-8')\r\n        f.write(string)\r\n        f.close()\r\n\r\n    @staticmethod\r\n    def mkdir(path):\r\n        '''creates a folder if it doesn't exist, takes care of bad characters'''\r\n        log.debug(\"mkdirInput \" + path)\r\n        splittedPath = path.split(\"/\")\r\n        for folder in splittedPath:\r\n            folder = IO.fixFileName(folder)\r\n        path = \"/\".join(splittedPath)    \r\n        log.debug(\"mkdirActual \" + path)\r\n        if not os.path.exists(path): os.makedirs(path)\r\n\r\nclass URL(object):\r\n\r\n    @staticmethod\r\n    def getFileInfo(url):\r\n        '''tuple (path,filename)'''\r\n        sample2 = request.Request(url, headers = hdr)\r\n        sample = request.urlopen(sample2)\r\n        headers = dict(sample.info())\r\n        print(headers)\r\n        filename = \"ERROR\"\r\n        if sample.getcode() == 200:\r\n            #has_key not work here, and this help avoid problem with names\r\n            return headers['content-disposition']\r\n            if 'content-disposition' in sample.headers.keys():\r\n                print(\"headers\")\r\n                filename = sample.headers['content-disposition'].split('filename=')[-1].replace('\"','').replace(';','')\r\n            else:\r\n                print(\"manual\")\r\n                filename = urlparse(sample.url).query.split('/')[-1].split('=')[-1].split('&')[-1]\r\n                if not filename:\r\n                    if url.split('/')[-1] != '':\r\n                        filename = sample.url.split('/')[-1].split('=')[-1].split('&')[-1]\r\n                        filename = unquote(filename)\r\n            parsed = urlparse(url).path\r\n            fixed = parsed[:-len(filename)]\r\n            fixed = \"/\" if len(fixed) == 0 or fixed == \"//\" else fixed\r\n            fileIO = IO.fixFileName(filename)\r\n            #fileIO = fileIO.split(\".\")\r\n            #if (len(fileIO) == 1): fileIO = fileIO[0]\r\n            #if (len(fileIO) >= 2):\r\n            #    if (fileIO[-1] \r\n            #   fileIO = fileIO[0]\r\n            \r\n\r\n            return (fixed,fileIO)\r\n        return (\"\",\"\")\r\n    \r\n    @staticmethod\r\n    def relurl(target,base):\r\n        base=urlparse(base)\r\n        target=urlparse(target)\r\n        if base.netloc != target.netloc:\r\n            raise ValueError('target and base netlocs do not match')\r\n        base_dir='.'+posixpath.dirname(base.path)\r\n        target='.'+target.path\r\n        return posixpath.relpath(target,start=base_dir)\r\n            \r\n    @staticmethod\r\n    def isUrlRelative(url):\r\n        if (url[0] == \"/\"): return True\r\n        return False\r\n\r\n    @staticmethod\r\n    def getOriginal(url):\r\n        '''get original url with headers'''\r\n        req = request.Request(url, headers = hdr)\r\n        res = request.urlopen(req)\r\n        finalurl = res.geturl()\r\n        return (finalurl,req.headers)\r\n    \r\n    @staticmethod\r\n    def toLocalURL(pageurl,link):\r\n        '''pageurl = where link is contained, link: the actual url to convert'''\r\n        if (\"#\" in link): return link\r\n        linkabsolute = urljoin(pageurl,link)\r\n        \r\n        log.debug(\"linkabsolute \" + linkabsolute)\r\n        log.debug(\"pageurl \" + pageurl)\r\n        urlnew = URL.relurl(linkabsolute,pageurl)\r\n        log.debug(\"urlnew \" + urlnew)\r\n        #splittedURI = urlnew.split(\"/\")[1:]\r\n        \r\n        #if (len(splittedURI[-1].split(\".\")) != 2):\r\n        #    splittedURI[-1] += \".html\"\r\n        \r\n        #urlnew = os.path.sep.join(splittedURI)[1:]\r\n        #\"./\" + \r\n        urlnew = urlnew + \".html\"\r\n        log.debug(\"urlnew \" + urlnew)\r\n        #absolute = absolute.replace(\"/\", os.path.sep)\r\n        \r\n        #parsed_uri = urlparse( absolute)\r\n        #host = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)\r\n        return urlnew\r\n        \r\n    \r\n\r\nclass HTML(object):\r\n\r\n    @staticmethod\r\n    def getAllLinks(pageString):\r\n        t = pageString\r\n        l = []\r\n        for i in range(6,len(t)): \r\n            if t[i-6:i] == \"href=\\\"\" or t[i-6:i] == \" src=\\\"\":\r\n                k = 0\r\n                \r\n                sublink = \"\"\r\n                while t[i+k] != \"\\\"\":\r\n                    sublink += t[i+k]\r\n                    k += 1\r\n                #if sublink[0] == \"#\": continue\r\n                #if not \"/wiki/\" in sublink: continue\r\n                #if \"#\" in sublink:\r\n                #    splitted = sublink.split(\"#\")\r\n                #    good = splitted[0][6:].replace(\"_\",\" \") + \".html#\" + splitted[1]\r\n                #else:\r\n                #good = sublink[6:].replace(\"_\",\" \") + \".html\"\r\n                l.append(sublink)\r\n            \r\n                \r\n        return l\r\n\r\n#@staticmethod\r\n#def downloadSinglePage(url):\r\n#        rawPage = HTML.getRawPage(url)\r\n#        IO.writeStringToFile(rawpage,URL.getFileNameByUrl(url))\r\n\r\nif __name__ == \"__main__\":\r\n    if len(sys.argv) == 1:\r\n        print(\" \")\r\n        print(\"+---------------+\")\r\n        print(\"|PyExplorer v0.0|\")\r\n        print(\"+---------------+\")\r\n        print(\" \")\r\n        print(\"Available commands:\")\r\n        print(\" \")\r\n        print(\"-r recursive\") \r\n        print(\"-i if you want to download images\")\r\n        print(\"-c if you want to download css\")\r\n        print(\"-j if you want to download javascript\")\r\n        print(\"-z if you want to download other files\")\r\n        print(\"-E activates all previous commands\")\r\n        print(\"-f domains to follow separated by commas (implies -r)\")\r\n        print(\"-x if you want to fix links to local ones\")\r\n        print(\"-o outputs log to file\")\r\n        print(\"example.com (website to crawl)\")\r\n        print(\" \")\r\n        print(\"Note: if files are outside the chosen domain they need an -f domain\")\r\n        print(\"Note: using only the domain as input will use -E\")\r\n        print(\"Note: urls containing slashes / as filename, it will be replaced with _\")\r\n        exit(0)\r\n\r\n\r\n    \r\n\r\n\r\n    if len(sys.argv) == 2:\r\n        pass\r\n    \r\n","sub_path":"PyExplorer/PyExplorer.py","file_name":"PyExplorer.py","file_ext":"py","file_size_in_byte":16505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"388656995","text":"from collections import Counter\n# Python3 program to print n-th permutation\n\nMAX_FACT = 31\nfact = [None] * (MAX_FACT)\n\ndef precomputeFactorials():\n    fact[0] = 1\n    for i in range(1, MAX_FACT):\n            fact[i] = fact[i - 1] * i\n\ndef nPermute(string, n):\n    precomputeFactorials()\n\n    length = len(string)\n    freq = Counter(string)\n    freq = [freq['H'], freq['V']]\n\n    out = [None] * length\n\n    Sum, k = 0, 0\n\n    while Sum != n:\n        Sum = 0\n        for i in range(2):\n            if freq[i] == 0:\n                continue\n\n            # Remove character\n            freq[i] -= 1\n\n            xsum = fact[length - 1 - k]\n            for j in range(2):\n                xsum = xsum // fact[freq[j]]\n            Sum += xsum\n\n            if Sum >= n:\n                out[k] = ('H' if i == 0 else 'V')\n                n -= Sum - xsum\n                k += 1\n                break\n\n            if Sum < n:\n                freq[i] += 1\n\n    i = 1\n    while k < length and i >= 0:\n        if freq[i]:\n            out[k] = 'V'\n            freq[i] -= 1\n            i += 1\n            k += 1\n\n        i -= 1\n\n    print(''.join(out[:k]))\n\n# Driver Code\nif __name__ == \"__main__\":\n\n    n = 3\n    string = \"HHHHVV\"\n\n    nPermute(string, n)\n\n# This code is contributed by Rituraj Jain\n","sub_path":"codeforces/educational 100/tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"291250116","text":"import requests\nimport asyncio\nimport json\nimport sys\nimport os\n\n\ndef getOctopiKey() -> str:\n    keys = []\n    with open('/home/pi/RPi-EdgeMicroserver/3D-Printer-Control-Hub/security/keys.txt') as f:\n        keys = f.readlines()\n    f.close()\n    return keys[0]\n\ndef jogPrinthead(dist:int, axis:int) -> bool:\n\n    key = getOctopiKey()\n    \n    base = 'http://octopi.local'\n    url = '/api/printer/printhead'\n\n    headers = {\n        'X-Api-Key': key.strip('\\n'),\n        'Content-Type': 'application/json',\n        'accept': 'application/json'\n        }\n\n    payload = {\"command\": \"jog\",\n                str(axis): float(dist)\n               }\n\n    params = {}\n    \n    try:\n        response = requests.request(\"POST\", base+url, params=params, headers=headers, data=json.dumps(payload))\n        return True\n    except:\n        pass\n        return False\n\n\ndist = sys.argv[1]\naxis = sys.argv[2]\n\n\njogPrinthead(dist, axis)","sub_path":"3D-Printer-Control-Hub/scripts/jogPrinthead.py","file_name":"jogPrinthead.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"263479834","text":"\n\n\nclass Solution:\n    \"\"\"\n    @param: nums: A list of integers\n    @return: An integer denotes the sum of max two non-overlapping subarrays\n    \"\"\"\n    def maxTwoSubArrays(self, nums):\n        # write your code here\n        lmax = [nums[0]]\n        cur_max = nums[0]\n        for num in nums[1:]:\n            cur_max = max(num, cur_max+num)\n            lmax.append(max(lmax[-1], cur_max))\n\n        rmax = [nums[-1]]\n        cur_max = nums[-1]\n        for num in nums[-2::-1]:\n            cur_max = max(num, cur_max+num)\n            rmax.insert(0, max(rmax[0], cur_max))\n\n        res = -float('inf')\n        for i in range(1, len(nums)):\n            res = max(res, lmax[i-1]+rmax[i])\n        return res\n\nif __name__ == '__main__':\n    s = Solution()\n    nums = [1, 3, -1, 2, -1, 2]\n    print(s.maxTwoSubArrays(nums))","sub_path":"Lintcode-ladder/DynamicProgramming/minimumSubarrayII.py","file_name":"minimumSubarrayII.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"84861606","text":"\"\"\"\nParses the python AST below, transforms it to C, JITs it, and runs it.\n\"\"\"\n\nimport logging\n\n#logging.basicConfig(level=10)\n\nimport numpy as np\n\nfrom ctypes import *\nimport ctree.np\n\nfrom ctree.frontend import get_ast\nfrom ctree.c.nodes import *\nfrom ctree.transformations import *\nfrom ctree.jit import LazySpecializedFunction\nfrom ctree.jit import ConcreteSpecializedFunction\nfrom ctree.types import get_ctype\n\n# ---------------------------------------------------------------------------\n# Specializer code\n\n\nclass OpTranslator(LazySpecializedFunction):\n    def args_to_subconfig(self, args):\n        \"\"\"\n        Analyze arguments and return a 'subconfig', a hashable object\n        that classifies them. Arguments with identical subconfigs\n        might be processed by the same generated code.\n        \"\"\"\n        A = args[0]\n        return {\n            'ptr': np.ctypeslib.ndpointer(A.dtype, A.ndim, A.shape),\n        }\n\n    def transform(self, py_ast, program_config):\n        \"\"\"\n        Convert the Python AST to a C AST according to the directions\n        given in program_config.\n        \"\"\"\n        arg_config, tuner_config = program_config\n        array_type = arg_config['ptr']\n        nItems = np.prod(array_type._shape_)\n        inner_type = array_type._dtype_.type()\n\n        tree = CFile(\"generated\", [\n            py_ast.body[0],\n            FunctionDecl(None, \"apply_all\",\n                         params=[SymbolRef(\"A\", array_type())],\n                         defn=[\n                             For(Assign(SymbolRef(\"i\", c_int()), Constant(0)),\n                                 Lt(SymbolRef(\"i\"), Constant(nItems)),\n                                 PostInc(SymbolRef(\"i\")),\n                                 [\n                                     Assign(ArrayRef(SymbolRef(\"A\"), SymbolRef(\"i\")),\n                                            FunctionCall(SymbolRef(\"apply\"), [ArrayRef(SymbolRef(\"A\"),\n                                                                                       SymbolRef(\"i\"))])),\n                                 ]),\n                         ]\n            ),\n        ])\n\n        tree = PyBasicConversions().visit(tree)\n\n        apply_one = tree.find(FunctionDecl, name=\"apply\")\n        apply_one.set_static().set_inline()\n        apply_one.return_type = inner_type\n        apply_one.params[0].type = inner_type\n\n        entry_point_typesig = tree.find(FunctionDecl, name=\"apply_all\").get_type()\n        print(\"FUNCTYPE\", entry_point_typesig._restype_, entry_point_typesig._argtypes_)\n\n        proj = Project([tree])\n        return ArrayFn().finalize(\"apply_all\", proj, entry_point_typesig)\n\nclass ArrayFn(ConcreteSpecializedFunction):\n    def finalize(self, entry_point_name, project_node, entry_typesig):\n        self._c_function = self._compile(entry_point_name, project_node, entry_typesig)\n        return self\n\n    def __call__(self, A):\n        return self._c_function(A)\n\nclass ArrayOp(object):\n    \"\"\"\n    A class for managing independent operation on elements\n    in numpy arrays.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Instantiate translator.\"\"\"\n        self.c_apply_all = OpTranslator(get_ast(self.apply))\n\n    def __call__(self, A):\n        \"\"\"Apply the operator to the arguments via a generated function.\"\"\"\n        return self.c_apply_all(A)\n\n\n# ---------------------------------------------------------------------------\n# User code\n\nclass Doubler(ArrayOp):\n    \"\"\"Double elements of the array.\"\"\"\n\n    def apply(n):\n        return n * 2\n\n\ndef py_doubler(A):\n    A *= 2\n\n\ndef main():\n    c_doubler = Doubler()\n\n    # doubling doubles\n    actual_d = np.ones(12, dtype=np.float64)\n    expected_d = np.ones(12, dtype=np.float64)\n    c_doubler(actual_d)\n    py_doubler(expected_d)\n    np.testing.assert_array_equal(actual_d, expected_d)\n\n    # doubling floats\n    actual_f = np.ones(13, dtype=np.float32)\n    expected_f = np.ones(13, dtype=np.float32)\n    c_doubler(actual_f)\n    py_doubler(expected_f)\n    np.testing.assert_array_equal(actual_f, expected_f)\n\n    # doubling ints\n    actual_i = np.ones(14, dtype=np.int32)\n    expected_i = np.ones(14, dtype=np.int32)\n    c_doubler(actual_i)\n    py_doubler(expected_i)\n    np.testing.assert_array_equal(actual_i, expected_i)\n\n    # demonstrate caching\n    c_doubler(actual_i)\n    c_doubler(actual_i)\n    py_doubler(expected_i)\n    py_doubler(expected_i)\n    np.testing.assert_array_equal(actual_i, expected_i)\n\n    print(\"Success.\")\n\n\nif __name__ == '__main__':\n    main()\n","sub_path":"examples/ArrayDoubler.py","file_name":"ArrayDoubler.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"617997443","text":"\nimport sklearn\nimport pandas as pd\nfrom sklearn import preprocessing\nimport sklearn.linear_model\nfrom sklearn.linear_model import LogisticRegression\n\ndef label_to_int(x,mapping):\n    return mapping[x]\n\nif __name__ == \"__main__\":\n\n    #folder_to_save = \"results\"\n    data = pd.read_csv(\"./data/iris.csv\")\n    label_encoder    = preprocessing.OneHotEncoder()\n    labels_colname   = data.columns[-1]\n    Y                = data[labels_colname]\n    label_dict       = {name:id for id, name in  enumerate(Y.unique())}\n    Y                = Y.apply(label_to_int, args= (label_dict,))\n    X                = data[data.columns[1:-1]]\n    print(\"\\n\\t\\tmodified after image\")\n    print(\"\\nTraining model...\")\n    logreg = LogisticRegression(C=1e5, solver='lbfgs', multi_class='multinomial')\n    logreg.fit(X, Y)\n    y_hat = logreg.predict(X)\n    result = pd.DataFrame({\"predictions\": y_hat})\n    print(\"\\nModel trained\")\n    result.to_csv(\"result.csv\", index=False)\n    print(\"\\nResults saved\\n\")\n\n","sub_path":"docker/container_examples/6_python_save_interactive/model_training.py","file_name":"model_training.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"617516946","text":"#!/usr/bin/env python3\nfrom flask import Flask,render_template,jsonify,redirect\nfrom flask_restful import reqparse\nfrom random import randint\nimport requests\nimport json\nimport os\n\n# print(\"Test print\")\n# print(os.environ['db_host'])\n# print(os.environ['db_port'])\n# print(os.environ['db_path'])\n\napp = Flask(__name__)\nwith open('config/setting.json') as config_file:\n    setting = json.load(config_file)\n    config_file.close()\n\n@app.route('/')\ndef homepage():\n    if len(setting['database-service']) == 0:\n        return render_template('error.html')\n\n\n    index = randint(0,len(setting['database-service'])-1)\n    temp = setting['database-service'][index]\n    url = \"http://\"+temp['host']+\":\"+temp['port']+\"/\"+temp['path']\n    result = requests.get(url).json()\n    #print(result)\n    result.append(setting['database-service'])\n    return render_template('index.html',result = result)\n\n@app.route('/getdata',methods=['GET'])\ndef fetch_data():\n    index = randint(0,len(setting['database-service'])-1)\n    temp = setting['database-service'][index]\n    url = \"http://\"+temp['host']+\":\"+temp['port']+\"/\"+temp['path']\n    print(url)\n    result = requests.get(url).json()\n    #print(result)\n    print(result)\n    return jsonify(result)\n\n@app.route('/add_dbservice',methods=[\"POST\"])\ndef add_service():\n    parser = reqparse.RequestParser()\n    parser.add_argument('host', type=str, help= \"host can't null\")\n    parser.add_argument('port', type=str, help= \"port can't null\")\n    parser.add_argument('path', type=str, help= \"path can't null\")\n    args = parser.parse_args()\n    new_service = {}\n    new_service[\"host\"] = args[\"host\"]\n    new_service[\"port\"] = args[\"port\"]\n    new_service[\"path\"] = args[\"path\"]\n    setting['database-service'].append(new_service)\n    with open('config/setting.json', 'w', encoding='utf-8') as config_file:\n        json.dump(setting, config_file, ensure_ascii=False, indent=2)\n        config_file.close()\n    return redirect('/')\n\n@app.route('/add_database',methods=[\"POST\"])\ndef add_database():\n    parser = reqparse.RequestParser()\n    parser.add_argument('db_name', type=str, help= \"db_name can't be null\")\n    parser.add_argument('host', type=str, help= \"host can't be null\")\n    parser.add_argument('user', type=str, help= \"user can't be null\")\n    parser.add_argument('passwd', type=str, help= \"passwd can't be null\")\n    args = parser.parse_args()\n    \n    with open('config/setting.json') as config_file:\n        setting = json.load(config_file)\n        config_file.close()\n    temp = setting['database-service']\n    print(temp)\n    for service in temp:\n        url = \"http://\"+service['host']+\":\"+service['port']+\"/\"+service['path']\n        requests.post(url,data=[(\"db_name\",args[\"db_name\"]),(\"host\",args[\"host\"]),(\"user\",args[\"user\"]),(\"passwd\",args[\"passwd\"])])\n    return redirect('/')\n\n@app.route('/add_cache',methods=[\"POST\"])\ndef add_cache():\n    parser = reqparse.RequestParser()\n    parser.add_argument('host', type=str, help= \"host can't be null\")\n    parser.add_argument('port', type=str, help= \"port can't be null\")\n    parser.add_argument('path', type=str, help= \"path can't be null\")\n    args = parser.parse_args()\n\n    with open('config/setting.json') as config_file:\n        setting = json.load(config_file)\n        config_file.close()\n    temp = setting['database-service']\n    for service in temp:\n        url = \"http://\"+service['host']+\":\"+service['port']+\"/\"+service['path']\n        requests.put(url,data=[(\"host\",args[\"host\"]),(\"port\",args[\"port\"]),(\"path\",args[\"path\"])])\n    return redirect('/')\n\n@app.route('/defragment',methods=[\"GET\"])\ndef defragment():\n    index = 0\n    temp = setting['database-service'][index]\n    url = \"http://\"+temp['host']+\":\"+temp['port']+\"/\"+temp['path']\n    requests.patch(url)\n    return redirect('/')\n\n@app.route('/delete_database',methods=[\"POST\"])\ndef delete_database():\n    print(\"<------delete database------>\")\n    parser = reqparse.RequestParser()\n    parser.add_argument('host', type=str, help=\"host can't be null\")\n    args = parser.parse_args()\n\n    with open('config/setting.json') as config_file:\n        setting = json.load(config_file)\n        config_file.close()\n    temp = setting['database-service']\n    # print(temp)\n    for service in temp:\n        url = \"http://\"+service['host']+\":\"+service['port']+\"/\"+service['path']\n        requests.delete(url,data=[(\"host\",args['host'])])\n    return redirect('/')\n\n@app.route('/delete_cache',methods=['POST'])\ndef delete_cache():\n    print(\"<-----delete cache----->\")\n    parser = reqparse.RequestParser()\n    parser.add_argument('host',type=str,help=\"host can't be null\")\n    args = parser.parse_args()\n\n    with open('config/setting.json') as config_file:\n        setting = json.load(config_file)\n        config_file.close()\n    temp = setting['database-service']\n    for service in temp:\n        url = \"http://\"+service['host']+\":\"+service['port']+'/'+service['path']\n        requests.options(url,data=[(\"host\",args['host'])])\n    return redirect('/')\n\n\napp.run(host='0.0.0.0',port=setting['management']['port'],debug=True)\n","sub_path":"Management-service/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"382620266","text":"__author__ = 'Yin'\nfrom pymongo import MongoClient\nfrom common import get_mode_share_by_distance, berkeley_area, Inside_polygon\nfrom get_database import get_section_db\nfrom pymongo import GEOSPHERE\nfrom dateutil import parser\n\n\ndef get_berkeley_sections():\n    Sections = get_section_db()\n    list_of_sections=[]\n    for section in Sections.find():\n        if section['section_start_point']!=None and section['section_end_point']!=None and \\\n            Inside_polygon(section['section_start_point'],berkeley_area()) and \\\n                Inside_polygon(section['section_end_point'],berkeley_area()):\n            list_of_sections.append(section)\n    return list_of_sections\n\ndef get_berkeley_mode_share_by_distance(start,end):\n    # start = datetime(2014, 3, 20)\n    # end = datetime(2014, 3, 21)\n    spec={\"$and\":[{\"section_start_datetime\": {\"$gte\": start, \"$lt\": end}},{ \"In_UCB\" :True}]}\n    return get_mode_share_by_distance(spec)\n\n","sub_path":"CFC_WebApp/main/Berkeley.py","file_name":"Berkeley.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"393866119","text":"import os\nimport torch\nimport torchvision\nimport numpy as np\nimport argparse\n\nfrom models.poseMF_shapeGaussian_net import PoseMFShapeGaussianNet\nfrom models.smpl_official import SMPL\nfrom models.pose2D_hrnet import PoseHighResolutionNet\nfrom models.canny_edge_detector import CannyEdgeDetector\n\nfrom configs.poseMF_shapeGaussian_net_config import config\nfrom configs.pose2D_hrnet_config import pose2D_hrnet_config\nfrom configs import paths\n\nfrom predict.predict_poseMF_shapeGaussian_net import predict_poseMF_shapeGaussian_net\n\n\ndef run_predict(device,\n                image_dir,\n                save_dir,\n                already_cropped_images=False,\n                visualise_samples=False,\n                visualise_uncropped=False,\n                joints2Dvisib_threshold=0.75):\n\n    # ------------------------- Load Models -------------------------\n    if not already_cropped_images:\n        # Bounding box / Object detection model\n        object_detect_model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True).to(device)\n    else:\n        object_detect_model = None\n\n    # HRNet model for 2D joint detection\n    hrnet_model = PoseHighResolutionNet(pose2D_hrnet_config).to(device)\n    hrnet_checkpoint = torch.load(paths.HRNET_WEIGHTS, map_location=device)\n    hrnet_model.load_state_dict(hrnet_checkpoint, strict=False)\n    print('\\nLoaded HRNet weights from', paths.HRNET_WEIGHTS)\n\n    # Edge detector\n    edge_detect_model = CannyEdgeDetector(non_max_suppression=config.DATA.EDGE_NMS,\n                                          gaussian_filter_std=config.DATA.EDGE_GAUSSIAN_STD,\n                                          gaussian_filter_size=config.DATA.EDGE_GAUSSIAN_SIZE,\n                                          threshold=config.DATA.EDGE_THRESHOLD).to(device)\n\n    # SMPL model\n    smpl_model = SMPL(paths.SMPL,\n                      batch_size=1,\n                      num_betas=config.MODEL.NUM_SMPL_BETAS).to(device)\n    smpl_immediate_parents = smpl_model.parents.tolist()\n\n    # 3D shape and pose distribution predictor\n    pose_shape_dist_model = PoseMFShapeGaussianNet(smpl_parents=smpl_immediate_parents,\n                                                   config=config).to(device)\n    checkpoint = torch.load(paths.POSE_SHAPE_NET_WEIGHTS, map_location=device)\n    pose_shape_dist_model.load_state_dict(checkpoint['best_model_state_dict'])\n    print('Loaded Distribution Predictor weights from', paths.POSE_SHAPE_NET_WEIGHTS)\n\n    # ------------------------- Predict -------------------------\n    torch.manual_seed(0)\n    np.random.seed(0)\n    predict_poseMF_shapeGaussian_net(pose_shape_model=pose_shape_dist_model,\n                                     pose_shape_config=config,\n                                     smpl_model=smpl_model,\n                                     hrnet_model=hrnet_model,\n                                     hrnet_config=pose2D_hrnet_config,\n                                     edge_detect_model=edge_detect_model,\n                                     device=device,\n                                     image_dir=image_dir,\n                                     save_dir=save_dir,\n                                     object_detect_model=object_detect_model,\n                                     joints2Dvisib_threshold=joints2Dvisib_threshold,\n                                     visualise_uncropped=visualise_uncropped,\n                                     visualise_samples=visualise_samples)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--image_dir', '-I', type=str)\n    parser.add_argument('--save_dir', '-S', type=str)\n    parser.add_argument('--cropped_images', '-C', action='store_true', help='Images already cropped and centred.')\n    parser.add_argument('--visualise_samples', '-VS', action='store_true')\n    parser.add_argument('--visualise_uncropped', '-VU', action='store_true')\n    parser.add_argument('--joints2Dvisib_threshold', '-T', type=float, default=0.75)\n    parser.add_argument('--gpu', type=int, default=0)\n    args = parser.parse_args()\n\n    os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"  # see issue #152\n    os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu)\n    device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n    print('\\nDevice: {}'.format(device))\n\n    if not os.path.exists(args.save_dir):\n        os.makedirs(args.save_dir)\n\n    run_predict(device=device,\n                image_dir=args.image_dir,\n                save_dir=args.save_dir,\n                already_cropped_images=args.cropped_images,\n                visualise_samples=args.visualise_samples,\n                visualise_uncropped=args.visualise_uncropped,\n                joints2Dvisib_threshold=args.joints2Dvisib_threshold)\n\n\n\n","sub_path":"run_predict.py","file_name":"run_predict.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"32690674","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport ckeditor.fields\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('projects', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AlterModelOptions(\n            name='projectpost',\n            options={'ordering': ['-publish_date'], 'verbose_name': 'Project', 'verbose_name_plural': 'Projects'},\n        ),\n        migrations.AlterModelOptions(\n            name='projects',\n            options={'ordering': ['-online', '-modified'], 'verbose_name': 'Project page', 'verbose_name_plural': 'Project pages'},\n        ),\n        migrations.AddField(\n            model_name='projects',\n            name='internal_name',\n            field=models.CharField(help_text='This name is used to differentiate project pages internally.', max_length=126, null=True),\n        ),\n        migrations.AddField(\n            model_name='projects',\n            name='online',\n            field=models.BooleanField(default=False),\n        ),\n        migrations.AlterField(\n            model_name='projectpost',\n            name='content_de',\n            field=ckeditor.fields.RichTextField(help_text='Image css class names: class=\"img_left img-rounded img-responsive\" OR class=\"img_center img-rounded img-responsive\"', null=True, blank=True),\n        ),\n        migrations.AlterField(\n            model_name='projectpost',\n            name='content_tr',\n            field=ckeditor.fields.RichTextField(help_text='Image css class names: class=\"img_left img-rounded img-responsive\" OR class=\"img_center img-rounded img-responsive\"', null=True, blank=True),\n        ),\n        migrations.AlterField(\n            model_name='projectpost',\n            name='slug_de',\n            field=models.SlugField(null=True, editable=False, max_length=200, blank=True, unique=True),\n        ),\n        migrations.AlterField(\n            model_name='projectpost',\n            name='slug_tr',\n            field=models.SlugField(null=True, editable=False, max_length=200, blank=True, unique=True),\n        ),\n        migrations.AlterField(\n            model_name='projectpost',\n            name='title_de',\n            field=models.CharField(max_length=200, unique=True, null=True, blank=True),\n        ),\n        migrations.AlterField(\n            model_name='projectpost',\n            name='title_tr',\n            field=models.CharField(max_length=200, unique=True, null=True, blank=True),\n        ),\n    ]\n","sub_path":"projects/migrations/0002_auto_20151004_1445.py","file_name":"0002_auto_20151004_1445.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"294401635","text":"#!/usr/bin/python3\n\"\"\"unittests for Rectangle class\"\"\"\nimport unittest\nimport json\nimport sys\nfrom io import StringIO\nimport io\nimport os\n\nfrom models.base import Base\nfrom models.rectangle import Rectangle\nfrom models.square import Square\n\nclass TestRectangle(unittest.TestCase):\n    def test_rectangle_exists(self):\n        r0 = Rectangle(1, 2)\n        self.assertIsInstance(r0, Base)\n        self.assertIsNot(r0, Base)\n        r1 = Rectangle(1, 2, 3)\n        self.assertIsInstance(r1, Base)\n        self.assertIsNot(r1, Base)\n        r2 = Rectangle(1, 2, 3, 4)\n        self.assertIsInstance(r2, Base)\n        self.assertIsNot(r2, Base)\n        with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n            r3 = Rectangle(\"1\", 2)\n        with self.assertRaisesRegex(TypeError, \"height must be an integer\"):\n            r4 = Rectangle(1, \"2\")\n        with self.assertRaisesRegex(TypeError, \"x must be an integer\"):\n            r5 = Rectangle(1, 2, \"3\")\n        with self.assertRaisesRegex(TypeError, \"y must be an integer\"):\n            r6 = Rectangle(1, 2, 3, \"4\")\n        r7 = Rectangle(1, 2, 3, 4, 5)\n        self.assertIsInstance(r7, Base)\n        self.assertIsNot(r7, Base)\n        with self.assertRaisesRegex(ValueError, \"width must be > 0\"):\n            r8 = Rectangle(-1, 2)\n        with self.assertRaisesRegex(ValueError, \"height must be > 0\"):\n            r9 = Rectangle(1, -2)\n        with self.assertRaisesRegex(ValueError, \"width must be > 0\"):\n            r10 = Rectangle(0, 2)\n        with self.assertRaisesRegex(ValueError, \"height must be > 0\"):\n            r11 = Rectangle(1, 0)\n        with self.assertRaisesRegex(ValueError, \"x must be >= 0\"):\n            r12 = Rectangle(1, 2, -3)\n        with self.assertRaisesRegex(ValueError, \"y must be >= 0\"):\n            r13 = Rectangle(1, 2, 3, -4)\n\n    def test_area(self):\n        r1 = Rectangle(3, 2)\n        self.assertEqual(r1.area(), 6)\n        r2 = Rectangle(2, 10)\n        self.assertEqual(r2.area(), 20)\n        r3 = Rectangle(8, 7, 0, 0, 12)\n        self.assertEqual(r3.area(), 56)\n\n    def test_str_(self):\n        Base._Base__nb_objects = 0\n        r1 = Rectangle(4, 6, 2, 1, 12)\n        self.assertEqual(r1.__str__(), \"[Rectangle] (12) 2/1 - 4/6\")\n        r2 = Rectangle(5, 5, 1)\n        self.assertEqual(r2.__str__(), \"[Rectangle] (1) 1/0 - 5/5\")\n\n    def test_display(self):\n        output = io.StringIO()\n        sys.stdout = output\n        Rectangle(2, 4).display()\n        sys.stdout = sys.__stdout__\n        self.assertEqual(output.getvalue(), '##\\n##\\n##\\n##\\n')\n        output = io.StringIO()\n        sys.stdout = output\n        Rectangle(2, 4, 1, 2).display()\n        sys.stdout = sys.__stdout__\n        self.assertEqual(output.getvalue(), '\\n\\n ##\\n ##\\n ##\\n ##\\n')\n        r = Rectangle(1, 2, 3, 4)\n        with self.assertRaises(TypeError):\n            r.display(1)\n        with self.assertRaises(TypeError):\n            r.display([1, 2])\n\n    def test_to_dictionary(self):\n        shape_dict = {'x': 1, 'y': 9, 'id': 1, 'height': 2, 'width': 10}\n        r1 = Rectangle(10, 2, 1, 9, 1)\n        self.assertEqual(r1.to_dictionary(), shape_dict)\n        with self.assertRaises(TypeError):\n            r1.to_dictionary(1)\n\n    def test_update(self):\n        r1 = Rectangle(10, 10, 10, 10)\n        r1.update(89)\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 10/10 - 10/10\")\n        r1.update(89, 1)\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 10/10 - 1/10\")\n        r1.update(89, 1, 2)\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 10/10 - 1/2\")\n        r1.update(89, 1, 2, 3)\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 3/10 - 1/2\")\n        r1.update(89, 1, 2, 3, 4)\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 3/4 - 1/2\")\n        r1.update(**{ 'id': 89 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 3/4 - 1/2\")\n        r1.update(**{ 'id': 89, 'width': 1 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 3/4 - 1/2\")\n        r1.update(**{ 'id': 89, 'width': 1, 'height': 2, 'x': 3, 'y': 4 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 3/4 - 1/2\")\n\n    def test_create(self):\n        r1 = Rectangle(3, 5, 1)\n        r1.create(**{ 'id': 89 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (3) 1/0 - 3/5\")\n        r1.create(**{ 'id': 89, 'width': 1 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (3) 1/0 - 3/5\")\n        r1.update(**{ 'id': 89, 'width': 1, 'height': 2 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 1/0 - 1/2\")\n        r1.create(**{ 'id': 89, 'width': 1, 'height': 2, 'x': 3 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 1/0 - 1/2\")\n        Rectangle.create(**{ 'id': 89, 'width': 1, 'height': 2, 'x': 3, 'y': 4 })\n        self.assertEqual(r1.__str__(), \"[Rectangle] (89) 1/0 - 1/2\")\n\n\n    def test_save_to_file(self):\n        r1 = Rectangle(10, 7, 2, 8)\n        r2 = Rectangle(2, 7, 2, 8)\n        r1.save_to_file([r1, r2])\n        a = os.path.exists(\"{}.json\".format(r1.__class__.__name__))\n        with open(\"Rectangle.json\", \"r\", encoding=\"utf-8\") as f:\n            data = f.read()\n        data = json.loads(data)\n        self.assertEqual(data, [r1.to_dictionary(), r2.to_dictionary()])\n        self.assertTrue(a)\n        r1.save_to_file([])\n        a = os.path.exists(\"{}.json\".format(r1.__class__.__name__))\n        with open(\"Rectangle.json\", \"r\", encoding=\"utf-8\") as f:\n            data = f.read()\n        data = json.loads(data)\n        self.assertEqual(data, [])\n        self.assertTrue(a)\n        r1.save_to_file(None)\n        a = os.path.exists(\"{}.json\".format(r1.__class__.__name__))\n        with open(\"Rectangle.json\", \"r\", encoding=\"utf-8\") as f:\n            data = f.read()\n        data = json.loads(data)\n        self.assertEqual(data, [])\n        self.assertTrue(a)\n\n    def test_load_from_file(self):\n        pass\n","sub_path":"0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py","file_name":"test_rectangle.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"441891113","text":"# -*- coding: utf-8 -*-\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog, QApplication\n\n\nclass Ui_MainWindow(object):\n    def setupUi(self, MainWindow):\n        MainWindow.setObjectName(\"MainWindow\")\n        MainWindow.resize(775, 721)\n        self.centralwidget = QtWidgets.QWidget(MainWindow)\n        self.centralwidget.setObjectName(\"centralwidget\")\n        self.pushButton_openImage = QtWidgets.QPushButton(self.centralwidget)\n        self.pushButton_openImage.setGeometry(QtCore.QRect(70, 50, 93, 28))\n        self.pushButton_openImage.setObjectName(\"pushButton_openImage\")\n        self.label_image = QtWidgets.QLabel(self.centralwidget)\n        self.label_image.setGeometry(QtCore.QRect(200, 50, 321, 231))\n        self.label_image.setFrameShape(QtWidgets.QFrame.Box)\n        self.label_image.setObjectName(\"label_image\")\n        self.label_image.setScaledContents(True)  # 图片填充整个框\n        self.pushButton_saveImage = QtWidgets.QPushButton(self.centralwidget)\n        self.pushButton_saveImage.setGeometry(QtCore.QRect(70, 100, 93, 28))\n        self.pushButton_saveImage.setObjectName(\"pushButton_saveImage\")\n        self.pushButton_openFile = QtWidgets.QPushButton(self.centralwidget)\n        self.pushButton_openFile.setGeometry(QtCore.QRect(70, 390, 101, 31))\n        self.pushButton_openFile.setObjectName(\"pushButton_openFile\")\n        self.label_txt = QtWidgets.QLabel(self.centralwidget)\n        self.label_txt.setGeometry(QtCore.QRect(200, 450, 341, 201))\n        self.label_txt.setFrameShape(QtWidgets.QFrame.Box)\n        self.label_txt.setObjectName(\"label_txt\")\n        self.pushButton_saveFile = QtWidgets.QPushButton(self.centralwidget)\n        self.pushButton_saveFile.setGeometry(QtCore.QRect(70, 450, 101, 28))\n        self.pushButton_saveFile.setObjectName(\"pushButton_saveFile\")\n        self.label_filePath = QtWidgets.QLabel(self.centralwidget)\n        self.label_filePath.setGeometry(QtCore.QRect(200, 380, 291, 61))\n        self.label_filePath.setWordWrap(True)\n        self.label_filePath.setObjectName(\"label_filePath\")\n        self.pushButton_openDirectory = QtWidgets.QPushButton(self.centralwidget)\n        self.pushButton_openDirectory.setGeometry(QtCore.QRect(70, 320, 93, 28))\n        self.pushButton_openDirectory.setObjectName(\"pushButton_openDirectory\")\n        self.label_directoryPath = QtWidgets.QLabel(self.centralwidget)\n        self.label_directoryPath.setGeometry(QtCore.QRect(200, 310, 291, 61))\n        self.label_directoryPath.setWordWrap(True)\n        self.label_directoryPath.setObjectName(\"label_directoryPath\")\n        self.label_imagePath = QtWidgets.QLabel(self.centralwidget)\n        self.label_imagePath.setGeometry(QtCore.QRect(570, 60, 150,100))\n        self.label_imagePath.setObjectName(\"label_imagePath\")\n        self.label_imagePath.setWordWrap(True)\n        MainWindow.setCentralWidget(self.centralwidget)\n        self.menubar = QtWidgets.QMenuBar(MainWindow)\n        self.menubar.setGeometry(QtCore.QRect(0, 0, 775, 26))\n        self.menubar.setObjectName(\"menubar\")\n        MainWindow.setMenuBar(self.menubar)\n        self.statusbar = QtWidgets.QStatusBar(MainWindow)\n        self.statusbar.setObjectName(\"statusbar\")\n        MainWindow.setStatusBar(self.statusbar)\n\n        self.retranslateUi(MainWindow)\n        QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n        self.pushButton_openImage.clicked.connect(self.openImage)\n        self.pushButton_saveImage.clicked.connect(self.saveImage)\n        self.pushButton_openFile.clicked.connect(self.openTextFile)\n        self.pushButton_saveFile.clicked.connect(self.saveTextFile)\n        self.pushButton_openDirectory.clicked.connect(self.openDirectory)\n\n\n    def retranslateUi(self, MainWindow):\n        _translate = QtCore.QCoreApplication.translate\n        MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n        self.pushButton_openImage.setText(_translate(\"MainWindow\", \"打开图像\"))\n        self.label_image.setText(_translate(\"MainWindow\", \"图片\"))\n        self.pushButton_saveImage.setText(_translate(\"MainWindow\", \"保存图像\"))\n        self.pushButton_openFile.setText(_translate(\"MainWindow\", \"打开文件\"))\n        self.label_txt.setText(_translate(\"MainWindow\", \"文本内容\"))\n        self.pushButton_saveFile.setText(_translate(\"MainWindow\", \"保存文件\"))\n        self.label_filePath.setText(_translate(\"MainWindow\", \"文件路径\"))\n        self.pushButton_openDirectory.setText(_translate(\"MainWindow\", \"打开文件夹\"))\n        self.label_directoryPath.setText(_translate(\"MainWindow\", \"文件夹路径\"))\n        self.label_imagePath.setText(_translate(\"MainWindow\", \"图片路径\"))\n\n    def openImage(self):  # 选择本地图片上传\n        global imgName  # 这里为了方便别的地方引用图片路径,我们把它设置为全局变量\n        imgName, imgType = QFileDialog.getOpenFileName(self.centralwidget, \"打开图片\", \"\", \"*.jpg;;*.png;;All Files(*)\")    # 弹出一个文件选择框,第一个返回值imgName记录选中的文件路径+文件名,第二个返回值imgType记录文件的类型\n        jpg = QtGui.QPixmap(imgName).scaled(self.label_image.width(), self.label_image.height())  # 通过文件路径获取图片文件,并设置图片长宽为label控件的长宽\n        self.label_image.setPixmap(jpg)  # 在label控件上显示选择的图片\n        self.label_imagePath.setText(imgName)  # 显示所选图片的本地路径\n\n    def saveImage(self):  # 保存图片到本地\n        screen = QApplication.primaryScreen()\n        pix = screen.grabWindow(self.label_image.winId())\n        fd,type= QFileDialog.getSaveFileName(self.centralwidget, \"保存图片\", \"\", \"*.jpg;;*.png;;All Files(*)\")\n        pix.save(fd)\n\n    def openDirectory(self):  # 打开文件夹(目录)\n        fd = QFileDialog.getExistingDirectory(self.centralwidget, \"选择文件夹\", \"\")\n        self.label_directoryPath.setText(fd)\n\n    def openTextFile(self):  # 选择文本文件上传\n        fd,fp = QFileDialog.getOpenFileName(self.centralwidget, \"选择文件\", \"\", \"*.txt;;All Files(*)\")\n        f=open(fd,'r')\n        self.label_txt.setText(f.read())\n        self.label_filePath.setText(fd)\n        f.close()\n\n    def saveTextFile(self):  # 保存文本文件\n        fd,fp= QFileDialog.getSaveFileName(self.centralwidget, \"保存文件\", \"\", \"*.txt;;All Files(*)\")\n        f=open(fd,'w')\n        f.write(self.label_txt.text())\n        f.close()\n\nif __name__ == \"__main__\":\n    import sys\n    app = QtWidgets.QApplication(sys.argv)\n    formObj = QtWidgets.QMainWindow()\n    ui = Ui_MainWindow()\n    ui.setupUi(formObj)\n    formObj.show()\n    sys.exit(app.exec_())","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":6714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"180463808","text":"# This model is based on the kernel of  Pranav Pandya and andy harless.\n#       https://www.kaggle.com/pranav84/single-lightgbm-in-r-with-75-mln-rows-lb-0-9690\n#       https://www.kaggle.com/aharless/try-pranav-s-r-lgbm-in-python/code\n# I modified code to make it easier for me\n# The actual changed values are the parameters only. I focused on parameter tuning\n# num_leaves :  7  ->  9\n# max_depth  :  4  ->  5\n# subsample  : 0.7 -> 0.9\n\n\n# This is the first version and will be performing additional data sampling and parameter tuning.\n\n\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.model_selection import train_test_split # for validation \nimport lightgbm as lgb\nimport gc # memory \nfrom datetime import datetime # train time checking\nimport numpy as np\nimport zipfile\n\n\nstart = datetime.now()\nVALIDATE = True\nRANDOM_STATE = 50\nVALID_SIZE = 0.3\nMAX_ROUNDS = 1000\nEARLY_STOP = 50\nOPT_ROUNDS = 700\n#skiprows = range(1,109903891)\nskiprows = range(1,9308568)\n#skiprows = range(1,184903890-4000000)\n#nrows = 75000000\nnrows = 45000000\noutput_filename = '/home/burke/song/v6/submission_v6_09.csv'\nmodel_name = '/home/burke/song/v6/modelv6_9.txt'\n\n\ndtypes = {\n        'ip'            : 'uint32',\n        'app'           : 'uint16',\n        'device'        : 'uint16',\n        'os'            : 'uint16',\n        'channel'       : 'uint16',\n        'is_attributed' : 'uint8',\n        'click_id'      : 'uint32'\n        }\n\n\n\ntrain_cols = ['ip','app','device','os', 'channel', 'click_time', 'is_attributed']\nwith zipfile.ZipFile('/home/burke/song/s1.zip', 'r') as myzip:\n    path = myzip.open('mnt/ssd/kaggle-talkingdata2/competition_files/train.csv')\ndf = pd.read_csv(path, iterator=True, chunksize=10000, dtype=dtypes, usecols=train_cols)\ntrain_df = pd.concat([chunk[chunk['click_time'].str.contains(\"2017-11-09\")] for chunk in df])\ndel df\ndel path\nscale_num = round(train_df.is_attributed.value_counts().reset_index()['is_attributed'][0]/train_df.is_attributed.value_counts().reset_index()['is_attributed'][1], 3)\nlen_train = len(train_df)\ngc.collect()\n\ndef click(df):\n    new_feature = 'nextClick'\n    D=2**26\n    df['category'] = (df['ip'].astype(str) + \"_\" + df['app'].astype(str) + \"_\" + df['device'].astype(str) + \"_\" + df['os'].astype(str)).apply(hash) % D\n    click_buffer= np.full(D, 3000000000, dtype=np.uint32)\n    df['epochtime']= df['click_time'].astype(np.int64) // 10 ** 9\n    next_clicks= []\n    for category, t in zip(reversed(df['category'].values), reversed(df['epochtime'].values)):\n        next_clicks.append(click_buffer[category]-t)\n        click_buffer[category]= t\n    del(click_buffer)\n    QQ= list(reversed(next_clicks))\n    df.drop(['epochtime','category','click_time'], axis=1, inplace=True)\n    df[new_feature] = pd.Series(QQ).astype('float32')\n    #df[new_feature+'_shift'] = df[new_feature].shift(+1).values\n    #newname = [new_feature, new_feature+'_shift']\n    newname = [new_feature, new_feature]\n    return df, newname\ndef do_next_prev_Click( df,agg_suffix, agg_type='float32'):\n    print('Extracting new features...')\n    \n    df['hour'] = pd.to_datetime(df.click_time).dt.hour.astype('int8')\n    df['day'] = pd.to_datetime(df.click_time).dt.day.astype('int8')\n    \n    #### New added\n    df['minute'] = pd.to_datetime(df.click_time).dt.minute.astype('int8')\n    df['second'] = pd.to_datetime(df.click_time).dt.second.astype('int8')\n    print(\"Extracting {0} time calculation features...\".format(agg_suffix))\n    \n    GROUP_BY_NEXT_CLICKS = [\n    {'groupby': ['ip', 'app', 'device', 'os', 'channel']},\n    {'groupby': ['ip', 'os', 'device']},\n    {'groupby': ['ip', 'app']},\n    {'groupby': ['ip', 'channel']},\n    {'groupby': ['ip', 'os', 'device', 'app']}\n    ]\n    add_p = []\n    # Calculate the time to next click for each group\n    for spec in GROUP_BY_NEXT_CLICKS:\n    \n       # Name of new feature\n        new_feature = '{}_{}'.format('_'.join(spec['groupby']),agg_suffix)    \n    \n        # Unique list of features to select\n        all_features = spec['groupby'] + ['click_time']\n\n        # Run calculation\n        print(\"Grouping by {0}, and saving time to {1} in: {2}\".format(spec['groupby'], agg_suffix, new_feature))\n        if agg_suffix==\"nextClick\":\n            df[new_feature] = (df[all_features].groupby(spec[\n            'groupby']).click_time.shift(-1) - df.click_time).dt.seconds.astype(agg_type)\n        elif agg_suffix== \"prevClick\":\n            df[new_feature] = (df.click_time - df[all_features].groupby(spec[\n                'groupby']).click_time.shift(+1) ).dt.seconds.astype(agg_type)\n        gc.collect()\n        add_p.append(new_feature)\n    df.drop(['hour', 'day', 'minute', 'second'], axis=1, inplace=True)\n    return df, add_p\ndef group_by_click(lis_p, data):\n    print('group by...')\n    newname = '{}_click_time_gap'.format('_'.join(lis_p))\n    all_p = lis_p[:]\n    all_p.append('click_time')\n    data[newname] = data[all_p].groupby(by=lis_p).click_time.transform(lambda x: x.diff().shift(-1)).dt.seconds\n    data[newname] = data[newname].fillna(-1)\n    print('merge...')\n    return data, newname\ndef group_by(lis_p, select_p, data, fuc, agg_type='uint32', show_max=False):\n    print('group by...')\n    newname = '{}'.format('_'.join(lis_p))\n    all_p = lis_p[:]\n    all_p.append(select_p)\n    if fuc == 'cumcount':\n        newname = newname+\"_cumcountBY_\"+select_p\n        gp = data[all_p].groupby(by=lis_p)\n        gp = gp[select_p].cumcount()\n        print('merge...')\n        data[newname] = gp.values\n        del gp\n        if show_max:\n            print( newname + \" max value = \", data[newname].max() )\n        data[newname] = data[newname].astype(agg_type)\n        return data, newname\n    elif fuc == 'count':\n        newname = newname+\"_countBY\"\n        gp = data[lis_p][lis_p].groupby(lis_p).size().rename(newname).to_frame().reset_index()\n        print('merge...')\n        data = data.merge(gp, on=lis_p, how='left')\n        del gp\n        if show_max:\n            print( newname + \" max value = \", data[newname].max() )\n        data[newname] = data[newname].astype(agg_type)\n        return data, newname\n    elif fuc == 'countuniq':\n        newname = newname+\"_countuniqBY_\"+select_p\n        gp = data[all_p].groupby(by=lis_p)\n        gp = gp[select_p].nunique().reset_index().rename(index=str, columns={select_p: newname})\n        print('merge...')\n        data = data.merge(gp, on=lis_p, how='left')\n        del gp\n        if show_max:\n            print( newname + \" max value = \", data[newname].max() )\n        data[newname] = data[newname].astype(agg_type)\n        return data, newname\n    elif fuc == 'var':\n        newname = newname+\"_varBY_\"+select_p\n        gp = data[all_p].groupby(by=lis_p)\n        gp = gp[select_p].var().reset_index().rename(index=str, columns={select_p: newname})\n        print('merge...')\n        data = data.merge(gp, on=lis_p, how='left')\n        del gp\n        if show_max:\n            print( newname + \" max value = \", data[newname].max() )\n        data[newname] = data[newname].astype(agg_type)\n        return data, newname\ndef prep_data( df ):\n    print('data prep...')\n    df['click_time'] = pd.to_datetime(df['click_time'])\n    df, tmp1 = group_by_click(['ip', 'device', 'app'],df)\n    gc.collect()\n    df, tmp2 = group_by_click(['ip', 'channel'],df)\n    gc.collect()\n    df, lis_add_p1 = do_next_prev_Click(df, agg_suffix='nextClick', agg_type='float32')\n    gc.collect()\n    df, lis_add_p2 = do_next_prev_Click(df, agg_suffix='prevClick', agg_type='float32')\n    gc.collect()\n    print('data prep...')\n    df['hour'] = df['click_time'].dt.hour.astype('uint8')\n    df['minute'] = df['click_time'].dt.minute.astype('uint8')\n    df['second'] = df['click_time'].dt.second.astype('uint8')\n    gc.collect()\n    df, tmp3 = group_by(['app','channel', 'hour','minute', 'second' ], 'device', df, 'count', agg_type = 'uint16', show_max=True)\n    #df, tmp4 = group_by(['ip','device', 'hour', 'minute' ], 'app', df, 'count', agg_type = 'uint16', show_max=True)\n    print('data drop...')\n    #df.drop(['second'], axis=1, inplace=True)\n    #df.drop(['minute'], axis=1, inplace=True)\n    gc.collect()\n    #group by\n    df, tmp5 = group_by(['ip'], 'channel', df, 'countuniq', agg_type = 'uint8', show_max=True)\n    gc.collect()\n    df, tmp6 = group_by(['ip'], 'app', df, 'countuniq', agg_type = 'uint8', show_max=True)\n    gc.collect()\n    df, tmp7 = group_by(['ip','os','device'], 'app', df, 'countuniq', agg_type = 'uint8', show_max=True)\n    gc.collect()\n    df, tmp8 = group_by(['app'], 'channel', df, 'countuniq', agg_type = 'uint8', show_max=True)\n    gc.collect()\n    df, tmp9 = group_by(['ip'], 'os', df, 'cumcount', show_max=True)\n    gc.collect()\n    df, lis = click(df)\n    gc.collect()\n    df, tmp10 = group_by(['ip','app'], 'os', df, 'countuniq', agg_type = 'uint16', show_max=True)\n    gc.collect()\n    df, tmp11 = group_by(['ip', 'device', 'os'], 'app', df, 'cumcount', show_max=True)\n    gc.collect()\n    df, tmp12 = group_by(['ip', 'device', 'app'], 'os', df, 'count', show_max=True)\n    gc.collect()\n    df, tmp13 = group_by(['ip', 'hour'], 'os', df, 'count',  show_max=True)\n    gc.collect()\n    df, tmp14 = group_by(['ip', 'app'], 'os', df, 'count', show_max=True)\n    gc.collect()\n    df, tmp15 = group_by(['ip', 'os', 'app'], 'channel', df, 'count', show_max=True)\n    gc.collect()\n    df, tmp16 = group_by(['ip', 'hour', 'device'], 'channel', df, 'count', show_max=True)\n    gc.collect()\n    df, tmp17 = group_by(['ip', 'app', 'os'], 'hour', df, 'var', agg_type='float32', show_max=True)\n    gc.collect()\n    df, tmp18 = group_by(['ip', 'channel'], 'hour', df, 'var', agg_type='float32', show_max=True)\n    gc.collect()\n    df.drop( ['ip'], axis=1, inplace=True )\n    gc.collect()\n    add_p = [tmp1,tmp2,tmp3,tmp5,tmp6,tmp7,tmp8,tmp9,tmp10,tmp11,tmp12,tmp13,tmp14,tmp15,tmp16,tmp17,tmp18]\n    for i in lis:\n        add_p.append(i)\n    for j in lis_add_p1:\n        add_p.append(j)\n    for j in lis_add_p2:\n        add_p.append(j)\n    return df, add_p\n\ntrain_df, app_p = prep_data(train_df)\ngc.collect()\n\nparams = {\n          'boosting_type': 'gbdt',\n          'objective': 'binary',\n          'metric':'auc',\n          'learning_rate': 0.1,\n          'num_leaves': 7,  # we should let it be smaller than 2^(max_depth)\n          'max_depth':3,#  -1 means no limit\n          'min_child_samples': 100,  # Minimum number of data need in a child(min_data_in_leaf)\n          'max_bin': 100,  # Number of bucketed bin for feature values\n          'subsample': 0.7,  # Subsample ratio of the training instance.\n          'subsample_freq': 1,  # frequence of subsample, <=0 means no enable\n          'colsample_bytree': 0.9,  # Subsample ratio of columns when constructing each tree.\n          'min_child_weight': 0,  # Minimum sum of instance weight(hessian) needed in a child(leaf)\n          'min_split_gain': 0,  # lambda_l1, lambda_l2 and min_gain_to_split to regularization\n          'subsample_for_bin': 200000,  # Number of samples for constructing bin\n          'nthread': 8,\n          'verbose': 0,\n          'scale_pos_weight':scale_num, # because training data is extremely unbalanced \n         }\n\ntarget = 'is_attributed'\ncategorical = ['app', 'device', 'os', 'channel', 'hour','minute','second']\napp_p.extend(categorical)\npredictors = app_p\n\n\nif VALIDATE:\n\n    train_df, val_df = train_test_split(train_df, test_size=VALID_SIZE, random_state=RANDOM_STATE, shuffle=True )\n    dtrain = lgb.Dataset(train_df[predictors].values, \n                         label=train_df[target].values,\n                         feature_name=predictors,\n                         categorical_feature=categorical)\n    del train_df\n    gc.collect()\n\n    dvalid = lgb.Dataset(val_df[predictors].values,\n                         label=val_df[target].values,\n                         feature_name=predictors,\n                         categorical_feature=categorical)\n    del val_df\n    gc.collect()\n\n    evals_results = {}\n\n    model = lgb.train(params, \n                      dtrain, \n                      valid_sets=[dtrain, dvalid], \n                      valid_names=['train','valid'], \n                      evals_result=evals_results, \n                      num_boost_round=MAX_ROUNDS,\n                      early_stopping_rounds=EARLY_STOP,\n                      verbose_eval=50, \n                      feval=None)\n\n    del dvalid\n\nelse:\n\n    gc.collect()\n    dtrain = lgb.Dataset(train_df[predictors].values, label=train_df[target].values,\n                          feature_name=predictors,\n                          categorical_feature=categorical\n                          )\n    del train_df\n    gc.collect()\n\n    evals_results = {}\n\n    model = lgb.train(params, \n                      dtrain, \n                      valid_sets=[dtrain], \n                      valid_names=['train'], \n                      evals_result=evals_results, \n                      num_boost_round=OPT_ROUNDS,\n                      verbose_eval=50,\n                      feval=None)\n    \ndel dtrain\ngc.collect()\n#import matplotlib.pyplot as plt\n#f, ax = plt.subplots(figsize=[10,10])\n#lgb.plot_importance(model, ax=ax, max_num_features=len(predictors))\n#plt.title(\"Light GBM Feature Importance\")\n#plt.savefig('feature_import.png')\n\ntest_cols = ['ip','app','device','os', 'channel', 'click_time', 'click_id']\nwith zipfile.ZipFile('/home/burke/song/a1.zip', 'r') as myzip:\n    path1 = myzip.open('test.csv')\ntest_df = pd.read_csv(path1, dtype=dtypes, usecols=test_cols)\ntest_df, app_p2 = prep_data(test_df)\ndel path1\ngc.collect()\nmodel.save_model(model_name)\nsub = pd.DataFrame()\nsub['click_id'] = test_df['click_id']\nsub['is_attributed'] = model.predict(test_df[predictors])\nsub.to_csv(output_filename, index=False, float_format='%.9f')\n\nprint('=='*35)\nprint('============================ Final Report ============================')\nprint('=='*35)\nprint(datetime.now(), '\\n')\nprint('{:^17} : {:}'.format('train time', datetime.now()-start))\nprint('{:^17} : {:}'.format('output file', output_filename))\nprint('{:^17} : {:.5f}'.format('train auc', model.best_score['train']['auc']))\nif VALIDATE:\n    print('{:^17} : {:.5f}\\n'.format('valid auc', model.best_score['valid']['auc']))\n    print('{:^17} : {:}\\n{:^17} : {}\\n{:^17} : {}'.format('VALIDATE', VALIDATE, 'VALID_SIZE', VALID_SIZE, 'RANDOM_STATE', RANDOM_STATE))\nprint('{:^17} : {:}\\n{:^17} : {}\\n{:^17} : {}\\n'.format('MAX_ROUNDS', MAX_ROUNDS, 'EARLY_STOP', EARLY_STOP, 'OPT_ROUNDS', model.best_iteration))\nprint('{:^17} : {:}\\n{:^17} : {}\\n'.format('skiprows', skiprows, 'nrows', nrows))\nprint('{:^17} : {:}\\n{:^17} : {}\\n'.format('variables', predictors, 'categorical', categorical))\nprint('{:^17} : {:}\\n'.format('model params', params))\nprint('=='*35)","sub_path":"SSMP9_6.py","file_name":"SSMP9_6.py","file_ext":"py","file_size_in_byte":14736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"279716723","text":"#coding=utf-8\n\nimport unittest\n\n\"\"\"\n\n645. Set Mismatch\nDescriptionHintsSubmissionsDiscussSolution\nDiscuss Pick One\nThe set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the \nset got duplicated to another number in the set, which results in repetition of one number and loss of another number.\n\nGiven an array nums representing the data status of this set after the error. Your task is to firstly find the number \noccurs twice and then find the number that is missing. Return them in the form of an array.\n\nExample 1:\nInput: nums = [1,2,2,4]\nOutput: [2,3]\nNote:\nThe given array size will in the range [2, 10000].\nThe given array's numbers won't have any order.\n\"\"\"\n\n\nclass Solution(object):\n    def findErrorNums(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: List[int]\n        \"\"\"\n        from collections import Counter\n        val_cnt = Counter(nums)\n        res1 = 0\n        res2 = 0\n        for val, cnt in val_cnt.items():\n            if cnt == 2:\n                res1 = val\n                break\n        n = len(nums)\n        res2 = (1+n)*n/2 + res1 - sum(nums)\n        return [res1, res2]\n\n\nclass SolutionTester(unittest.TestCase):\n    def setUp(self):\n        self.sol = Solution()\n\n    def test_case1(self):\n        nums = [1,2,2,4]\n        answer = [2, 3]\n        result = self.sol.findErrorNums(nums)\n        self.assertEqual(answer, result)\n\n\ndef main():\n    suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)\n    unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == \"__main__\":\n    main()\n\n\n\n#-*- coding:utf-8 -*-\n\n\"\"\"\n\nCount each element. We know the original elements must have been 1, 2, ..., len(A).\nOnce we have the counts, it is easy to scan through and see which element must have occurred twice, and which one never occurred.\n\nIn our implementation, we could also use collections.Counter(A).\n\ndef findErrorNums(self, A):\n    N = len(A)\n    count = [0] * (N+1)\n    for x in A:\n      count[x] += 1\n    for x in xrange(1, len(A)+1):\n        if count[x] == 2:\n            twice = x\n        if count[x] == 0:\n            never = x\n    return twice, never\nBonus solution: Say (x, y) is the desired answer. We know sum(A) - x + y = sum([1, 2, ..., N]), and \nsum(x*x for x in A) - x*x + y*y = sum([1*1, 2*2, ..., N*N]). So we know x-y and x*x-y*y. Dividing the latter by x-y, we \nknow x+y. Hence, we know x and y.\n\ndef findErrorNums(self, A):\n    N = len(A)\n    alpha = sum(A) - N*(N+1)/2\n    beta = (sum(x*x for x in A) - N*(N+1)*(2*N+1)/6) / alpha\n    return (alpha + beta) / 2, (beta - alpha) / 2\n\n\"\"\"","sub_path":"freq/set_mismatch.py","file_name":"set_mismatch.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"635823107","text":"from flask import Flask,jsonify,render_template,request,redirect,url_for\nimport traceback\nimport requests\nimport json\napp=Flask(__name__)\nname_list=[]\n\nresponse_fetch=requests.get('http://3.6.93.159:7883/machstatz/get_all_users')\ndict={\"name\":\"\",\"email\":\"\"}\nfor items in response_fetch.json():\n    dict[\"name\"]=items[\"fist_name\"]+\" \"+items[\"last_name\"]\n    dict[\"email\"]=items[\"email\"]\n    name_list.append(dict)\nlength=len(name_list)\n\n@app.route(\"/\")\ndef home():\n    return render_template('screen_1.html')\n\n\n@app.route(\"/machstatz\")\ndef existing_user():\n    return render_template('delete_existing_user.html',length=length,name_list=name_list)\n\n\n@app.route(\"/machstatz/add_new_user\",methods=['GET','POST'])\ndef add_new_user():\n    resp={\"email\":\"\",\"fist_name\":\"\",\"last_name\":\"\",\"pwd\":\"\",\"username\":\"\"}\n    response={\"message\":\"Created the new user successfully.\",\"status\":\"Success\"}\n    if request.method==\"POST\":\n        resp[\"email\"]=request.form[\"email\"]\n        resp[\"fist_name\"]=request.form[\"fname\"]\n        resp[\"last_name\"]=request.form[\"lname\"]\n        resp[\"pwd\"]=request.form[\"pwd\"]\n        resp[\"username\"]=request.form[\"username\"]\n        for items in response_fetch.json():\n            if items[\"email\"]==resp[\"email\"]:\n                response[\"message\"]=\"User with provided email or username is already exist.\"\n                response[\"status\"]=\"Error\"\n    return response\n\n\n@app.route(\"/machstatz/delete_existing_user\")\ndef delete_existing_user():\n    response={\"message\":\"Unable to delete the user or user may not exist.\",\"status\":\"Error\"}\n    if request.method==\"POST\":\n        enterd_email=request.form[\"email\"]   #(This email needs to be used to delete the user from database which we dont have access to)\n        for item in name_list():\n            if enterd_email==item[\"email\"]:\n                name_list.remove(item)\n                response[\"message\"]=\"User deleted successfully.\"\n                response[\"status\"]=\"Deleted\"\n                \n    return response\n    \n\n\nif __name__=='__main__':\n    app.run(debug=False,host='0.0.0.0')\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"575688094","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tensorflow\nfrom tensorflow.keras.preprocessing import sequence\nimport csv\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Bidirectional, LSTM, Masking, Convolution1D, Dropout, Activation\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport keras\nimport tensorflow\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nimport datetime\nnow = datetime.datetime.now\n\ndef process(temp):\n    min_len = 3000\n    for i in range(11):\n        j = 0\n        while temp[j][i] != '' and j 0:\n                #user = selected_user\n                #print \"Found user %s\" % selected_user\n            #else:\n                #insert = users.insert().values(username = uname, active = True)\n                #connection.execute(insert)\n            #uppdatera sigel\n            #skapa ett userobjekt\n                #insert.execute(username = uname, active = 1)\n        #except Exception as e:\n            #print \"Error trying to load user: \", e\n            #return None\n                \n                #newvalues = users.update().where(users.username == uname).values(active = 1, sigel = sigel).execute()\n                #user = users.select(users.c.username == uname).execute().first()\n                #return user\n            \n    \n\nclass Storage(object):\n    def __init__(self, path):\n        self.path = path\n        if not os.path.exists(self.path):\n            os.makedirs(self.path)\n\n    def save_draft(self, user_id, rec_type, rec_id, json_data, etag):\n        path = construct_path([self.path, user_id, rec_type])\n        create_dir_if_not_exists(path)\n        filename = \"/\".join([path, rec_id])\n        with open(filename, 'w') as f:\n            f.write(json_data)\n\n    def update_draft(self, user_id, rec_type, rec_id, json_data, etag):\n        self.save_draft(user_id, rec_type, rec_id, json_data, etag)\n\n    def get_draft(self, user_id, rec_type, rec_id):\n        path = construct_path([self.path, user_id, rec_type])\n        filename = \"/\".join([path, rec_id])\n        if os.path.exists(filename):\n            with open(filename) as f:\n                return open(filename, 'r').read()\n        else:\n            None\n\n    def delete_draft(self, user_id, rec_type, rec_id):\n        filename = construct_path([self.path, user_id, rec_type, rec_id])\n        if os.path.exists(filename):\n            os.remove(filename)\n\n    def get_drafts(self, user_id):\n        result = {}\n        for root, subFolders, files in os.walk(construct_path([self.path, user_id])):\n            for file in files:\n                f = os.path.join(root,file)\n                result[\"/\".join(f.rsplit(\"/\",2)[-2:])] = f\n        return result\n\n    def get_drafts_as_json(self, user_id):\n        result = {}\n        drafts = []\n        for root, subFolders, files in os.walk(construct_path([self.path, user_id])):\n            for file in files:\n                f = os.path.join(root,file)\n                item = {}\n                item['type'] = f.rsplit(\"/\",2)[-2:-1][0]\n                item['id'] = f.rsplit(\"/\",2)[-1:][0]\n                item['path'] = f\n                drafts.append(item)\n        result['drafts'] = drafts\n        return json.dumps(result)\n\n    def draft_exists(self, rec_type, rec_id):\n        return os.path.exists(\"/\".join([self.path, rect_type, rec_id]))\n\n\ndef construct_path(path_array):\n    return \"/\".join(path_array)\n\ndef create_dir_if_not_exists(path):\n    if not os.path.exists(str(path)):\n        os.makedirs(path)\n\n","sub_path":"storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"135678602","text":"\"\"\"\ngoogle_search.py - Willie Google Search\n\"\"\"\n\nfrom willie.module import commands, example\n\nimport requests\nimport HTMLParser\n\n@commands('g', 'google')\n@example('.g San Francisco')\ndef google_search(bot, trigger):\n    payload = {'q': trigger.group(2)}\n    json_response = requests.get('http://ajax.googleapis.com/ajax/services/search/web?v=1.0', params=payload).json()\n    results = json_response['responseData']['results']\n    if not results:\n    \tbot.say('No results found.')\n    else:\n    \tfirst_result = results[0]\n    \tbot.say(u\"{} - {}\".format(first_result['unescapedUrl'], unescape_html(first_result['titleNoFormatting'])))\n\ndef unescape_html(html_string):\n    return HTMLParser.HTMLParser().unescape(html_string)\n","sub_path":"commonbot/willie/modules/google_search.py","file_name":"google_search.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"492938526","text":"\n\nfrom xai.brain.wordbase.nouns._guava import _GUAVA\n\n#calss header\nclass _GUAVAS(_GUAVA, ):\n\tdef __init__(self,): \n\t\t_GUAVA.__init__(self)\n\t\tself.name = \"GUAVAS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"guava\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_guavas.py","file_name":"_guavas.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"557594108","text":"# def input_reader(filename, dict_params=None, default=True,verbose=True):\n# \t\"\"\"\n# \tRead the text file version of parameters into a dictionary\n# \t- minor: range one parameter for given start, end, and number of separations\n# \t\"\"\"\n\n# \timport numpy as np\n# \timport astropy.constants as const\n# \timport pprint as pp\n\n# \t# Constants setup\n# \tc         = const.c.cgs.value\n# \tAU        = const.au.cgs.value                         # Astronomical Unit       [cm]\n# \tpc        = const.pc.cgs.value                         # Parsec                  [cm]\n# \tMS        = const.M_sun.cgs.value                      # Solar mass              [g]\n# \tLS        = const.L_sun.cgs.value                      # Solar luminosity        [erg/s]\n# \tRS        = const.R_sun.cgs.value                      # Solar radius            [cm]\n# \tG         = const.G.cgs.value                          # Gravitational constant  [cm^3/g/s^2]\n# \tyr        = 60*60*24*365.                              # Years in seconds        [s]\n# \tPI        = np.pi                                      # PI constant\n# \tsigma     = const.sigma_sb.cgs.value                   # Stefan-Boltzmann constant\n# \tmh        = const.m_p.cgs.value + const.m_e.cgs.value  # Mass of Hydrogen atom   [g]\n# \t# Maybe don't need this\n# \tu = dict([('c',c), ('AU',AU), ('pc',pc), ('MS',MS), ('LS',LS), ('RS',RS), ('G',G), ('yr',yr), ('sigma',sigma), ('PI', np.pi), ('mh',mh)])\n\n# \t# if there is no dict_params provided, then I must get the parameters from somewhere\n# \tif dict_params == None:\n# \t\tparams = np.genfromtxt(filename, dtype=None)\n# \t\tdict_params = {}\n# \t\tfor var, val in params:\n# \t\t\tdict_params[var] = val\n# \t\t# Use the default parameters for mostly fixed parameter (e.g. disk)\n# \t\tif default == True:\n# \t\t\tdict_params['M_disk'] = 5e-1\n# \t\t\tdict_params['M_disk_dot'] = 6.5e-7\n# \t\t\tdict_params['beta'] = 1.093\n# \t\t\tdict_params['h100'] = 8.123\n# \t\t\tdict_params['rho_cav'] = 1e-21\n# \t\tif verbose == True:\n# \t\t\tpp.pprint(dict_params)\n# \telse:\n# \t\t# the dict_params can be provided by reading in .prev_params\n# \t\tprint 'The parameters are provided by user'\n# \t\tif verbose == True:\n# \t\t\tpp.pprint(dict_params)\n\n# \treturn dict_params\n\ndef input_reader_table(filename,default=False):\n\t\"\"\"\n\tRead in a table with each model as a row.\n\toutput as a tuple containing dictionary of model parameters\n\t\"\"\"\n\timport numpy as np\n\timport astropy.constants as const\n\n\tmodel = np.genfromtxt(filename, dtype=float, skip_header=1)\n\theader = open(filename,'r').readlines()[0].split()\n\t# output is the tuple that consist all dictionaries of model parameters.\n\t# if type(model) == np.ndarray:\n\t# \tmodel = (model,)\n\tif model.ndim == 1:\n\t\tmodel = model[None,:]\n\n\toutput = ()\n\tfor i in range(0,len(model)):\n\t\tdict_dum = {}\n\t\tfor name, val in zip(header,model[i]):\n\t\t\tdict_dum[name] = val\n\t\t# Use the default parameters for mostly fixed parameter (e.g. disk)\n\t\tif default == True:\n\t\t\tdict_dum['M_disk'] = 5e-1\n\t\t\tdict_dum['M_disk_dot'] = 6.5e-7\n\t\t\tdict_dum['beta'] = 1.093\n\t\t\tdict_dum['h100'] = 8.123\n\t\t\tdict_dum['rho_cav'] = 1e-21\n\t\toutput = output+(dict_dum,)\n\n\treturn output\n\n# filename = '/Users/yaolun/programs/misc/hyperion/tsc_params.dat'\n# filename = '/Users/yaolun/programs/misc/hyperion/input_table.txt'\n# input_reader_table(filename)\n# input_reader(filename)\n","sub_path":"hyperion/clean/input_reader.py","file_name":"input_reader.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"341719287","text":"from day10.czlowiek import Czlowiek\nfrom day10.film import Film\n\n\nclass Klient(Czlowiek):\n    \"\"\"\n    Klient wypożyczalni\n    \"\"\"\n\n    def __init__(self, imie, pesel):\n        \"\"\"Tworzy nowego klienta\n            (str, int) -> Klient\"\"\"\n        self.pesel = pesel\n        wiek = str(pesel)[0:2]\n        Czlowiek.__init__(self, imie, wiek)\n\n    def wypozycz(self, film: Film, dni: int):\n        \"\"\"Wypozycza film\n\n        :param film: Film wypożyczny przez klienta\n        :param dni: ilość dni wypożyczenia\n        \"\"\"\n        # asercja - sprawdzenie - założenie typu obiektu\n        assert type(film) is Film\n        film.klient = self\n\n        print(f\"Koszt wypożyczenia: {film.cena * dni} zł\")\n","sub_path":"day10/klient.py","file_name":"klient.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"579562739","text":"import cv2\nimport os\nimport numpy as np\nimport time\n\nfrom PIL import Image\n\neigenface = cv2.face.EigenFaceRecognizer_create(15, 8000)\nfisherface = cv2.face.FisherFaceRecognizer_create(2, 2000)\nlbph = cv2.face.LBPHFaceRecognizer_create(1, 1, 7, 7, 18)\n\n\ndef getImagemComId():\n    caminhos = [os.path.join('yalefaces/treinamento', f) for f in os.listdir('yalefaces/treinamento')]\n    faces = []\n    ids = []\n    for caminhoImagem in caminhos:\n        imagemFace = Image.open(caminhoImagem).convert('L')\n        imagemNP = np.array(imagemFace, 'uint8')\n        id = int(os.path.split(caminhoImagem)[1].split(\".\")[0].replace(\"subject\", \"\"))\n        ids.append(id)\n        faces.append(imagemNP)\n\n    return np.array(ids), faces\n\n\nids, faces = getImagemComId()\n\nprint(\"Treinando...\")\n\ntempo_inicio_eigenface = time.time()\neigenface.train(faces, ids)\neigenface.write('classificadores/classificadorEigenYale.yml')\nprint(\"--- %s segundos ---\" % (time.time() - tempo_inicio_eigenface))\n\ntempo_inicio_fisherface = time.time()\nfisherface.train(faces, ids)\nfisherface.write('classificadores/classificadorFisherYale.yml')\nprint(\"--- %s segundos ---\" % (time.time() - tempo_inicio_fisherface))\n\ntempo_inicio_lbph = time.time()\nlbph.train(faces, ids)\nlbph.write('classificadores/classificadorLBPHYale.yml')\nprint(\"--- %s segundos ---\" % (time.time() - tempo_inicio_lbph))\n\nprint(\"Treinamento realizado\")\n","sub_path":"service/treinamento_yale.py","file_name":"treinamento_yale.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"150118462","text":"import curses\n\n\nVALID_LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\ndef start_game(screen: curses.initscr()):\n    curses.curs_set(0)\n    curses.noecho()\n    curses.cbreak()\n\n    screen.clear()\n\n    screen.addstr(0, 0, \"Secret Word: \")\n\n    screen.refresh()\n    word_chars = \"\"\n    while True:\n        c = screen.getch()\n        ch = chr(c).upper()\n        if len(word_chars) < 4 and ch in VALID_LETTERS:\n            word_chars += ch\n            screen.addstr(ch.upper())\n            screen.refresh()\n\n        if len(word_chars) == 4:\n            break\n\n    screen.getkey()\n\ndef main():\n    print(\"Starting Wordmaster...\")\n    curses.wrapper(start_game)\n\n\nif __name__ == \"__main__\":\n    main()\n","sub_path":"wordmaster.py","file_name":"wordmaster.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"366475579","text":"import rospy\nfrom periphery import GPIO\n\n\nfrom motors_bridge import MotorsBridge\nfrom PID import PID\nimport math\nimport time\n\nfrom geometry_msgs.msg import Vector3\nfrom std_msgs.msg import Float32MultiArray, Float64, String\nimport rospkg\n\nrospack = rospkg.RosPack()\nvar_path = rospack.get_path('larc_control')\nvar_path = var_path + '/script/var.py'\n\nfrom var import *\n# execfile(var_path)\n\nBTN1_PIN = 431\nBTN2_PIN = 432\n\nSRC_TIME = 30\n\nERROR_W = 0.01\nERROR_X = 0.005\nERROR_Y = 0.005\n\nclass Fsm:\n\n    def __init__(self):\n        self.state = self.s_start_state\n        self.state_1 = None\n\n        ## PID\n        self.pid_w = PID(1.0, 0.0, 0.0)\n        self.pid_w.SetPoint = 0.0\n        self.pid_w.setWindup(20.0)\n        self.meas_w_1 = 0\n\n        self.pid_x = PID(4.0, 0.0, 0.0)\n        self.pid_x.SetPoint = 0.0\n        self.pid_x.setWindup(20.0)\n        self.meas_x_1 = 0\n\n        self.pid_y = PID(4.0, 0.0, 0.0)\n        self.pid_y.SetPoint = 0.0\n        self.pid_y.setWindup(20.0)\n        self.meas_y_1 = 0\n\n        ## Variables\n        self.timer1 = 0\n        self.count_zero = 0\n\n        ## ROS\n        self.pub_cmd_vel = rospy.Publisher(\"/cmd_vel\", Vector3, queue_size = 1)\n        self.pub_move = rospy.Publisher(\"/larc_movement/go_to_pos\", Float32MultiArray, queue_size = 1)\n        self.pub_gripper = rospy.Publisher(\"/gripper/command\", Float64, queue_size = 1)\n\n        self.msg = Float32MultiArray()\n\n        self.ret_state = []\n        self.ret_from_init_pos = None\n        self.ret_from_cam_pos = None\n        self.ret_from_control = None\n\n        self.pick_phases = []\n        self.release_phases = []\n\n        self.left_color = ''\n        self.right_color = ''\n        self.ctp = ''\n\n        self.count_pick = 0\n        self.count_red = 0\n        self.count_green = 0\n        self.count_blue = 0\n\n        self.fsm_start_signal = 0\n\n        ## Others\n        self.mb = MotorsBridge()\n        self.button1 = GPIO(BTN1_PIN, \"in\")\n        assert self.button1.pin == BTN1_PIN\n        assert self.button1.fd > 0\n        self.button2 = GPIO(BTN2_PIN, \"in\")\n        assert self.button2.pin == BTN2_PIN\n        assert self.button2.fd > 0\n\n    def tick(self, vision_info, joint_state, is_moving, fsm_start_signal):\n        if self.state != self.state_1:\n            rospy.loginfo('Entering to state \"{}\"'.format(self.state.__name__))\n        self.fsm_start_signal = fsm_start_signal\n        if self.fsm_start_signal == -1:\n            next_state = self.s_idle\n        elif not(self.state==self.s_idle or self.state==self.init_position_0 or self.state==self.s_cam_position) and ( (not self.button1.read()) or (not self.button2.read()) ):\n            next_state = self.s_stop\n        else:\n            next_state = self.state(vision_info, joint_state, is_moving)\n        self.state_1 = self.state\n        self.state = next_state\n\n    def s_stop(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1:\n            self.pub_cmd_vel.publish(0.0, 0.0, 0.0)\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1<45:\n            return self.s_stop\n        else:\n            return self.s_idle\n\n    def s_start_state(self, vision_info, joint_state, is_moving):\n        self.timer1 = 0\n        return self.s_idle\n\n    def s_idle(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1:\n            self.pub_cmd_vel.publish(0.0, 0.0, 0.0)\n            self.count_pick = 0\n            self.count_red = 0\n            self.count_green = 0\n            self.count_blue = 0\n        self.timer1 += 1\n        if self.fsm_start_signal == 1 or (not self.button1.read()):\n            self.ret_from_init_pos = self.s_idle\n            return self.init_position_0\n        elif self.fsm_start_signal == 2:\n            self.ret_from_cam_pos = self.s_idle\n            return self.s_cam_position\n        elif self.fsm_start_signal == 3:\n            self.ret_from_control = self.s_idle\n            return self.s_control2\n        elif self.fsm_start_signal == 4:\n            self.ret_from_cam_pos = self.s_forward1\n            self.ret_from_control = self.s_idle\n            return self.s_cam_position\n        elif self.fsm_start_signal == 5:\n            return self.choose_1\n        elif self.fsm_start_signal == 6 or (not self.button2.read()):\n            self.ret_from_cam_pos = self.s_forward1\n            self.ret_from_control = self.choose_1\n            return self.s_cam_position\n        else:\n            return self.s_idle\n\n    def init_position_0(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.msg.data = init_positions[0]\n            self.pub_move.publish(self.msg)\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1<20 or is_moving:\n            return self.init_position_0\n        else:\n            return self.init_position_1\n\n    def init_position_1(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.pub_gripper.publish(0.25)\n            self.msg.data = init_positions[1]\n            self.pub_move.publish(self.msg)\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1<20 or is_moving:\n            return self.init_position_1\n        else:\n            return self.ret_from_init_pos\n\n    def s_cam_position(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.msg.data = cam_pos\n            self.pub_move.publish(self.msg)\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1<20 or is_moving:\n            return self.s_cam_position\n        else:\n            return self.ret_from_cam_pos\n\n    def s_forward1(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.pub_cmd_vel.publish(0.0, 5.0, 0.0)\n        if vision_info.black_strip_flag and vision_info.black_strip_y>50:\n            return self.s_forward2\n        else:\n            return self.s_forward1\n\n    def s_forward2(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.pub_cmd_vel.publish(0.0, 2.0, 0.0)\n        if vision_info.black_strip_flag and vision_info.black_strip_y>200:\n            return self.s_forward3\n        else:\n            return self.s_forward2\n\n    def s_forward3(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.pub_cmd_vel.publish(0.0, 1.5, 0.0)\n        if vision_info.num_containers==0:\n            return self.s_forward3\n        else:\n            return self.s_wait2\n\n    def s_wait2(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1<5:\n            return self.s_wait2\n        else:\n            if vision_info.num_containers==2:\n                self.pub_cmd_vel.publish(0.0, 0.0, 0.0)\n                return self.s_control2\n            else:\n                if len(vision_info.cont_x)==0:\n                    return self.s_wait2\n                elif vision_info.cont_x[0] > 320:\n                    return self.s_right\n                else:\n                    return self.s_left\n\n    def s_right(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.pub_cmd_vel.publish(2.0, 0.0, 0.0)\n        if vision_info.num_containers<2:\n            return self.s_right\n        else:\n            return self.s_wait1\n\n    def s_left(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.pub_cmd_vel.publish(-2.0, 0.0, 0.0)\n        if vision_info.num_containers<2:\n            return self.s_left\n        else:\n            return self.s_wait1\n\n    def s_wait1(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1<10:\n            return self.s_wait1\n        else:\n            self.pub_cmd_vel.publish(0.0, 0.0, 0.0)\n            return self.s_control2\n\n    # def s_control1(self, vision_info, joint_state, is_moving):\n    #     if self.state != self.state_1: # Recien llego a este estado?\n    #         self.pub_gripper.publish(0.65)\n    #     meas_w = vision_info.error_s\n    #     if math.isnan(meas_w):\n    #         meas_w = self.meas_w_1\n    #     if meas_w>0.3:\n    #         meas_w = 0.3\n    #     if meas_w<-0.3:\n    #         meas_w = -0.3\n    #     self.pid_w.update(meas_w)\n    #     cw = -self.pid_w.output\n    #     # print('meas_w: ' + str(meas_w) + ', cw: ' + str(cw))\n    #     self.pub_cmd_vel.publish(0.0, 0.0, cw)\n    #     self.meas_w_1 = meas_w\n    #     if meas_w>=0.01:\n    #         return self.s_control1\n    #     else:\n    #         return self.s_control2\n\n    def s_control2(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1: # Recien llego a este estado?\n            self.count_zero = 0\n        ###\n        meas_w = vision_info.error_s\n        if math.isnan(meas_w):\n            meas_w = self.meas_w_1\n        if meas_w>0.3:\n            meas_w = 0.3\n        if meas_w<-0.3:\n            meas_w = -0.3\n        self.pid_w.update(meas_w)\n        cw = -self.pid_w.output\n        # cw = 0.0\n        self.meas_w_1 = meas_w\n        ###\n        meas_x = vision_info.error_x/640.0\n        if math.isnan(meas_x):\n            meas_x = self.meas_x_1\n        if meas_x>0.3:\n            meas_x = 0.3\n        if meas_x<-0.3:\n            meas_x = -0.3\n        self.pid_x.update(meas_x)\n        cx = self.pid_x.output\n        self.meas_x_1 = meas_x\n        ###\n        meas_y = vision_info.error_y/640.0\n        if math.isnan(meas_y):\n            meas_y = self.meas_y_1\n        if meas_y>0.3:\n            meas_y = 0.3\n        if meas_y<-0.3:\n            meas_y = -0.3\n        self.pid_y.update(meas_y)\n        cy = -self.pid_y.output\n        self.meas_y_1 = meas_y\n\n        # print('')\n        # print(meas_w)\n        # print(meas_x)\n        # print(meas_y)\n\n        if abs(meas_w)0:\n            # self.ctp = pick_order.pop(0)\n            self.ctp = pick_order[self.count_pick]\n            self.count_pick += 1\n            rospy.loginfo('Picking: \"{}\"'.format(self.ctp))\n            if self.ctp[1]=='1':\n                self.pick_phases = [    pick_routines[self.ctp][0],\n                                        pick_routines[self.ctp][1],\n                                        pick_routines[self.ctp][2] ]\n            else:\n                self.pick_phases = [    pick_routines[self.ctp][0],\n                                        pick_routines[self.ctp][1],\n                                        pick_routines[self.ctp][0] ]\n            return self.s_pick_0\n        else:\n            return self.s_idle\n\n    def choose_2(self, vision_info, joint_state, is_moving):\n        if self.ctp[0]=='0' or self.ctp[0]=='2' or self.ctp[0]=='4':\n            rospy.loginfo('Picking the left one, color: {}'.format(self.left_color))\n            if self.left_color=='green' and self.count_green>=7:\n                routine = release_red_routines[self.count_red]\n                self.count_red += 1\n            elif self.left_color=='blue' and self.count_blue>=7:\n                routine = release_red_routines[self.count_red]\n                self.count_red += 1\n            elif self.left_color=='green':\n                routine = release_green_routines[self.count_green]\n                self.count_green += 1\n            elif self.left_color=='blue':\n                routine = release_blue_routines[self.count_blue]\n                self.count_blue += 1\n            else:\n                routine = release_red_routines[self.count_red]\n                self.count_red += 1\n\n        elif self.ctp[0]=='1' or self.ctp[0]=='3' or self.ctp[0]=='5':\n            rospy.loginfo('Picking the right one, color: {}'.format(self.right_color))\n            if self.right_color=='green' and self.count_green>=7:\n                routine = release_red_routines[self.count_red]\n                self.count_red += 1\n            elif self.right_color=='blue' and self.count_blue>=7:\n                routine = release_red_routines[self.count_red]\n                self.count_red += 1\n            if self.right_color=='green':\n                routine = release_green_routines[self.count_green]\n                self.count_green += 1\n            elif self.right_color=='blue':\n                routine = release_blue_routines[self.count_blue]\n                self.count_blue += 1\n            else:\n                routine = release_red_routines[self.count_red]\n                self.count_red += 1\n        self.release_phases = [routine[0], routine[1], routine[2], routine[0]]\n        return self.s_release_0\n\n    ## DUMMY\n    def dummy_1(self, vision_info, joint_state, is_moving):\n        self.pick_phases = [    [-0.15, 0.055, -0.5, 1.5, -0.5, 1.43],\n                                [-0.12, 0.055, -1.0, 1.0, -0.5, 1.43],\n                                [-0.15, 0.055, -0.5, 1.5, -0.5, 1.43] ]\n        self.ret_state.append(self.dummy_2)\n        return self.s_pick_0\n\n    # pick\n    def s_pick_0(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1:\n            self.msg.data = self.pick_phases[0]\n            self.pub_move.publish(self.msg)\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1=7:\n                return self.choose_1\n            if self.ctp=='303' and self.left_color=='blue' and self.count_blue>=7:\n                return self.choose_1\n            return self.s_pick_1\n    def s_pick_1(self, vision_info, joint_state, is_moving):\n        if self.state != self.state_1:\n            self.msg.data = self.pick_phases[1]\n            self.pub_move.publish(self.msg)\n            self.timer1 = 0\n        self.timer1 += 1\n        if self.timer1 0.5).astype(np.uint8)\n\n    plot_figures(image,pred_mask, count)\n    count += 1\n\n    if count>10:\n        break\n\nplt.ioff()\nplt.show()","sub_path":"use_network_dynamic.py","file_name":"use_network_dynamic.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"632800691","text":"'''\n    VERSION 0.8.4\n    \n    zmiany:\n    -zapis do pliku po kazdym MT (funkcja log_write)\n    -przechwytywanie wyjatku telnet\n    - porzadki w logach\n    - dodanie funkcji check_services = wylacza ftp,https, http na 443, \n    - tabulacja w logach\n    - slash zamiast sztywnych zmiennych (lokalizacja\n    \n\n\n\n\n\n'''\n\n\n''' TODO:\n\n- bug l2mte (mac) - nastepny \n- nazwy wifi\n\n\n\n'''\n\n\n'''\nProgram do przeadresowywania klasy. Dziala zarowna na platformie nt jak i posix.\n\nprogram odczytuje z pliku \n\n\n'''\n#!/usr/bin/python3\nimport socket,time, os, telnetlib, sys, binascii, select, hashlib\nif os.name == 'posix':\n    import posix\n    md_command = 'mkdir -p'\n    slash='/'\nelif os.name =='nt':\n    md_command = 'md'\n    slash='\\\\'\n\n\n##### nazwa pliku z lista mt\nlist_file = 'lista.txt'\n#####\n\nclass ApiRos:\n    \"Routeros api\"\n    def __init__(self, sk):\n        self.sk = sk\n        self.currenttag = 0\n        \n    def login(self, username, pwd):\n        for repl, attrs in self.talk([\"/login\"]):\n            chal = binascii.unhexlify((attrs['=ret']).encode('UTF-8'))\n        md = hashlib.md5()\n        md.update(b'\\x00')\n        md.update(pwd.encode('UTF-8'))\n        md.update(chal)\n        self.talk([\"/login\", \"=name=\" + username,\n                   \"=response=00\" + binascii.hexlify(md.digest()).decode('UTF-8') ])\n\n    def talk(self, words,listen=True):\n        if self.writeSentence(words) == 0: return\n        r = []\n        if listen:\n            while 1:\n                i = self.readSentence();\n                if len(i) == 0: continue\n                reply = i[0]\n                attrs = {}\n                for w in i[1:]:\n                    j = w.find('=', 1)\n                    if (j == -1):\n                        attrs[w] = ''\n                    else:\n                        attrs[w[:j]] = w[j+1:]\n                r.append((reply, attrs))\n                if reply == '!done': return r\n                if reply == '!trap':\n                    if i[1]=='=message=cannot log in':\n                        blad=1\n                        raise RuntimeWarning(\"Nie mozna sie zalogowac\")\n                        \n                    \n\n    def writeSentence(self, words):\n        ret = 0\n        for w in words:\n            self.writeWord(w)\n            ret += 1\n        self.writeWord('')\n        return ret\n\n    def readSentence(self):\n        r = []\n        while 1:\n            w = self.readWord()\n            if w == '' : return r\n            r.append(w)\n            \n               \n    def writeWord(self, w):\n        if view_print=='True': print((\"<<< \" + w))\n        self.writeLen(len(w))\n        self.writeStr(w)\n\n    def readWord(self):\n        global answer        \n        ret = self.readStr(self.readLen())\n        if view_print=='True': print((\">>> \" + ret))\n        answer.append(ret)\n        return ret\n\n    def writeLen(self, l):\n        if l < 0x80:\n            self.writeStr(chr(l))\n        elif l < 0x4000:\n            l |= 0x8000\n            self.writeStr(chr((l >> 8) & 0xFF))\n            self.writeStr(chr(l & 0xFF))\n        elif l < 0x200000:\n            l |= 0xC00000\n            self.writeStr(chr((l >> 16) & 0xFF))\n            self.writeStr(chr((l >> 8) & 0xFF))\n            self.writeStr(chr(l & 0xFF))\n        elif l < 0x10000000:        \n            l |= 0xE0000000         \n            self.writeStr(chr((l >> 24) & 0xFF))\n            self.writeStr(chr((l >> 16) & 0xFF))\n            self.writeStr(chr((l >> 8) & 0xFF))\n            self.writeStr(chr(l & 0xFF))\n        else:                       \n            self.writeStr(chr(0xF0))\n            self.writeStr(chr((l >> 24) & 0xFF))\n            self.writeStr(chr((l >> 16) & 0xFF))\n            self.writeStr(chr((l >> 8) & 0xFF))\n            self.writeStr(chr(l & 0xFF))\n\n    def readLen(self):              \n        c = ord(self.readStr(1))    \n        if (c & 0x80) == 0x00:      \n            pass                    \n        elif (c & 0xC0) == 0x80:    \n            c &= ~0xC0              \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n        elif (c & 0xE0) == 0xC0:    \n            c &= ~0xE0              \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n        elif (c & 0xF0) == 0xE0:    \n            c &= ~0xF0              \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n        elif (c & 0xF8) == 0xF0:    \n            c = ord(self.readStr(1))     \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n            c <<= 8                 \n            c += ord(self.readStr(1))    \n        return c                    \n\n    def writeStr(self, str):        \n        n = 0;                      \n        while n < len(str):         \n            r = self.sk.send(bytes(str[n:], 'UTF-8'))\n            if r == 0:                 \n                raise RuntimeError(\"Polaczenie przerwane przez MT\")\n            n += r                  \n\n    def readStr(self, length):      \n        global wifi_utf\n        ret = ''\n        while len(ret) < length:\n            s = self.sk.recv(length - len(ret))\n            if s == '':\n                raise RuntimeError(\"Polaczenie przerwane przez MT\")\n            if b'=name=' in s:\n                wifi_utf=str(s)[8:-1]\n            ret += s.decode('UTF-8','replace')\n        return ret\n#######################################################################\ndef make_socket(address):\n    s = None # socket\n    for res in socket.getaddrinfo(address, \"8728\", socket.AF_UNSPEC, socket.SOCK_STREAM):\n        af, socktype, proto, canonname, sa = res\n        try:\n             s = socket.socket(af, socktype, proto)\n        except (socket.error, msg):\n            s = None\n            continue\n        try:\n            s.connect(sa)\n        #except (socket.error, msg):\n        except OSError:\n            #print (\"Blad!\")            \n            s.close()\n            s = None\n            continue\n        break\n        s.timeout()\n    return s\n\ndef telnet_api(HOST,user,passw):\n    try: \n        tn = telnetlib.Telnet(HOST,'23')\n        tn.read_until(b\"Login:\")\n        tn.write(user.encode('UTF-8') + b\"\\n\")\n        tn.read_until(b\"Password:\")\n        print('   -- telnet > login ok')\n        tn.write(passw.encode('UTF-8') + b\"\\n\")\n        tn.read_until(b'>')\n        print('   -- telnet > password ok')\n        command1 = 'ip service enable api'\n        command2 = 'ip service print'\n        tn.write(command1.encode('UTF-8')+b\"\\r\\n\")\n        tn.write(command2.encode('UTF-8')+b\"\\r\\n\")\n        tn.read_until(b'#')\n        print('   -- telnet > api turning on ok')\n        tn.write(b\"quit\\r\\n\")\n        tn.close()\n    except (OSError, EOFError):\n        \n        return False\n    return True\n\ndef odkoduj(tekst):\n    new_tekst=''\n    polskie =      {\"xa5\":\"A\",\"xc6\":\"C\",\n\"xca\":\"E\",\"xa3\":\"L\",\"xd1\":\"N\",\"xd3\":\"O\",\n\"x8c\":\"S\",\"x8f\":\"Z\",\"xaf\":\"Z\",\"xb9\":\"a\",\n\"xe6\":\"c\",\"xea\":\"e\",\"xb3\":\"l\",\"xf1\":\"n\",\n\"xf3\":\"o\",\"x9c\":\"s\",\"x9f\":\"z\",\"xbf\":\"z\"}\n    x=0\n    while (x< (len(tekst))):\n        print (tekst[x])\n        if tekst[x] == '\\\\' and tekst[x+1]=='x':\n            indeks_str=tekst[x+1]+tekst[x+2]+tekst[x+3]\n            print(' '+indeks_str)\n            new_tekst=new_tekst+polskie[indeks_str]\n            x=x+4\n        else:\n            new_tekst=new_tekst+tekst[x] \n            x=x+1                  \n    return (new_tekst)\n#-----------------------------\n    \ndef log_write(log_type,log_string):\n    if log_type=='error':\n        error_log_file.writelines(log_string)\n        os.fsync(error_log_file)  # file flush\n    elif log_type=='good':\n        good_log_file.writelines(log_string)\n        os.fsync(good_log_file)  # file flush\n    elif log_type=='mac':\n        mac_log_file.writelines(log_string)\n        os.fsync(mac_log_file)  # file flush\n#---------------------------------        \n        \n    \n    \n        \n            \n           \n           \n    \n\n########################################################################################################\n\n##\npy_loc = os.path.dirname(os.path.abspath(__file__))+slash #lokalizacja tego pliku\nlog_file_dir =py_loc+\"log\"+slash\nMT_list_file=py_loc+list_file    ## nazwa pliku z lista MT\nview_print='False'\ntest_eth='False'\nnew_gateway=''\nold_gateway=''\naction='disable'\nmask=''\nchange_lang='False'\nlogin=''\npassword=''\n##\nanswer=[]\nwifi_utf=''\ntoday=time.strftime(\"%Y.%m.%d-%H_%M\");\ndata=[]\nos.system(md_command+' \"'+log_file_dir+'\"')\nerror_log_file=open(log_file_dir+'errorlog'+\"__\"+today+'.log','w')\ngood_log_file=open(log_file_dir+'goodlog'+\"__\"+today+'.log','w')\nmac_log_file=open(log_file_dir+'mac_log'+\"__\"+today+'.log','w')\n\n\ntry:       #WCZYTANIE USTAWIEN Z PLIKU lista.txt\n    plik = open(MT_list_file)\n    for line in plik:\n        if (line[0] == '#' or line[0]=='' or line[0]=='\\n'): continue\n        conf_tab=line.split('\\n')\n        \n        conf_tab=conf_tab[0].split('=')\n        if conf_tab[0]=='login': login=conf_tab[1].split()[0]\n        elif conf_tab[0]=='password': password=conf_tab[1].split()[0]\n        elif conf_tab[0]=='new_gateway': new_gateway=conf_tab[1].split()[0]\n        elif conf_tab[0]=='old_gateway': old_gateway=conf_tab[1].split()[0]\n        elif conf_tab[0]=='new_mask': mask=conf_tab[1].split()[0]\n        elif conf_tab[0]=='action': action=conf_tab[1].split()[0]\n        elif conf_tab[0]=='test_eth': test_eth=conf_tab[1].split()[0]\n        elif conf_tab[0]=='view_print': view_print=conf_tab[1].split()[0]\n        elif conf_tab[0]=='change_lang': change_lang=conf_tab[1].split()[0]\n        elif conf_tab[0]=='check_services': check_services=conf_tab[1].split()[0]\n        else:           \n            if ';'in line:  # jesli ip w linii      \n                data.extend(line.split('\\n')) # IP;new_IP\n    plik.close()\nexcept FileNotFoundError:\n    log_write('error','Brak pliku konfiguracyjnego!')\n    raise RuntimeError(\"Brak pliku konfiguracyjnego!\")\nif login=='' or password=='':\n    print(\" !! Nie podano loginu lub hasla!\")\n\n\n# wczytanie IP+new_IP    \nfor i in range(len(data)):\n    try:\n        data.remove('')\n    except ValueError:\n        break\n#=========================================================        \n#=================== GLOWNA PETLA  =======================        \n#=========================================================        \nfor line in data: # PETLA Z MT\n    \n    \n    IP=line.split(';')[0]\n    new_IP=line.split(';')[1]\n    print (\"#######  \"+IP+' >> '+new_IP+\"  ######\")\n    print (\" ++ Lacze do mikrotika IP: \"+IP)    \n    s=make_socket(IP) # otwiera socket   API - pierwsza proba            \n    if s is None:\n        log_write('error',IP+\"  --  Blad polaczenia, nie odpowiada (wylaczone api?)\\n\")\n        print(\" !! Blad polaczenia, nie odpowiada (wylaczone api?)\")\n        print(\" -- Lacze sie przez telnet - wlacze API\")  \n#TELNET - wlacz\n        if not telnet_api(IP,login,password): ## TELNET jestli nie API\n            log_write('error',IP+\"  --  Nie udalo sie polaczyc przez telnet, pomijam MT\\n\")\n            print(\" !! Nie udalo sie polaczyc przez telnet, pomijam MT\")\n            continue\n        else:\n            print(\" ++ Wlaczylem API, kontynuuje...\\n ++ Lacze do API\")\n            log_write('good',\" ++ Wlaczylem API, kontynuuje...\\n ++ Lacze do API\")\n            s=make_socket(IP) # otwiera socket   API\n            if s is None:\n                log_write('error',IP+\"  --  Blad polaczenia, nie odpowiada\\n\")\n                print(\" !! Blad polaczenia, nie odpowiada\")\n                continue\n                \n#**********************  KONIEC TELNET  *******************************\n                \n # jesli polaczono to wykonaj komendy API\n    try:\n        mtapi = ApiRos(s) #klasa api\n        mtapi.login(login, password) # loguje sie z loginem i pass\n        print(\"    api > login ok\")\n        \n\n#\n    #   pobiera nazwe(z polskimi znakami) w klasie\n    #   zmienia na angielskie znaki (wifi_utf) - funkcja odkoduj\n    #   zmienia nazwe interfejsu wlan \n    #   wykonuje operacje na karcie wlan\n    \n        answer=[]\n        if test_eth=='True':            \n            mtapi.talk([\"/interface/ethernet/print\"])        \n            \n        else:\n            mtapi.talk([\"/interface/wireless/print\"])   \n        \n        if change_lang=='True': # zmiana znakow\n            print(\" -- sprawdzam i zmieniam polskie znaki w nazwie wifi\")\n            wifi_utf=odkoduj(wifi_utf) # pobieraa wifi_utf w klasie (kodowanie utf-8)\n        for element in answer:\n            if 'mac-address' in element:\n                mac=element.split('=')[2]\n                #mac=str(mac[mac.find('mac-address')+1])\n            if '.id' in element: wifi_id = element\n        if change_lang=='True': #ZMIANA JEZYKA\n            if test_eth=='True':\n                mtapi.talk(['/interface/ethernet/set',wifi_id,'=name='+wifi_utf]) # zmiana nazwy w mt bez polskich znakow            \n            else:\n                mtapi.talk(['/interface/wireless/set',wifi_id,'=name='+wifi_utf]) # zmiana nazwy w mt bez polskich znakow \n        # tabulacja wedlug dlugosci nazwy wifi\n        tabulate='\\t'\n        if len(wifi_utf)<16:\n            tabulate='\\t\\t'\n            if len(wifi_utf)<8:\n                tabulate='\\t\\t\\t'\n        log_write('mac',wifi_utf+tabulate+'old: '+IP+'\\tnew: '+new_IP+'/'+mask+'\\tmac: '+mac+'\\n')\n        \n#\n        if new_IP!=IP and mask!='':\n            if test_eth=='True':\n                mtapi.talk(['/ip/address/add','=interface=eth','=address='+new_IP+'/'+mask,]) #\n                print(\" -- ip address add interface=eth address=\"+new_IP+\"/\"+mask)\n            else:\n                mtapi.talk(['/ip/address/add','=interface='+wifi_utf,'=address='+new_IP+'/'+mask,]) # nowy adres\n                print(\" -- ip address add interface=\"+wifi_utf+\" address=\"+new_IP+\"/\"+mask)\n        elif new_IP!=IP and mask=='':\n            print(\" !! BLAD! Nie podano nowej maski!\")\n            continue\n                \n#\n#\n        if old_gateway!=new_gateway:\n            print(\" -- route add gateway=\"+new_gateway)\n            mtapi.talk(['/ip/route/add','=gateway='+new_gateway])\n#\n#\n        if IP!=new_IP:\n            s.close()\n            s = None\n            print (\" ++ Lacze na nowym adresie IP: \"+new_IP)\n            s=make_socket(new_IP)\n            if s is None:\n                log_write('error',IP+\"  --  Blad ponownego polaczenia na IP \"+new_IP+\"  (nie odpowiada)\\n\")\n                print (\" !! Blad ponownego polaczenia na IP \"+new_IP+\"  (nie odpowiada)\")\n                continue    \n            mtapi = ApiRos(s)\n            mtapi.login(login, password) \n            print(\"    api > login ok\")        \n#\n        \n       \n#\n        #ip\n        answer=[]\n        if new_IP!=IP:\n            mtapi.talk(['/ip/address/print'])\n            for element in answer:\n                if '.id' in element: interface_id = element                                    \n                if 'address' in element:\n                    if element.split('=')[2].split('/')[0] == IP:\n                        mtapi.talk(['/ip/address/'+action, interface_id])\n                        print(\" -- ip address \"+action+\" \"+ IP)\n                        break\n        #route\n        if old_gateway!=new_gateway and old_gateway!='': # jesli stara i nowa brama rozne, to usun\n            answer=[]\n            mtapi.talk(['/ip/route/print'])\n            for element in answer:\n                if '.id' in element: route_id = element\n                if '=gateway=' in element:\n                    if element.split('=')[2] == old_gateway:\n                        mtapi.talk(['/ip/route/'+action, route_id])\n                        print(\" -- ip route \"+action+' '+old_gateway)\n                        break \n                        \n                        \n#\n        #\n        if check_services=='True':\n            print(' ++ Wylaczam ftp i zmieniam port WWW na 443')\n            log_write('good',' ++ Wylaczylem FTP, zmienilem port WWW na 443\\n')\n            mtapi.talk(['/ip/service/disable','=.id=ftp'])\n            mtapi.talk(['/ip/service/disable','=.id=www-ssl'])\n            mtapi.talk(['/ip/service/set','=.id=www','=port=443'])\n\n\n#\n                    \n#\n#            \n    except RuntimeError:\n        log_write('error',IP+\"  --  Polaczenie przerwane przez MT\\n!\")\n        print (\" !! Polaczenie przerwane przez MT!\")\n        if s is not None:\n            s.close()\n            continue # glowna petla\n        #continue\n    except RuntimeWarning:\n        log_write('error',IP+\"  --  Blad logowania (sprawdz)\\n\")\n        print(\" !! Blad logowania (sprawdz)\")\n        if s is not None:\n            s.close()\n            continue ## kolejny MT\n        #continue\n#\n        \n    if s is not None: # Zamkniecie socketa, nastepny z listy\n        s.close() \n     \n    if IP==new_IP and new_gateway==old_gateway:\n        log_write('good',IP+\"  --  OK, nie zmienialem adresacji\")\n        print(\" ++ OK, nie zmienialem adresacji\\n\\n\")\n    else:\n        log_write('good',IP+\"  --  OK, przeadresowane na \"+new_IP+\" \\n\")\n        print(\" ++ OK, przeadresowane na \"+new_IP+\" \\n######  OK  ######\\n\\n\")\n          \n\n    #ODKRESLENIE W LOGACH\n    log_write('good','-------------------------------------------------')\n    log_write('error','-------------------------------------------------')\n    \n#=========================================================        \n#===========KONIEC GLOWNA PETLA  =======================        \n#=========================================================  \n\n\nprint(\"**** ZAKONCZONO ****\\nLogi z pracy znajdziesz w folderze logi\")\ngood_log_file.close()\nerror_log_file.close()\nmac_log_file.close()\nif os.name=='nt':\n    os.system(\"pause\")\n\n","sub_path":"python/adresacja/chaddr.py","file_name":"chaddr.py","file_ext":"py","file_size_in_byte":18161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"64865963","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tensorflow\nimport make_data\nfrom tensorflow.keras.preprocessing import sequence\nimport csv\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Bidirectional, LSTM, Masking, Convolution1D, Dropout, Activation, LeakyReLU, Flatten\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt, tanh\n\nimport datetime\n\nfrom tensorflow.python.keras.backend import binary_crossentropy\nnow = datetime.datetime.now\n\ndef process(temp):\n    min_len = 3000\n    for i in range(11):\n        j = 0\n        while temp[j][i] != '' and j/',\n        '/report///',\n    ], type='http', auth='user', website=True)\n    def report_routes(self, reportname, docids=None, converter=None, **data):\n        if converter == 'pdf':\n            context = dict(request.env.context)\n            report = request.env['ir.actions.report']._get_report_from_name(reportname)\n            if report.docx_engine and not report.docx_convert:\n                docids = [int(i) for i in docids.split(',')]\n                docx = report.with_context(context).render_qweb_pdf(docids, data=data)[0]\n                docxhttpheaders = [('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'), ('Content-Length', len(docx))]\n                return request.make_response(docx, headers=docxhttpheaders)\n            else:\n                return super(DocxReportController, self).report_routes(reportname, docids, converter, **data)\n        else:\n            return super(DocxReportController, self).report_routes(reportname,docids,converter, **data)\n\n    @http.route(['/report/download'], type='http', auth=\"user\")\n    def report_download(self, data, token):\n        try:\n            response = super(DocxReportController, self).report_download(data, token)\n            if response.headers.get('Content-type') == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\n                response.headers.set('Content-Disposition', response.headers.get('Content-Disposition')[:-3] + 'docx')\n            return response\n        except Exception as e:\n            se = _serialize_exception(e)\n            error = {\n                'code': 200,\n                'message': \"Odoo Server Error\",\n                'data': se\n            }\n            return request.make_response(html_escape(json.dumps(error)))\n","sub_path":"addons/mk_addons/mk_report/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"196433900","text":"'''\n배우는 이유 : 최근에는 웹을 만들때 반드시 html만을 이용하는 것은 아니다.\n최근에는 자바를 이용해서 웹을 만드는 경우가 존재한다. 이를 위해서 이것이 필요하다.\n    1. Phantom JS (프로그램)\n    2. Selenium (스크립트)\n    이번에는 Selenium을 이용하여 보는 과정을 익힌다.\n'''\n\nfrom selenium import webdriver\n\nurl = \"http://www.naver.com/\"\n\n# PhantomJS를 이용해서 자료를 받아오는 과정\n# PhantomJS 드라이버 추출하기\nbrowser = webdriver.Chrome()\n# 3초 대기하기 wdbdriver의 버그 때문에 초기화 하기 위해서는 3초 가량 대기해야 한다.\nbrowser.implicitly_wait(3)\n\n\n# URL 읽어 들이기 : 웹브라우저에 URL을 얻어도는 과정\nbrowser.get(url)\n# 실상 여기에서 자신이 원한는 과정을 모두 넣어주면 된다.\n# 화면을 캡처해서 저장하기\nbrowser.save_screenshot(\"Website.png\")\n# 브라우저 종료하기\nbrowser.quit()","sub_path":"Machine_Learning_Practice/JVscript.py","file_name":"JVscript.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"580249481","text":"import datetime\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport re\nimport requests\nfrom django.db import connection\n\nfrom django.db import models\n\n# Create your models here.\nfrom django.db.models import Sum\n\n\nclass County(models.Model):\n    county = models.CharField(max_length=100, null=False)\n    population = models.IntegerField()\n    sq_mi = models.IntegerField()\n\n    def __str__(self):\n        return self.county\n\n    @staticmethod\n    def county_dict():\n        counties = County.objects.values('id', 'county')\n        c_dict = {x['county']: x['id'] for x in counties}\n        return c_dict\n\n    @staticmethod\n    def load_county_info():\n        \"\"\"\n        Loads county information from csv file. Expects county name, population, and sq_ft area\n        :return: True if successful\n        \"\"\"\n        path = r'mi/data/counties.csv'\n        with open(path) as f:\n            data = f.readlines()\n            for line in data[1:]:\n                # remove new line character at end and set to title case\n                county, population, sq_mi = line.replace('\\n', '').split(',')\n                try:\n                    c = County.objects.get(county=county)\n                    c.population = population\n                    c.sq_mi = sq_mi\n                    c.save()\n                except BaseException as be:\n                    c = County.objects.create(county=county, population=population, sq_mi=sq_mi)\n                    c.save()\n                    print(county)\n                    print(be)\n        return True\n\n    def person_per_mi(self):\n        \"\"\"\n        Divide population by square mile land coverage to get population density\n        :return:\n        \"\"\"\n        return round(self.population / self.sq_mi, 2)\n\n    @staticmethod\n    def total_population():\n        \"\"\"\n        sums up population of all counties\n        :return: total MI population\n        \"\"\"\n        qs = County.objects.all().aggregate(total=Sum('population'))\n        return qs['total']\n\n    @staticmethod\n    def total_area():\n        \"\"\"\n        sums up sq_mi of all counties\n        :return: total MI square mileage\n        \"\"\"\n        qs = County.objects.all().aggregate(total=Sum('sq_mi'))\n        return qs['total']\n\n\nclass DateTotal(models.Model):\n    date = models.DateField()\n    county = models.ForeignKey(to=County, on_delete=models.CASCADE)\n    cases = models.IntegerField()\n    deaths = models.IntegerField()\n\n    def __str__(self):\n        return f'{self.date} - {self.county} - {str(self.cases)} cases, {str(self.deaths)} deaths'\n\n    @staticmethod\n    def change_over_n_days(county=None, days=7) -> (float, float):\n        \"\"\"\n        returns the percent change in cases and deaths over previous n days; defaults to 7\n        :param county: county to search for, gets all counties if none\n        :param days: days to go back over\n        :return: tuple of cases, deaths as floats\n        \"\"\"\n        first_day = datetime.date.today() - datetime.timedelta(days=1 + days)\n        last_day = datetime.date.today() - datetime.timedelta(days=1)\n        if county:\n            change = DateTotal.objects.filter(county__county=county)\n        else:\n            change = DateTotal.objects.all()\n\n        # first = change.filter(date=first_day).aggregate(cases=Sum('cases'), deaths=Sum('deaths'))\n        # last = change.filter(date=last_day).aggregate(cases=Sum('cases'), deaths=Sum('deaths'))\n\n        first_cases, first_deaths = DateTotal.totals_on_date(first_day, county=county)\n        last_cases, last_deaths = DateTotal.totals_on_date(last_day, county=county)\n\n        case_change = last_cases / first_cases - 1.0\n        death_change = last_deaths / first_deaths - 1.0\n\n        return case_change, death_change\n\n    @staticmethod\n    def totals_on_date(date=datetime.date.today(), county=None, cumulative=True):\n        \"\"\"\n        gets cases/deaths on a specific date. Optional county parameters and cumulative boolean\n        :param date: date to search for, defaults to today\n        :param county: county to get totals for. if blank, sums all\n        :param cumulative: if true, totals are cumulative for all available dates.\n        :return: tuple of cases, deaths\n        \"\"\"\n        if county:\n            totals = DateTotal.objects.filter(county__county=county)\n        else:\n            totals = DateTotal.objects.all()\n\n        if cumulative:\n            totals = totals.filter(date__lte=date)\n        else:\n            totals = totals.filter(date=date)\n\n        totals = totals.aggregate(cases=Sum('cases'), deaths=Sum('deaths'))\n\n        return totals['cases'], totals['deaths']\n\n    @staticmethod\n    def get_all_cases_and_deaths(county=None):\n        \"\"\"\n        gets the total cases and deaths\n        :param county: if populated, limits search to specific county\n        :return: tuple of (cases, deaths)\n        \"\"\"\n        if county:\n            totals = DateTotal.objects.filter(county__county=county)\n        else:\n            totals = DateTotal.objects.all()\n\n        totals = totals.aggregate(cases=Sum('cases'), deaths=Sum('deaths'))\n\n        return totals['cases'], totals['deaths']\n\n    @staticmethod\n    def cases_and_deaths_per_n(county=None, n=1000):\n        \"\"\"\n        calculates total cases/deaths per n number of persons\n        :param county: county to search for, defaults to None/aggregates all\n        :param n: total persons, defaults to 1000\n        :return: tuple of (cases per n, deaths per n)\n        \"\"\"\n        cases, deaths = DateTotal.get_all_cases_and_deaths(county)\n        if county:\n            population = County.objects.get(county=county).population\n        else:\n            population = County.total_population()\n\n        cases_per_n = round(cases / population * n, 2)\n        deaths_per_n = round(deaths / population * n, 2)\n\n        return cases_per_n, deaths_per_n\n\n    @staticmethod\n    def cases_and_deaths_per_sq_mi(county=None):\n        \"\"\"\n        calculates total cases/deaths per square mile in the county\n        :param county: county to search for\n        :return: tuple of (cases per sq_mi, deaths per sq_mi)\n        \"\"\"\n        cases, deaths = DateTotal.get_all_cases_and_deaths(county)\n        if county:\n            area = County.objects.get(county=county).sq_mi\n        else:\n            area = County.total_area()\n\n        cases_per_sq_mi = round(cases / area, 2)\n        deaths_per_sq_mi = round(deaths / area, 2)\n\n        return cases_per_sq_mi, deaths_per_sq_mi\n\n    @staticmethod\n    def load_data_path(from_date: datetime.date = None):\n        \"\"\"\n        Loads totals from csv file in data - data/date_totals.csv\n        :param from_date: if populated, will only start adding cases >= specified date.\n        :return: True if successful\n        \"\"\"\n        if not from_date:\n            from_date = datetime.date.today()\n        path = r'../data/date_totals.csv'\n        with open(path) as f:\n            data = f.readlines()\n            for line in data[1:]:\n                # remove new line character at end and set to title case\n                split_line = line.replace('\\n', '').split(',')\n                if from_date:\n                    if datetime.datetime.strptime(split_line[0], '%Y-%m-%d').date() < from_date:\n                        continue\n                new_info = DateTotal.create(*split_line)\n                new_info.save()\n        return True\n\n    @classmethod\n    def base_dir(cls):\n        return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    @staticmethod\n    def update_totals():\n        \"\"\"Gets and loads totals from the MI website\"\"\"\n        web_page = 'https://www.michigan.gov/coronavirus/0,9753,7-406-98163_98173---,00.html'\n        pattern = r'Cases_and_Deaths_by_County_and.*\\.xlsx'\n        # pattern = r'Cases_by_County_and.*\\.xlsx'\n        html = requests.get(web_page).text\n        excel_link = re.findall(pattern, html)[0]\n        base = 'https://www.michigan.gov/documents/coronavirus/'\n        print('Obtaining records...')\n        df = pd.read_excel(base + excel_link)\n        df['COUNTY'] = df['COUNTY'].apply(DateTotal.clean_county)\n        df['county_id'] = df['COUNTY']\n        df.to_csv(f'{DateTotal.base_dir()}/mi/data/totals/totals.csv', index=False)\n        # df = pd.read_csv(f'{DateTotal.base_dir()}/mi/data/totals/totals.csv')\n        df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')\n        # df['Date'] = df['Date'] + datetime.timedelta(1)\n        county_dict = County.county_dict()\n        today = datetime.date.today().strftime('%Y-%m-%d')\n        df = df[(df['Date'] < today) & (df['CASE_STATUS'] == 'Confirmed')]\n        df.replace({'county_id': county_dict}, inplace=True)\n        DateTotal.objects.all().delete()\n        columns = ['id', 'date', 'cases', 'deaths', 'county_id']\n        df.columns = [x.lower() for x in df.columns]\n\n        df['id'] = df.index + 1\n        df = df[columns]\n        df['date'] = df['date'].dt.strftime('%Y-%m-%d')\n        # df.set_index('date', inplace=True)\n        query = 'INSERT INTO mi_datetotal (id, date, cases, deaths, county_id) VALUES (?, ?, ?, ?, ?);'\n        records = [tuple(x) for x in df.to_numpy()]\n        print(f'Loading {str(len(df))} records...')\n        connection.cursor().executemany(query, records)\n\n    @staticmethod\n    def get_today_totals():\n        website = 'https://www.michigan.gov/coronavirus/0,9753,7-406-98163_98173---,00.html'\n        df: pd.DataFrame = pd.read_html(website)[0]  # should be at least 2 tables; totals is first one\n        today = datetime.date.today().strftime('%Y-%m-%d')\n        df = pd.DataFrame(np.row_stack([df.columns, df.values]), columns=['0', '1', '2'])\n        headers = ['date', 'County', 'Confirmed Cases', 'Reported Deaths']\n        df.columns = headers[1:]\n        df['date'] = today\n        # df = df[['date', '0', '1', '2']]\n        df.fillna(0, inplace=True)\n        df = df[headers]\n        # df.loc[0]['2'] = 0 if 'named' in df.loc[0]['2'] else df.loc[0]['2']  # no header rows any more\n        df.to_csv(f'{os.path.join(DateTotal.base_dir())}/mi/data/totals/totals_{today}_raw.csv',\n                  index=False, header=False)\n        # yesterday = datetime.date.today() - datetime.timedelta(days=1)\n\n        totals = DateTotal.objects.values('county__county')\\\n            .annotate(case_total=Sum('cases'), death_total=Sum('deaths'))\n\n        totals_dict = {x['county__county']: {'cases': x['case_total'],\n                                             'deaths': x['death_total']} for x in totals}\n        new_dict = {}\n        for i in df.index:\n            county = df.at[i, headers[1]]\n            county = DateTotal.clean_county(county)\n            cases = df.at[i, headers[2]]\n            deaths = df.at[i, headers[3]]\n            if new_dict.get(county):\n                new_dict[county]['cases'] = str(int(new_dict[county]['cases']) + int(cases))\n                new_dict[county]['deaths'] = str(int(new_dict[county]['deaths']) + int(deaths))\n            else:\n                new_dict[county] = {'cases': cases, 'deaths': deaths}\n\n        dates = []\n        counties = []\n        cases = []\n        deaths = []\n        for k, v in new_dict.items():\n            if k.upper() == 'COUNTY':\n                continue\n            dates.append(today)\n            counties.append(k)\n            if totals_dict.get(k):\n                case_count = int(v['cases']) - totals_dict[k]['cases']\n                death_count = int(v['deaths']) - totals_dict[k]['deaths']\n            else:\n                case_count = int(v['cases'])\n                death_count = int(v['deaths'])\n            cases.append(case_count)\n            deaths.append(death_count)\n\n        data_dict = {'dates': dates, 'county': counties, 'cases': cases, 'deaths': deaths}\n        data = pd.DataFrame(data_dict)\n\n        data.to_csv(f'{DateTotal.base_dir()}/mi/data/totals/totals_{today}.csv', index=False)\n        return True\n\n    @staticmethod\n    def clean_county(county):\n        if county.upper() == 'OUT-OF-STATE':\n            county = 'Non-MI'\n        elif county.upper() == 'DETROIT CITY':\n            county = 'Detroit'\n        elif county.upper() == 'BAY COUNTY':\n            county = 'Bay'\n        elif county.upper()[:5] == 'OTHER':\n            county = 'Unknown'\n        elif 'JOSEPH' in county.upper():\n            county = 'St. Joseph'\n        elif 'CLAIR' in county.upper():\n            county = 'St. Clair'\n        elif 'MDOC' in county.upper():\n            county = 'MDOC'\n        elif 'FCI' in county.upper():\n            county = 'FCI'\n        return county\n\n    @staticmethod\n    def load_today_totals():\n        today = datetime.date.today().strftime('%Y-%m-%d')\n        path = f'{DateTotal.base_dir()}/mi/data/totals/totals_{today}.csv'\n        with open(path) as f:\n            data = f.readlines()\n            for line in data[1:]:\n                # remove new line character at end and set to title case\n                split_line = line.replace('\\n', '').split(',')\n                county = split_line[1]\n                if 'TOTAL' in county.upper():\n                    continue\n                county = DateTotal.clean_county(county)\n\n                cases = split_line[2]\n                deaths = split_line[3]\n\n                new_info = DateTotal.create(date=today,\n                                            county=county,\n                                            cases=cases,\n                                            deaths=deaths)\n                new_info.save()\n        return True\n\n    @classmethod\n    def create(cls, date, county, cases, deaths):\n        \"\"\"Convenience class to add a new DateTotal quickly. Does not save.\"\"\"\n        if County.objects.filter(county=county).exists():\n            db_county = County.objects.get(county=county)\n        else:\n            new_county = County.objects.create(county=county, population=0, sq_mi=0)\n            print('Created a new county:', county)\n            new_county.save()\n            db_county = County.objects.get(county=county)\n\n        case = cls(\n                date=date,\n                county=db_county,\n                cases=cases,\n                deaths=deaths\n                )\n        return case\n\n\nclass Event(models.Model):\n    entry_date = models.DateField(auto_now=True)\n    eff_dt = models.DateTimeField()\n    event_text = models.CharField(max_length=255)\n\n    def __str__(self):\n        return f'Effective {str(self.eff_dt)} - {self.event_text[:50]}{\"...\" if len(self.event_text) > 50 else \"\"}'\n","sub_path":"covid/mi/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"147065744","text":"#!/usr/bin/env python\n\nimport math\nfrom math import sin, cos, pi\n\nimport rospy\nimport tf\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3\n\ndef odometry_publisher():\n    pub = rospy.Publisher('odom', Odometry, queue_size=10)\n    rospy.init_node('odometry_publisher', anonymous=True)\n    broad = tf.TransformBroadcaster()\n\n    r = rospy.Rate(1) # 1Hz\n    seq = 0\n\n    x = 0.0\n    y = 0.0\n    th = 0.0\n    vx = 0.1\n    vy = -0.1\n    vth = 0.1\n\n    current_time = rospy.Time.now()\n    last_time = rospy.Time.now()\n\n    while not rospy.is_shutdown():\n        current_time = rospy.Time.now()\n\n        dt = (current_time - last_time).to_sec()\n        delta_x = (vx * cos(th) - vy * sin(th)) * dt\n        delta_y = (vx * sin(th) + vy * cos(th)) * dt\n        delta_th = vth * dt\n\n        x += delta_x\n        y += delta_y\n        th += delta_th\n\n        odom_quat = tf.transformations.quaternion_from_euler(0, 0, th)\n\n        broad.sendTransform((x, y, 0.0), odom_quat, current_time, \"base_link\", \"odom\")\n\n        odom = Odometry()\n        odom.header.seq = seq\n        odom.header.stamp = current_time\n        odom.header.frame_id = \"odom\"\n\n        odom.pose.pose = Pose(Point(x, y, 0.0), Quaternion(*odom_quat))\n\n        odom.child_frame_id = \"base_link\"\n        odom.twist.twist = Twist(Vector3(vx, vy, 0), Vector3(0, 0, vth))\n\n        pub.publish(odom)\n        rospy.loginfo(odom)\n\n        last_time = current_time\n        seq += 1\n\n        r.sleep()\n\nif __name__ == '__main__':\n    try:\n        odometry_publisher()\n    except rospy.ROSInterruptException: pass\n","sub_path":"scripts/oddom.py","file_name":"oddom.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"337527176","text":"#!/usr/bin/env python3\n#\n#   Genrates user defined noisy NMR FIDs for testing purposes\n#   The output is a vector of discrete values in the form of a file, one value on each line\n#   You have can adjust the 5 parameters AMPLITUDE, SNR, FREQUENCY, DECAY_TIME, NUM_POINTS\n# \n#   Hacking:  this script supports waveforms with 1 fundamental frequency, a specified T2*,\n#   and a collection time (implicit in the locked sample rate of 7502 points regardless\n#   of the collection time - that is specific to my rig, so sorry about that.\n#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport random\n\n\n# Adjust these 5 parameters to constrcut your desired signal\nAMPLITUDE       = 70\nSNR             = 120\nFREQUENCY       = 8750.338\nDECAY_TIME      = .00023\nNUM_POINTS      = 6145\nCOLLECTION_TIME     = .002      #   [s]\n# UNMODIFIED_SAMPLE_N is fixed by my actual spectrometer\nUNMODIFIED_SAMPLE_N = 7502\nSAMPLE_RATE         = UNMODIFIED_SAMPLE_N/COLLECTION_TIME # [s**-1]\nBIN_SIZE            = COLLECTION_TIME/UNMODIFIED_SAMPLE_N\nDC_OFFSET           = 5\n# The way noise is implemented in fid() is not how it really emerges in NMR. It really is distributed with a mean RMS noise voltage specified.  Here, the added noise is eithr a random number between +V_noise, -V_noise (probability 2/3) or 0 (probabilty 1/3).  \n\n# The function that generated the signal vector\n\ndef fid(amplitude, snr, frequency, decay_time, dc_offset, time):     \n    return amplitude/snr*random.randint(-1,1)*random.random() + amplitude*math.exp(-time/decay_time)*math.sin(2*math.pi*frequency*time) + dc_offset\n\ndef write_data(amplitude, snr, frequency, decay_time, dc_offset):\n    yvals = []\n    tvals = np.linspace(0,.002*NUM_POINTS/7502,NUM_POINTS)\n    for time in tvals:\n        yvals.append(fid(amplitude, snr, frequency,decay_time,dc_offset,time))\n    with open(\"sim.amp.{}.snr.{}.freq.{}.t2.{}.dcoffset.{}\".format(amplitude,snr,frequency,decay_time, dc_offset), 'w') as f:\n        for val in yvals:\n            f.write(str(val)+'\\n')\n        f.close()\n\ndef main():\n    print(\"sample rate:\\t{}\\tper second\\nbin size:\\t{}\\tseconds per bin\".format(SAMPLE_RATE, BIN_SIZE))\n    print(\"Amplitude:\\t{} units\\nSNR:\\t{}\\nFrequency:\\t{} Hz\\nT2*:\\t{}\\nDC Offset:\\t{}\\n...\".format(AMPLITUDE,SNR, FREQUENCY, DECAY_TIME, DC_OFFSET))\n    write_data(AMPLITUDE, SNR, FREQUENCY, DECAY_TIME, DC_OFFSET)\n    print(\"Data written successfully.\")\n\nif __name__ == '__main__':\n    main()\n\n#write_data(AMPLITUDE, SNR, FREQUENCY, DECAY_TIME)\n\n\n","sub_path":"python/signal_processing/test_data/write_data.py","file_name":"write_data.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"67150714","text":"from typing import List, NamedTuple\n\n\nclass Table(NamedTuple):\n    primary_key: str\n    keys: List[str]\n    locked: bool = True\n\n\nTABLES = {\n    \"bot_events\": Table(  # Events to be sent to the bot via websocket\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",\n            \"data\"\n        ])\n    ),\n\n    \"bot_logs\": Table(  # Logs uploaded via the logs API endpoint\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",\n            \"log_data\"\n        ])\n    ),\n\n    \"superstarify\": Table(  # Users in superstar prison\n        primary_key=\"user_id\",\n        keys=sorted([\n            \"user_id\",\n            \"end_timestamp\",\n            \"forced_nick\"\n        ])\n    ),\n\n    \"superstarify_namelist\": Table(  # Names and images of music superstars\n        primary_key=\"name\",\n        keys=sorted([\n            \"name\",\n            \"image_url\"\n        ]),\n        locked=False\n    ),\n\n    \"code_jams\": Table(  # Information about each code jam\n        primary_key=\"number\",\n        keys=sorted([\n            \"date_end\",  # datetime\n            \"date_start\",  # datetime\n            \"end_html\",  # str\n            \"end_rst\",  # str\n            \"info_rst\",  # str\n            \"info_html\",  # str\n            \"number\",  # int\n            \"participants\",  # list[str]\n            \"repo\",  # str\n            \"state\",  # str\n            \"task_html\",  # str\n            \"task_rst\",  # str\n            \"teams\",  # list[str]\n            \"theme\",  # str\n            \"title\",  # str\n            \"winning_team\"  # str\n        ])\n    ),\n\n    \"code_jam_forms\": Table(  # Application forms for each jam\n        primary_key=\"number\",\n        keys=sorted([\n            \"number\",  # int\n            \"preamble_rst\",  # str\n            \"preamble_html\",  # str\n            \"questions\"  # list[dict[str, str]]  {title, type, input_type, options?}\n        ])\n    ),\n\n    \"code_jam_questions\": Table(  # Application form questions\n        primary_key=\"id\",\n        keys=sorted([\n            \"data\",  # dict\n            \"id\",  # uuid\n            \"optional\",  # bool\n            \"title\",  # str\n            \"type\",  # str\n        ])\n    ),\n\n    \"code_jam_responses\": Table(  # Application form responses\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",  # uuid\n            \"snowflake\",  # str\n            \"jam\",  # int\n            \"answers\",  # list [{question, answer, metadata}]\n            \"approved\"  # bool\n        ])\n    ),\n\n    \"code_jam_teams\": Table(  # Teams for each jam\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",  # uuid\n            \"name\",  # str\n            \"members\",  # list[str]\n            \"repo\",  # str\n            \"jam\"  # int\n        ])\n    ),\n\n    \"code_jam_infractions\": Table(  # Individual infractions for each user\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",  # uuid\n            \"participant\",  # str\n            \"reason\",  # str\n            \"number\",  # int (optionally -1 for permanent)\n            \"decremented_for\"  # list[int]\n        ])\n    ),\n\n    \"code_jam_participants\": Table(  # Info for each participant\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",  # str\n            \"gitlab_username\",  # str\n            \"timezone\"  # str\n        ])\n    ),\n\n    \"member_chunks\": Table(\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",  # str\n            \"chunk\",  # list\n        ])\n    ),\n\n    \"oauth_data\": Table(  # OAuth login information\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",\n            \"access_token\",\n            \"expires_at\",\n            \"refresh_token\",\n            \"snowflake\"\n        ])\n    ),\n\n    \"off_topic_names\": Table(  # Names for the off-topic category channels\n        primary_key=\"name\",\n        keys=(\"name\",),\n        locked=False\n    ),\n\n    \"tags\": Table(  # Tag names and values\n        primary_key=\"tag_name\",\n        keys=sorted([\n            \"tag_name\",\n            \"tag_content\",\n            \"image_url\"\n        ]),\n        locked=False\n    ),\n\n    \"users\": Table(  # Users from the Discord server\n        primary_key=\"user_id\",\n        keys=sorted([\n            \"avatar\",\n            \"user_id\",\n            \"roles\",\n            \"username\",\n            \"discriminator\"\n        ])\n    ),\n\n    \"wiki\": Table(  # Wiki articles\n        primary_key=\"slug\",\n        keys=sorted([\n            \"slug\",\n            \"headers\",\n            \"html\",\n            \"rst\",\n            \"text\",\n            \"title\"\n        ])\n    ),\n\n    \"wiki_revisions\": Table(  # Revisions of wiki articles\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",\n            \"date\",\n            \"post\",\n            \"slug\",\n            \"user\"\n        ])\n    ),\n\n    \"_versions\": Table(  # Table migration versions\n        primary_key=\"table\",\n        keys=sorted([\n            \"table\",\n            \"version\"\n        ])\n    ),\n\n    \"pydoc_links\": Table(  # pydoc_links\n        primary_key=\"package\",\n        keys=sorted([\n            \"base_url\",\n            \"inventory_url\",\n            \"package\"\n        ]),\n        locked=False\n    ),\n\n    \"bot_settings\": Table(\n        primary_key=\"key\",\n        keys=sorted([\n            \"key\",   # str\n            \"value\"  # any\n        ])\n    ),\n\n    \"bot_infractions\": Table(\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",                # str\n            \"user_id\",           # str\n            \"actor_id\",          # str\n            \"reason\",            # str\n            \"type\",              # str\n            \"inserted_at\",       # datetime\n            \"expires_at\",        # datetime\n            \"closed\",            # bool\n            \"hidden\",            # bool\n            \"legacy_rowboat_id\"  # str\n        ])\n    ),\n\n    \"watched_users\": Table(  # Users being monitored by the bot's BigBrother cog\n        primary_key=\"user_id\",\n        keys=sorted([\n            \"user_id\",\n            \"channel_id\"\n        ])\n    ),\n\n    \"reminders\": Table(\n        primary_key=\"id\",\n        keys=sorted([\n            \"id\",          # str\n            \"user_id\",     # str\n            \"channel_id\",  # str\n            \"expires_at\",  # datetime\n            \"content\"      # str\n        ])\n    )\n}\n","sub_path":"pysite/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"213056211","text":"# coding=utf-8\n\n__all__ = [\"Downloader\"]\n\nfrom kivy.network.urlrequest import UrlRequest\nfrom os.path import join, exists\nfrom os import makedirs, remove\nfrom random import choice\nfrom mapview import CACHE\n\nclass Downloader(object):\n    _instance = None\n\n    @staticmethod\n    def instance():\n        if Downloader._instance is None:\n            Downloader._instance = Downloader()\n        return Downloader._instance\n\n    def __init__(self,  *args):\n        super(Downloader, self).__init__()\n\n        if not exists(CACHE['directory']):\n            makedirs(CACHE['directory'])\n    \n    def download_tile(self, tile):\n        if tile.state == \"done\":\n            return\n        cache_fn = tile.cache_fn\n        if exists(cache_fn):\n            ### libpng error: IDAT: invalid distance too far back\n            try:\n                tile.set_source(cache_fn)\n                return\n            except:\n                remove(cache_fn)\n            \n        tile_y = tile.map_source.get_row_count(tile.zoom) - tile.tile_y - 1\n        uri = tile.map_source.url.format(z=tile.zoom,\n                                         x=tile.tile_x,\n                                         y=tile_y,\n                                         s=choice(tile.map_source.subdomains))\n\n        def success(request, result):\n            # print('SUCCESS:', request.file_path)\n            try:\n                tile.set_source(request.file_path)\n            except:\n                remove(request.file_path)\n\n        def failure(request, result):\n            pass\n\n        def error(request, error):\n            pass\n\n        req = UrlRequest(uri,\n                         on_success=success,\n                         on_failure=failure,\n                         on_error=error,\n                         timeout=5,\n                         method='GET',\n                         file_path=cache_fn)\n        \n        #tile.set_source(cache_fn)\n","sub_path":"mapview/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"555414836","text":"import pytz\nfrom models import User1\nfrom datetime import datetime\ndef del_user(username):\n    u = User1.objects.get(username = username)\n    u.delete()\n\ndef last_logged():\n    z = User1.objects.all()\n    for x in z:\n       if (datetime.now().replace(tzinfo=pytz.UTC) - x.last_login).days > 30:\n           del_user(x.username)\n       else:\n           continue\n\n\n\n\n\n","sub_path":"myapp/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"385006963","text":"#!/usr/bin/env python3\nimport sys\nimport gzip\nimport re\n\nfilename_tbl = sys.argv[1]\nfilename_base = re.sub(r'.bp\\+\\_tbl.gz', '', filename_tbl)\n\nblastp_Evalue_cutoff = 0.0001\nmin_best_targets = 3\n\n\ndef open_file(tmp_filename):\n    f = open(tmp_filename, 'r')\n    if tmp_filename.endswith('.gz'):\n        f = gzip.open(tmp_filename, 'rt')\n    return f\n\n\nblastp_list = dict()\nsys.stderr.write('Read %s\\n' % filename_tbl)\nf_bp = open_file(filename_tbl)\nfor line in f_bp:\n    if line.startswith('#'):\n        continue\n\n    tokens = line.strip().split(\"\\t\")\n    q_id = tokens[0]\n    t_id = tokens[1]\n    evalue = float(tokens[-2])\n    bits = float(tokens[-1])\n\n    if evalue > blastp_Evalue_cutoff:\n        continue\n\n    if q_id not in blastp_list:\n        blastp_list[q_id] = dict()\n\n    if t_id not in blastp_list[q_id]:\n        blastp_list[q_id][t_id] = bits\n    elif bits > blastp_list[q_id][t_id]:\n        blastp_list[q_id][t_id] = bits\nf_bp.close()\nsys.stderr.write('Total Sequences: %d\\n' % len(blastp_list))\n\nf_prot_targets = open('%s.prot_targets' % filename_base, 'w')\nfor tmp_h in blastp_list.keys():\n    tmp_best_bits = max(blastp_list[tmp_h].values())\n    tmp_target_list = \\\n                sorted(blastp_list[tmp_h].keys(), key=blastp_list[tmp_h].get, reverse=True)\n    tmp_target_str = ';'.join([\"%s=%.1f\" % (x, blastp_list[tmp_h][x]) for x in tmp_target_list])\n    f_prot_targets.write('%s\\t%.1f\\t%s\\n' % (tmp_h, tmp_best_bits, tmp_target_str))\nf_prot_targets.close()\n","sub_path":"annot/MODtree_bp_tbl-to-prot_targets.py","file_name":"MODtree_bp_tbl-to-prot_targets.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"89863597","text":"# Universidade Federal de Campina Grande - UFCG\n# Programação 1 - 2019.2\n# Guilherme Aureliano\n\ndef divisor(num, lista):\n    retorno = -1\n    for i in range(len(lista)):\n        if lista[i] % num == 0:\n            retorno = i\n            break\n    return retorno\n","sub_path":"unidade6/divisor.py","file_name":"divisor.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"305316689","text":"# 4.\tОпределить, какое число в массиве встречается чаще всего.\nfrom random import randint\n\n\ndef max_counts_in_mass(mass: list):\n    \"\"\"Определяет, какое число в массиве встречается чаще всего\"\"\"\n    # Генерируем словарь \"Число: количество повторений в массиве\"\n    counts = dict()\n    for el in mass:\n        if el in counts:\n            counts[el] += 1\n        else:\n            counts[el] = 1\n\n    return max(counts, key=counts.get)\n\n\nif __name__ == '__main__':\n\n    # Инициализируем массив с повторяющимеся элементами\n    N = 24\n    m = [randint(0, 8) for _ in range(N)]\n\n    print(max_counts_in_mass(m))\n","sub_path":"Lesson_3/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"41651232","text":"import json\nimport os\nimport numpy as np\nimport pickle\nimport cv2\nfrom skimage import exposure\n\nfrom loadAll import normalise_images\nfrom sklearn import preprocessing\n\n\n\"\"\" \n    makepickle(): \n    Converts all frames from all subjects to 4 pickle files: \n        - IP6target: Normalised targets from training subjects of XCam and YCam. Shape of (?, 2) \n        - IP6appleLeftEye, IP6AappleRightEye, IP6AappleFace: Normalised frames from training subjects using IPHONE6/6S\n        . Shape (?, 112,112,1) \n\n\n    Expected Data hierarchy \n    Data \n        -00000\n            -/appleFace/\n                -#frames\n            -/appleLeftEye/\n                -#frames\n            -/appleRightEye/\n                -#frames\n            appleface.json\n            appleLeftEye.json\n            appleRightEye.json\n            dotInfo.json\n            frames.json\n            info.json\n            motion.json\n            screen.json\n            faceGrid.json\n        -00001\n            .... \n\n\n\"\"\"\n\n\n#SUBJECTS_PATH = '/Users/MikiWong/PycharmProjects/FYP_June/data/gazecapture'\n\nSUBJECTS_PATH = '/export/home/mikiwong/Gazecapture_unseen/'\n#SUBJECTS_PATH = '/Users/MikiWong/PycharmProjects/FYP_June/data/gazecapture_v/'\n#SUBJECTS_PATH = '/export/home/mikiwong/Desktop/GazeCapture_Test/'\ntargetfile = 'VAppletarget_0815.pickle'\nxtargetfile = 'VApplextarget_0815.pickle'\nytargetfile = 'VAppleytarget_0815.pickle'\nrightfile = 'VAppleRightEye_0815.pickle'\nleftfile = 'VAppleLeftEye_0815.pickle'\nfacefile = 'VAppleFace_0815.pickle'\n\nMAX_SUBJ = 300\nMAX_FRAMES = 200\nMAX_totFRAMES  = 60000\n\n\ndef makepickle():\n\n    SUBJECTS = os.listdir(SUBJECTS_PATH)\n    target = []\n    xtarget = []\n    ytarget =[]\n    appleRightEyeFrames = []\n    appleLeftEyeFrames = []\n    appleFaceFrames = []\n    subj_count = 0\n    totframes_count =0\n\n    for subject in SUBJECTS:\n        subj_count += 1\n        if totframes_count >= MAX_totFRAMES:\n            break\n        if subj_count >= MAX_SUBJ:\n            break\n        else:\n            if not subject.startswith('.'):\n                SUBJ_DIR = SUBJECTS_PATH + subject\n                FRAMES_DIR = SUBJECTS_PATH + subject + '/frames'\n                INFO_DIR = SUBJECTS_PATH + subject + '/info.json'\n\n                SCREEN_PATH = SUBJ_DIR + '/screen.json'\n                DOTINFO_PATH = SUBJ_DIR + '/dotInfo.json'\n                APPLERIGHTEYEJ = SUBJ_DIR + '/appleRightEye.json'\n                APPLERIGHTEYE = SUBJ_DIR + '/appleRightEye'\n                APPLELEFTEYE = SUBJ_DIR + '/appleLeftEye'\n                APPLEFACE = SUBJ_DIR + '/appleFace'\n\n                with open(INFO_DIR) as json_data:\n                    i = json.load(json_data)\n\n                device = i['DeviceName']\n\n                # if device == 'iPhone 6' or device == 'iPhone 6s' or device == 'iPhone 6S':\n                #     widthpts = 375\n                #     heightpts = 667\n                # else:\n                #     continue\n\n                frames = os.listdir(FRAMES_DIR)\n                frames.sort()\n\n                with open(APPLERIGHTEYEJ) as json_data:\n                    e = json.load(json_data)\n                with open(DOTINFO_PATH) as json_data:\n                    d = json.load(json_data)\n\n                v = e['IsValid']\n                # XPts = d['XPts']\n                # YPts = d['YPts']\n                XCam = d['XCam']\n                YCam = d['YCam']\n\n                frame_count = 0\n                for val, name, x, y in zip(v, frames, XCam, YCam):\n                    if frame_count >= MAX_FRAMES:\n                       break\n                    if val == 1:\n                        frame1 = os.path.join(APPLERIGHTEYE, name)\n                        appleRightEyeFrame = cv2.imread(frame1, cv2.IMREAD_GRAYSCALE)\n                        appleRightEyeFrame = exposure.equalize_hist(appleRightEyeFrame )\n                        frame2 = os.path.join(APPLELEFTEYE, name)\n                        appleLeftEyeFrame = cv2.imread(frame2, cv2.IMREAD_GRAYSCALE)\n                        appleLeftEyeFrame = exposure.equalize_hist(appleLeftEyeFrame )\n                        frame3 = os.path.join(APPLEFACE, name)\n                        appleFaceFrame = cv2.imread(frame3, cv2.IMREAD_GRAYSCALE)\n                        appleFaceFrame = exposure.equalize_hist(appleFaceFrame)\n\n                        appleFaceFrame = cv2.resize(appleFaceFrame, (112, 112))\n                        appleLeftEyeFrame = cv2.resize(appleLeftEyeFrame, (112, 112))\n                        appleRightEyeFrame = cv2.resize(appleRightEyeFrame, (112, 112))\n\n                        #x = x / widthpts\n                        #y = y / heightpts\n\n                        #if x > 1 or y > 1:\n                        #    print(\"Weird >1: \", subject, x, y)\n                        #    break\n                        appleFaceFrames.append(appleFaceFrame)\n                        appleRightEyeFrames.append(appleRightEyeFrame)\n                        appleLeftEyeFrames.append(appleLeftEyeFrame)\n                        target.append(x)\n                        target.append(y)\n                        xtarget.append(x)\n                        ytarget.append(y)\n                        frame_count += 1\n                        totframes_count +=1\n\n\n\n                # Target reshape to x,y\n                # appleFaceFrames = np.reshape(appleFaceFrames, (1, 112,112))\n                # appleRightEyeFrames = np.reshape(appleRightEyeFrames, (1, 112,112))\n                # appleLeftEyeFrames = np.reshape(appleLeftEyeFrames, (1, 112,112))\n                print(\"--------- \", subj_count, \" ---------\")\n                print(\"Subject:\", subject)\n                print(\"Frames for \", subject, \":\", frame_count)\n                print(\"Device name:\", device)\n                #print(\"Device WIDTH/HEIGHT:\", widthpts, heightpts)\n\n\n    target = np.reshape(target, (-1, 2))\n    xtarget = np.reshape(target, (-1, 1))\n    ytarget = np.reshape(ytarget, (-1, 1))\n\n\n\n    # print(\"TargetL\", target)\n\n    appleFaceFrames = np.reshape(appleFaceFrames, (-1, 112, 112, 1))\n    appleRightEyeFrames = np.reshape(appleRightEyeFrames, (-1, 112, 112, 1))\n    appleLeftEyeFrames = np.reshape(appleLeftEyeFrames, (-1, 112, 112, 1))\n\n    # print(\"LEFTL\", appleLeftEyeFrames)\n\n    # appleFaceFrames, appleRightEyeFrames, appleLeftEyeFrames = normalise_images(appleFaceFrames, appleRightEyeFrames,\n    #                                                                             appleLeftEyeFrames)\n\n    print(\"F/L/R/T shapes. Should be not more than 50 samples per subject : \", appleFaceFrames.shape,\n          appleRightEyeFrames.shape, appleLeftEyeFrames.shape, target.shape)\n    print(\"Subject count:\", subj_count)\n    print(\"Frames count:\", totframes_count)\n\n    with open(targetfile, 'wb') as output:\n        pickle.dump(target, output, protocol=4)\n    with open(xtargetfile, 'wb') as output:\n        pickle.dump(xtarget, output,protocol=4)\n    with open(ytargetfile, 'wb') as output:\n        pickle.dump(ytarget, output,protocol=4)\n    with open(rightfile, 'wb') as output:\n        pickle.dump(appleRightEyeFrames, output,protocol=4)\n\n    with open(leftfile, 'wb') as output:\n        pickle.dump(appleLeftEyeFrames, output,protocol=4)\n\n    with open(facefile, 'wb') as output:\n        pickle.dump(appleFaceFrames, output,protocol=4)\n\n        return appleFaceFrames, appleLeftEyeFrames, appleRightEyeFrames, target\n\n\nmakepickle()","sub_path":"use_gazecapture2.py","file_name":"use_gazecapture2.py","file_ext":"py","file_size_in_byte":7395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"631947367","text":"import os\nimport sys\nsys.path.insert(1, os.getcwd())\nsys.path.insert(1, '../')\nfrom tqdm import tqdm\nfrom webapp import db\nfrom webapp.models import Entry, Link, Translation, Retrieval\nfrom webapp.retrieval import retrieve_neighbours_en\nfrom sqlalchemy import func, and_\nfrom argparse import ArgumentParser\n\n\ndef store_retrieved(model, langs):\n    \n    reqs = db.session.query(Entry.id).filter(Entry.lang.in_(langs)).all()\n    reqs = [req.id for req in reqs]\n    queries = db.session.query(Translation)\\\n                        .filter(and_(Translation.model==model, Translation.parent_id.in_(reqs)))\\\n                        .all()\n    for q in tqdm(queries):\n        if q.translated:\n            exists = Retrieval.query.filter(and_(Retrieval.query_id==q.parent_id,\\\n                                         Retrieval.model==model))\\\n                                         .first()\n            if not exists:\n                try:\n                    retrieved = retrieve_neighbours_en(q.parent_id, model)\n                except:\n                    print(q.parent_id,file=error)\n                    continue\n                else:\n                    retrieved_id = retrieved[0][0]\n                    score = retrieved[0][1]   \n                    entry = Retrieval(query_id=q.parent_id, retrieved_id=retrieved_id,\\\n                                      score=score, model=model)\n                    try:\n                        db.session.add(entry)\n                        db.session.commit()\n                    except:\n                        print(q.parent_id,file=error)\n\nif __name__ == '__main__':\n    langs = ['hi', 'ta', 'te', 'ml', 'bn', 'gu', 'mr', 'pa', 'or'] #[ur]\n    parser=ArgumentParser()\n    parser.add_argument('--model', help='retrieval based on model used for tanslation', required=True)\n    args = parser.parse_args()\n    model = args.model\n    error = open('retrieval_error.txt', 'a')\n    store_retrieved(model, langs)","sub_path":"cli/store-retrieved.py","file_name":"store-retrieved.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"347503557","text":"from django.conf.urls import url\nimport views\n\n__author__ = 'NoahButler'\n\n\nurlpatterns = [\n    url(r'^gps/queue/$', views.receive_queue_gps),\n    url(r'^send/sound/$', views.receive_added_sound),\n    url(r'^new/queue/$', views.receive_new_queue),\n    url(r'^send/token/$', views.receive_token_update),\n    url(r'^send/name/$', views.receive_queue_name),\n    url(r'^request/queue/$', views.request_queue),\n    url(r'^close/queue/$', views.close_queue),\n    url(r'^queue/exists/$', views.queue_exists),\n    url(r'^gps/sender/$', views.local_queues),\n    url(r'^liked/sound/$', views.received_like_sound),\n    url(r'^login/redirect/$', views.login_redirect),\n\n]\n\n","sub_path":"SQueue/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"126285886","text":"# -*- coding: utf-8 -*-\n#\n#  This file is part of Bioconvert software\n#\n#  Copyright (c) 2017 - Bioconvert Development Team\n#\n#  Distributed under the terms of the 3-clause BSD license.\n#  The full license is in the LICENSE file, distributed with this software.\n#\n#  website: https://github.com/biokit/bioconvert\n#  documentation: http://bioconvert.readthedocs.io\n#\n##############################################################################\n\"\"\"Convert :term:`VCF` file to :term:`BED` file\"\"\"\nfrom bioconvert import ConvBase, extensions\nimport colorlog\nlogger = colorlog.getLogger(__name__)\n\n\n__all__ = [\"VCF2BED\"]\n\n\nclass VCF2BED(ConvBase):\n    \"\"\"\n    Convert VCF file to BED file by extracting positions.\n\n    Available methods:\n\n    - awk::\n\n        awk '! /\\#/' INPUT | awk '{if(length($4) > length($5)) \n        print $1\"\\t\"($2-1)\"\\t\"($2+length($4)-1);\n        else print $1\"\\t\"($2-1)\"\\t\"($2+length($5)-1)}' > OUTPUT\n\n        This method report an interval of 1 for SNP, the length of the insertion or the length of \n        the deleted part in case of deletion.\n    \"\"\"\n\n    def __init__(self, infile, outfile):\n        \"\"\"\n        :param str infile: The path to the input VCF file.\n        :param str outfile: The path to the output file.\n        \"\"\"\n        super().__init__(infile, outfile)\n        self._default_method = \"awk\"\n\n    def _method_awk(self, *args, **kwargs):\n        \"\"\"\n        do the conversion :term`VCF` -> :term:'BED` using awk\n\n        :return: the standard output\n        :rtype: :class:`io.StringIO` object.\n        \"\"\"\n        awkcmd = \"\"\"awk '{{if(length($4) > length($5)) print $1,($2-1),($2+length($4)-1); else print $1,($2-1),($2+length($5)-1)}}' OFS='\\t'\"\"\"\n        cmd = \"awk '! /\\#/' {} | {} > {}\".format(self.infile, awkcmd, self.outfile)\n        self.execute(cmd)\n","sub_path":"bioconvert/vcf2bed.py","file_name":"vcf2bed.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"82426644","text":"from typing import TYPE_CHECKING\n\nfrom rest_framework import serializers\nfrom rest_polymorphic.serializers import PolymorphicSerializer\n\nfrom indicators.models import Variable, CensusVariable, CKANVariable, CensusVariableSource\nfrom indicators.serializers.source import CKANSourceSerializer\n\nif TYPE_CHECKING:\n    pass\n\n\nclass DenominatorSerializer(serializers.ModelSerializer):\n    locale_options = serializers.JSONField()\n\n    class Meta:\n        model = Variable\n        fields = (\n            'id',\n            'name',\n            'slug',\n            'depth',\n            'percent_label',\n            'short_name',\n            'locale_options'\n        )\n\n\nclass VariableSerializer(serializers.ModelSerializer):\n    denominators = DenominatorSerializer(many=True)\n    locale_options = serializers.JSONField()\n\n    class Meta:\n        model = Variable\n        fields = (\n            'id',\n            'name',\n            'slug',\n            'description',\n            'short_name',\n            'units',\n            'unit_notes',\n            'denominators',\n            'sources',\n            'depth',\n            'display_name',\n            'percent_label',\n            'locale_options',\n        )\n\n\nclass CensusVariableSourceSerializer(serializers.ModelSerializer):\n    name = serializers.ReadOnlyField(source='source.name')\n    slug = serializers.ReadOnlyField(source='source.slug')\n    description = serializers.ReadOnlyField(source='source.description')\n    dataset = serializers.ReadOnlyField(source='source.dataset')\n    info_link = serializers.ReadOnlyField(source='source.info_link')\n\n    class Meta:\n        model = CensusVariableSource\n        fields = (\n            'id',\n            'name',\n            'slug',\n            'description',\n            'dataset',\n            'info_link',\n        )\n\n\nclass CensusVariableSerializer(VariableSerializer):\n    sources = CensusVariableSourceSerializer(source='variable_to_source', many=True)\n\n    class Meta:\n        model = CensusVariable\n        fields = VariableSerializer.Meta.fields + (\n            'sources',\n        )\n\n\nclass CKANVariableSerializer(VariableSerializer):\n    sources = CKANSourceSerializer(many=True)\n\n    class Meta:\n        model = CKANVariable\n        fields = VariableSerializer.Meta.fields + (\n            'sources',\n        )\n\n\nclass VariablePolymorphicSerializer(PolymorphicSerializer):\n    model_serializer_mapping = {\n        CensusVariable: CensusVariableSerializer,\n        CKANVariable: CKANVariableSerializer,\n    }\n\n\n# Brief\nclass CensusVariableBriefSerializer(VariableSerializer):\n    sources = CensusVariableSourceSerializer(source='variable_to_source', many=True)\n    denominators = DenominatorSerializer(many=True)\n\n    class Meta:\n        model = CensusVariable\n        fields = VariableSerializer.Meta.fields + ('sources',)\n\n\nclass CKANVariableBriefSerializer(serializers.ModelSerializer):\n    sources = CKANSourceSerializer(many=True)\n    denominators = DenominatorSerializer(many=True)\n\n    class Meta:\n        model = CKANVariable\n        fields = VariableSerializer.Meta.fields + ('sources',)\n\n\nclass BriefVariablePolymorphicSerializer(PolymorphicSerializer):\n    model_serializer_mapping = {\n        CensusVariable: CensusVariableBriefSerializer,\n        CKANVariable: CKANVariableBriefSerializer,\n    }\n\n\n# With Viz\nclass CensusVizVariableSerializer(VariableSerializer):\n    denominators = DenominatorSerializer(many=True)\n\n    class Meta:\n        model = CensusVariable\n        fields = VariableSerializer.Meta.fields + ('sources',)\n\n\nclass CKANVizVariableSerializer(VariableSerializer):\n    denominators = DenominatorSerializer(many=True)\n\n    class Meta:\n        model = CKANVariable\n        fields = VariableSerializer.Meta.fields + ('sources', )\n\n\nclass VizVariablePolymorphicSerializer(PolymorphicSerializer):\n    model_serializer_mapping = {\n        CensusVariable: CensusVizVariableSerializer,\n        CKANVariable: CKANVizVariableSerializer,\n    }\n","sub_path":"indicators/serializers/variable.py","file_name":"variable.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"48490580","text":"#!/usr/bin/env python3\n\nimport aes\nimport base64\nimport json\nimport helper\nimport os\nimport sys\nimport tcp\nimport threading\nimport traceback\n\n# read node id\nnode_id = sys.argv[1] if len(sys.argv) > 1 else input('Enter node ID: ')\n\n# get script directory\ndirname = os.path.dirname(os.path.realpath(__file__))\n\n# load corresponding configuration file\nwith open(dirname+'/cfg/node/{}.json'.format(node_id)) as f:\n    cfg = json.load(f)\n\n# connect to gateway\ns = tcp.connect(cfg['gw']['host'], cfg['gw']['port'])\n\nnode_ciphs = {}\n\n\n# worker thread for listening to gateway messages\ndef gw_rx(c):\n    try:\n        f = helper.aes_makefile(s, c)\n\n        while True:\n            msg = f.readline().decode()\n            if len(msg) == 0:\n                break\n            msg = json.loads(msg)\n            print('\\r>> gw:\\t', msg, sep='', file=sys.stderr)\n\n            # received JSON must have `type` field\n            if 'type' not in msg:\n                raise ValueError\n\n            if msg['type'] == 'msg-from-node':\n                src = msg['from']\n                msg = msg['msg']\n\n                # received JSON must have `type` field\n                if 'type' not in msg:\n                    if src in node_ciphs:\n                        msg = json.loads(node_ciphs[src].decrypt(\n                            base64.decodebytes(msg.encode())\n                        ).decode())\n                        print('** dec:\\t', msg, sep='', file=sys.stderr)\n                    else:\n                        raise ValueError\n\n                if msg['type'] == 'aes-cfb-dh-req':\n                    gl, pl = 3, 256\n                    helper.aes_send_json(s, c, {\n                        'type': 'send-to-node',\n                        'to': src,\n                        'msg': {\n                            'type': 'aes-cfb-dh-init',\n                            'gl': gl,\n                            'pl': pl\n                        }\n                    })\n\n                    node_ciphs[src] = aes.cfb_dh_recv(\n                        gl, pl,\n                        helper.AESBase64JsonSock(s, c, 'msg', {\n                            'type': 'send-to-node',\n                            'to': src\n                        }, {\n                            'type': 'msg-from-node',\n                            'from': src\n                        })\n                    )\n                elif msg['type'] == 'aes-cfb-dh-init':\n                    node_ciphs[src] = aes.cfb_dh_init(\n                        msg['gl'], msg['pl'],\n                        helper.AESBase64JsonSock(s, c, 'msg', {\n                            'type': 'send-to-node',\n                            'to': src\n                        }, {\n                            'type': 'msg-from-node',\n                            'from': src\n                        })\n                    )\n\n            else:\n                raise ValueError\n    except KeyboardInterrupt:\n        pass\n    except Exception:\n        traceback.print_exc()\n\n    s.close()\n\ntry:\n    # pre-encryption communication\n    c = helper.aes_request(s)\n\n    threading.Thread(target=gw_rx, args=(c,)).start()\n\n    # encrypted communication\n    # send node id\n    helper.aes_send_json(s, c, {'type': 'set-id', 'id': node_id})\n\n    # send whatever the user types on screen, encrypted\n    print('Enter target node ID in one line, and the message in the next one')\n    print('Subsequent entries are permitted')\n\n    while True:\n        to = input()\n\n        if to not in node_ciphs:\n            helper.aes_send_json(s, c, {\n                'type': 'send-to-node',\n                'to': to,\n                'msg': {\n                    'type': 'aes-cfb-dh-req'\n                }\n            })\n\n        msg = input()\n\n        helper.aes_send_json(s, c, {\n            'type': 'send-to-node',\n            'to': to,\n            'msg': base64.encodebytes(node_ciphs[to].encrypt(json.dumps({\n                'type': 'reading',\n                'value': msg\n            }).encode())).decode()\n        })\nexcept (EOFError, KeyboardInterrupt):\n    pass\nexcept Exception:\n    traceback.print_exc()\n\ns.close()\n","sub_path":"src/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"474312777","text":"import torch as tr\nimport cv2\nimport numpy as np\nimport rospkg\n\npath = rospkg.RosPack().get_path('team105')\n\ndevice = tr.device(\"cuda:0\" if tr.cuda.is_available() else \"cpu\")\n\nclass CNN32(tr.nn.Module):\n    def __init__(self):\n        super(CNN32, self).__init__() #3x32x32\n        self.pool = tr.nn.MaxPool2d(2, 2)\n\n        self.conv1 = tr.nn.Conv2d(3, 32, 5) #28 (in_channels=3, out_channels=64, kernel_size=5, stride=1, padding=0)\n        #pool 14\n        self.conv2 = tr.nn.Conv2d(32, 64,3) #12\n        #pool 6\n        self.conv3 = tr.nn.Conv2d(64, 128, 3) #4\n        #pool 2\n        self.fc1 = tr.nn.Linear(128 *2 *2, 1024) #\n        self.fc2 = tr.nn.Linear(1024, 512)\n        self.fc3 = tr.nn.Linear(512, 3)\n\n\n    def forward(self, X): #3*32*32 #3*227*227\n        X = tr.nn.functional.relu(self.conv1(X))\n        X = self.pool(X)\n        X = tr.nn.functional.relu(self.conv2(X))\n        X = self.pool(X)\n        X = tr.nn.functional.relu(self.conv3(X))\n        X = self.pool(X)\n\n        X = X.view(X.size(0), -1)\n\n        X = tr.tanh(self.fc1(X))\n        X = tr.tanh(self.fc2(X))\n        X = tr.nn.functional.softmax(self.fc3(X), dim=1)\n        return X\n\nnet= CNN32().to(device)\nnet.load_state_dict(tr.load(path + '/param/sign_classi_param_9932_half', map_location=device))\n\ndef predict(img, new_size=32):\n    img = np.array(img, dtype= np.float32) / 255.\n    img = cv2.resize(img, (new_size, new_size))\n\n    img= img.reshape(1,new_size,new_size,3).transpose((0,3,1,2))\n\n    with tr.no_grad():\n        img = tr.from_numpy(img).to(device)\n        output= net(img)\n        output= tr.argmax(output)\n\n    return int(output) #0= not turn; 1= turn right, 2= turn left\n\n# with tr.no_grad():\n#     # while True:\n#     #     dir= raw_input(\"file directory: \")\n#     #     if dir == '': break\n#     for i in range(24,28):\n#         dir= 'other imgs/o27.png'#'other imgs/o' + str(i) + '.png'\n#\n#         img= cv2.imread(dir)\n#         img= np.flip(img,1)\n#         cv2.imshow(str(predict(img)), cv2.resize(img, (150,150)))\n#         cv2.waitKey(0)\n","sub_path":"src/sign_classi.py","file_name":"sign_classi.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"269838261","text":"def anagrams(word, words):\n    word_letters = sorted(list(word))\n    unsorted_letters = [list(x) for x in words]\n    words_letters = [sorted(list(x)) for x in words]\n    anagram_tf = [cmp(x, word_letters) for x in words_letters]\n    final_anagram = []\n    x = 0\n    while x < len(unsorted_letters):\n        if anagram_tf[x] == 0:\n            final_anagram.append(words[x])\n        x += 1\n    return final_anagram","sub_path":"projects/Python-Kata/Kata 5/Where my anagrams at.py","file_name":"Where my anagrams at.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"563173705","text":"from mongoengine import *\nfrom mongoengine.queryset.visitor import Q\nimport csv\nfrom datetime import datetime\n\nhost = ''\ndb = ''\nconnect(db, host=host)\n\nclass Problem(Document):\n    questionNo = IntField()\n    question = StringField(required=True)\n    description = StringField(required=True)\n    answer = StringField(required=True)\n    note = StringField()\n    understand = BooleanField(default=False)\n    importance = IntField(default=5) #1-10?\n    category = StringField(required=True)\n    sub_category = StringField()\n    last_review_date = DateTimeField()\n    review_dates = ListField()\n\n# def getAllProblems():\n#     problems = Problem.objects()\n#     json_data = problems.to_json()\n#     return json_data\n\ndef readFromCSV():\n    filename = \"import.csv\"\n\n    rows = [] \n\n    with open(filename, 'r', encoding='utf-8') as csvfile: \n        csvreader = csv.reader(csvfile)         \n        fields = next(csvreader) \n\n        for row in csvreader: \n            rows.append(row) \n\n    # questionNo\n    # description\n    # sub_category\n    # note\n    # last_review_date\n    # category\n    for row in rows:\n        date = datetime.strptime(row[4], '%m/%d/%Y' )\n        p = Problem()\n        p.questionNo = row[0]\n        p.question = row[1]\n        p.sub_category = row[2]\n        p.note = row[3]\n        p.last_review_date = date\n        p.category = row[5]\n        p.description = row[6]\n        p.review_dates.append(date)\n        p.answer = ''\n        p.save()\n\n    # print (len(problems))\n    # Problem.objects.insert(problems, load_bulk=False)\n\nif __name__ == \"__main__\":\n    readFromCSV()\n","sub_path":"other/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"99995392","text":"\"\"\"\nImage preprocessing modules.\n\nThis code is brought from https://github.com/CuriousAI/ladder/blob/master/nn.py\n\"\"\"\nimport scipy\nimport numpy as np\n\n\nclass ZCA(object):\n    def __init__(self, n_components=None, data=None, filter_bias=0.1):\n        self.filter_bias = np.float32(filter_bias)\n        self.P = None\n        self.P_inv = None\n        self.n_components = 0\n        self.is_fit = False\n        if n_components and data:\n            self.fit(n_components, data)\n\n    def fit(self, n_components, data):\n        if len(data.shape) == 2:\n            self.reshape = None\n        else:\n            assert n_components == np.product(data.shape[1:]), \\\n                'ZCA whitening components should be %d for convolutional data'\\\n                % np.product(data.shape[1:])\n            self.reshape = data.shape[1:]\n\n        data = self._flatten_data(data)\n        assert len(data.shape) == 2\n        n, m = data.shape\n        self.mean = np.mean(data, axis=0)\n\n        bias = self.filter_bias * scipy.sparse.identity(m, 'float32')\n        cov = np.cov(data, rowvar=0, bias=1) + bias\n        eigs, eigv = scipy.linalg.eigh(cov)\n\n        assert not np.isnan(eigs).any()\n        assert not np.isnan(eigv).any()\n        assert eigs.min() > 0\n\n        if self.n_components:\n            eigs = eigs[-self.n_components:]\n            eigv = eigv[:, -self.n_components:]\n\n        sqrt_eigs = np.sqrt(eigs)\n        self.P = np.dot(eigv * (1.0 / sqrt_eigs), eigv.T)\n        assert not np.isnan(self.P).any()\n        self.P_inv = np.dot(eigv * sqrt_eigs, eigv.T)\n\n        self.P = np.float32(self.P)\n        self.P_inv = np.float32(self.P_inv)\n\n        self.is_fit = True\n\n    def apply(self, data, remove_mean=True):\n        data = self._flatten_data(data)\n        d = data - self.mean if remove_mean else data\n        return self._reshape_data(np.dot(d, self.P))\n\n    def inv(self, data, add_mean=True):\n        d = np.dot(self._flatten_data(data), self.P_inv)\n        d += self.mean if add_mean else 0.\n        return self._reshape_data(d)\n\n    def _flatten_data(self, data):\n        if self.reshape is None:\n            return data\n        assert data.shape[1:] == self.reshape\n        return data.reshape(data.shape[0], np.product(data.shape[1:]))\n\n    def _reshape_data(self, data):\n        assert len(data.shape) == 2\n        if self.reshape is None:\n            return data\n        return np.reshape(data, (data.shape[0],) + self.reshape)\n\n\nclass ContrastNorm(object):\n    def __init__(self, scale=55, epsilon=1e-8):\n        self.scale = np.float32(scale)\n        self.epsilon = np.float32(epsilon)\n\n    def apply(self, data, copy=False):\n        if copy:\n            data = np.copy(data)\n        data_shape = data.shape\n        if len(data.shape) > 2:\n            data = data.reshape(data.shape[0], np.product(data.shape[1:]))\n\n        assert len(data.shape) == 2, 'Contrast norm on flattened data'\n\n        data -= data.mean(axis=1)[:, np.newaxis]\n\n        norms = np.sqrt(np.sum(data ** 2, axis=1)) / self.scale\n        norms[norms < self.epsilon] = np.float32(1.)\n\n        data /= norms[:, np.newaxis]\n\n        if data_shape != data.shape:\n            data = data.reshape(data_shape)\n\n        return data\n","sub_path":"util/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"127879881","text":"#---- Image processing client ----\n#--------- Written 2019 ----------\nimport socket\nfrom struct import *\nimport threading\nimport globals\n\nPORT = 8085\nIPADDR = '10.19.18.85'\n\n#Function connects up to server and sets sock\ndef connect_to_server(ipaddr):\n\ttry:\n\t\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tprint(sock)\n\texcept socket.error as err:\n\t\tprint(\"Socket creation error\")\n\t\treturn -1\n\n\tsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n\ttry:\n\t\tsock.connect((ipaddr, PORT))\n\texcept socket.error as err:\n\t\tprint(\"Error connecting to server\")\n\t\treturn -1\n\n\treturn sock\n\n#Function creates an message (one of the predefined ones at the top of this \n#file) and sends it\ndef send_message(sock, typ, receiver, lon, lat, alt):\n\t#Init message\n\tif typ == 0:\n\t\tsock.send(pack('icc', typ, b'I', b'N'))\n\n\t#Coord message\n\telif typ == 1:\n\t\tsock.send(pack('iccddd', typ, b'I', receiver.encode('ascii'), lon, lat, alt))\n\n\telse:\n\t\tprint(\"message type not recognized\")\n\n#Function constantly reads from socket\ndef read_message(sock):\n\twhile True:\n\t\tbuff = sock.recv(1024)\n\t\tif buff:\n\t\t\t#The message is an init message\n\t\t\tif int(buff[0]) == 0:\n\t\t\t\tmsg = unpack('icc', buff[0:calcsize('icc')])\n\t\t\t\tprint(\"Init message\")\n\n\t\t\t#The message is a coord message\n\t\t\telif int(buff[0]) == 1:\n\t\t\t\tmsg = unpack('iccddd', buff[0:calcsize('iccddd')])\n\t\t\t\tlon = msg[3] #Is a float\n\t\t\t\tlat = msg[4] #Is a float\n\t\t\t\talt = msg[5] #Is a float\n\t\t\t\tprint(\"Coord message, alt: \" + str(alt))\n\t\t\t\t#Set global variables needed by main program\n\t\t\t\tglobals.image_processing_begin = True\n\t\t\t\tglobals.image_processing_send = True\n\t\t\t\tglobals.latitude = lat\n\t\t\t\tglobals.longitude = lon\n\t\t\t\tglobals.altitude = alt\n\n\t\t\t#The message is a start message\n\t\t\telif int(buff[0]) == 2:\n\t\t\t\tmsg = unpack('icc', buff[0:calcsize('icc')])\n\t\t\t\tprint(\"Start message\")\n\n\t\t\t#The message is an abort message\n\t\t\telif int(buff[0]) == 3:\n\t\t\t\tmsg = unpack('icc', buff[0:calcsize('icc')])\n\t\t\t\tglobals.image_processing_abort = True\n\t\t\t\tprint(\"Abort message\")\n\n\t\t\t#The message is a status message\n\t\t\telif int(buff[0]) == 4:\n\t\t\t\tmsg = unpack('iccdddi', buff[0:calcsize('iccdddi')])\n\t\t\t\tprint(\"Status message\")\n\n\t\t\t#The message is not recognized\n\t\t\telse:\n\t\t\t\tprint(\"Message not recognized\")\n\n#How to connect to the server (do once)\n#sock = connect_to_server(IPADDR)\n#How to tell server that you are the image processing client (do once)\n#send_message(sock, 0, 'N', 0, 0, 0)\n#How to start the listening thread (do once)\n#listening_thread = threading.Thread(target=read_message, args=(sock,), daemon=True)\n#listening_thread.start()\n#How to send a message, this is a coordinate message to main with lon 10, lat 11 and alt 12. This should not be used more than about once per second\n#send_message(sock, 1, 'M', 10, 11, 12)\n#How to close the listening thread, do this at the end of the code once (outside of the while loop)\n#listening_thread.join()\n","sub_path":"TCPClient.py","file_name":"TCPClient.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"402313122","text":"\"\"\"Merge Two Sorted Lists\nMerge two sorted linked lists and return it as a new list. The new list should\nbe made by splicing together the nodes of the first two lists.\n\nExample:\n    Input: 1->2->4, 1->3->4\n    Output: 1->1->2->3->4->4\n\nIdea:\n    - Similar to conqer step in MergeSort\n    - Should run in O(N) and O(1) space.\n\"\"\" \n# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.next = None\n\ndef merge_two_lists(l1, l2):\n    \"\"\"Attemp 2:\n\n    Runtime: O(N)\n    Space: O(1)\n    \"\"\"\n    if not l1: return l2\n    if not l2: return l1\n    \n    sentinel_node = ListNode(-1)\n    curr = sentinel_node\n    while l1 and l2:\n        if l1.val <= l2.val:\n            curr.next, l1 = l1, l1.next\n        else:\n            curr.next, l2 = l2, l2.next\n\n    # Append remaining nodes\n    curr.next = l1 or l2\n    return sentinel_node.next\n\n\n\ndef old_merge_two_lists(l1, l2):\n    \"\"\"Attempt 1:\n    \n    Runtime: O(n)\n    space: O(n)\n\n    \"\"\"\n    if not l1: return l2\n    if not l2: return l1\n    \n    i = l1\n    j = l2\n    merged = None\n    root = None\n    while i and j:\n        if i.val <= j.val:\n            if merged is None:\n                merged = ListNode(i.val)\n                root = merged\n            else:\n                merged.next = ListNode(i.val)\n                merged = merged.next\n            i = i.next\n        else:\n            if merged is None:\n                merged = ListNode(j.val)\n                root = merged\n            else:\n                merged.next = ListNode(j.val)\n                merged = merged.next\n            j = j.next\n    while i:\n        merged.next = ListNode(i.val)\n        merged = merged.next\n        i = i.next\n\n    while j:\n        merged.next = ListNode(j.val)\n        merged = merged.next\n        j = j.next            \n    return root","sub_path":"leetcode/easy_merge_sorted_list.py","file_name":"easy_merge_sorted_list.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"456808960","text":"import sublime, sublime_plugin, os.path\n\nclass OpenFileQuickListCommand(sublime_plugin.TextCommand):\n  def run(self, edit):\n    window = sublime.active_window()\n    views = window.views()\n    self.fullPath = []\n    self.folders = window.folders()\n\n\n    self.fileNames = []\n    for view in views:\n      if view and view.file_name():\n        file = view.file_name()\n        self.fullPath.append(file)\n        self.fileNames.append([self.get_file_name(file), self.replace_root(file)])\n\n    window.show_quick_panel(self.fileNames, self.on_quick_panel_selection, 0, 0)\n\n  def on_quick_panel_selection(self, index):\n    if index > -1:\n      file = self.fullPath[index]\n      print(\"Opening file '%s'\" % (file))\n      self.view.window().open_file(file)\n\n  def get_file_name(self, path):\n    return os.path.basename(path)\n\n  def replace_root(self, path):\n    name = path\n    for folder in self.folders:\n      name = path.replace(folder, \"\")\n\n    return name","sub_path":"OpenFileQuickList.py","file_name":"OpenFileQuickList.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"201493292","text":"#use dic to clone this graph\n\n\n# Definition for a undirected graph node\n# class UndirectedGraphNode:\n#     def __init__(self, x):\n#         self.label = x\n#         self.neighbors = []\nfrom collections import deque\n\nclass Solution:\n    # @param node, a undirected graph node\n    # @return a undirected graph node\n    def cloneGraph(self, node):\n        if node == None:\n            return None\n        q = deque([node])\n        dic = {}\n        while len(q) != 0:\n            tmp = q.popleft()\n            dic[tmp] = UndirectedGraphNode(tmp.label)\n            for neighbor in tmp.neighbors:\n                if neighbor not in dic:\n                    q.append(neighbor)\n        for origin, clone in dic.items():\n            for neighbor in origin.neighbors:\n                clone.neighbors.append(dic[neighbor])\n        return dic[node]\n","sub_path":"algorithms/133. Clone Graph.py","file_name":"133. Clone Graph.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"590693675","text":"\"\"\"\nReverse Link List II\n====================\n\nReverse a linked list from position m to n. Do it in-place and in one-pass.\n\nFor example:\nGiven 1->2->3->4->5->NULL, m = 2 and n = 4,\n\nreturn 1->4->3->2->5->NULL.\n\"\"\"\n\nfrom __future__ import print_function\nfrom linked_list import Node\n\n\ndef reverse(l, m, n):\n    node = l\n    prev = None\n\n    for _ in range(m):\n        prev = node\n        node = node.next\n\n    head_tail = prev\n    rev_tail = node\n\n    for _ in range(n-m+1):\n        if not node:\n            break\n        next = node.next\n        node.next = prev\n        prev = node\n        node = next\n\n    rev_head = prev\n    tail_head = node\n\n    if head_tail is not None:\n        head_tail.next = rev_head\n    rev_tail.next = tail_head\n\n    return l if m else rev_head\n\n\nl = Node.from_iterable([1, 2, 3, 4, 5, 6, 7, 8])\nprint(reverse(l, 2, 4))\n","sub_path":"InterviewBit/LinkedLists/ReverseLinkListII.py","file_name":"ReverseLinkListII.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"12268823","text":"import json\n\nfrom django.contrib import messages\nfrom django.template.response import TemplateResponse\nfrom django.utils.translation import pgettext_lazy\nfrom impersonate.views import impersonate as orig_impersonate\nfrom random import randint\n\nfrom ..account.models import User\nfrom ..dashboard.views import staff_member_required\nfrom ..product.models import Category\nfrom ..product.utils import products_for_homepage\nfrom ..product.utils.availability import products_with_availability\nfrom ..seo.schema.webpage import get_webpage_schema\n\n\ndef home(request):\n    products = products_for_homepage()[:8]\n    products = list(products_with_availability(\n        products, discounts=request.discounts, taxes=request.taxes,\n        local_currency=request.currency))\n    webpage_schema = get_webpage_schema(request)\n\n    # DEMO: get Shop Now links based on current categories, instead of\n    # hardcoding them in template.\n    num = 3\n    shop_now_links = []\n    categories = list(Category.objects.all()[:num])\n    for dummy in range(num):\n        if categories:\n            category = categories.pop()\n            link = category.get_absolute_url()\n        else:\n            link = ''\n        shop_now_links.append(link)\n\n    return TemplateResponse(\n        request, 'home.html', {\n            'parent': None,\n            'products': products,\n            'shop_now_links' : shop_now_links,\n            'webpage_schema': json.dumps(webpage_schema)})\n\n\n@staff_member_required\ndef styleguide(request):\n    return TemplateResponse(request, 'styleguide.html')\n\n\ndef impersonate(request, uid):\n    response = orig_impersonate(request, uid)\n    if request.session.modified:\n        msg = pgettext_lazy(\n            'Impersonation message',\n            'You are now logged as {}'.format(User.objects.get(pk=uid)))\n        messages.success(request, msg)\n    return response\n\n\ndef handle_404(request, exception=None):\n    ctx = {'variant': randint(0, 2)}\n    return TemplateResponse(request, '404.html', ctx, status=404)\n\n\ndef manifest(request):\n    return TemplateResponse(\n        request, 'manifest.json', content_type='application/json')\n\n\ndef privacy_policy(request):\n    return TemplateResponse(request, 'privacy_policy.html')\n","sub_path":"saleor/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"566239001","text":"from __future__ import print_function\n\nimport json\nimport os\nimport re\n\nfrom uitools.qt import Q\nfrom sgfs import SGFS\n\nimport nuke\n\nfrom . import footage\nfrom . import publish\nfrom . import uiutils as ui\n\n\ndef add_shot_cache_command():\n    \n    node = ui.one_selected_node()\n    \n    meta = footage.get_metadata(node)\n    if not meta:\n        ui.warning(\"Could not find footage metadata from selection.\")\n        return\n\n    shot_name = meta['dst_name']\n\n    m = re.match(r'^([A-Z]{2})(\\d+)([a-z])?(?:_|$)', shot_name)\n    if not m:\n        ui.warning(\"Could not interpret edit shot name: {}\".format(shot_name))\n        return\n\n    seq, shot_num, shot_letter = m.groups()\n\n    type_, ok = Q.InputDialog.getText(None, 'Cache Type', 'What are you caching?', text='footage')\n    if not ok:\n        return\n    type_ = re.sub(r'\\W+', '-', type_).strip('-')\n\n    dir_ = os.path.join('/Volumes/heap/sitg/work/cache-film', seq, shot_name, 'nuke')\n\n    write = nuke.nodes.Write(\n        name='cache_{}_{}'.format(shot_name, type_),\n        channels='rgba',\n        file=os.path.join(dir_, type_, '%04d.exr'),\n        proxy=os.path.join(dir_, type_, '%04d.proxy.exr'),\n        file_type='exr',\n        create_directories=True,\n    )\n    write.setInput(0, node)\n    write['compression'].setValue('PIZ')\n\n","sub_path":"sitg/nuke/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"277587026","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pdb\nimport time\nimport cx_Oracle\nimport multiprocessing\n\nipList = (\"192.168.7.121\",\n          \"192.168.7.122\",\n          \"192.168.7.123\",\n          \"192.168.7.124\",\n          \"192.168.7.125\",\n          \"192.168.7.126\",\n          \"192.168.7.127\",\n          \"192.168.7.128\",\n          \"192.168.7.129\",\n          \"192.168.7.130\",\n          \"192.168.7.131\",\n          \"192.168.7.132\",\n          \"192.168.7.133\",\n          \"192.168.7.134\",\n          \"192.168.7.135\")\n\nsqlstr = ''\nwith open('testSql.sql', 'r') as fs:\n    sqlstr = fs.read().strip('\\n')\n\n\ndef doQuery(ip, sql):\n    result = []\n    conn = cx_Oracle.connect(\"fhnsdb/fhnsdb@%s:1521/ora11g\" % ip)\n    c = conn.cursor()\n    x = c.execute(sql)\n    result = x.fetchall()\n    c.close()\n    conn.close()\n    return result\n\n\n# cpus = multiprocessing.cpu_count()\npool = multiprocessing.Pool()\n\nresult = []\nfor ips in ipList:\n    # pdb.set_trace()\n    rtmp = pool.apply_async(doQuery, args=(ips, sqlstr))\n    result.append([ips, rtmp])\npool.close()\npool.join()\n\nwith open(\"Sqlout.log\", \"w\") as fd:\n    for i in result:\n        for j in i[1].get():\n            strresult = ''\n            # pdb.set_trace()\n            for k in j:\n                strresult += '%s,' % str(k)\n            fd.write(\"%s\\n\" % strresult.rstrip(','))\n","sub_path":"aioSqlQuery.py","file_name":"aioSqlQuery.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"436052425","text":"\"\"\"\nMy purpose in life is to update the hourly_YYYY with observed or\ncomputed hourly precipitation\n\"\"\"\nimport datetime\nimport sys\n\nimport pytz\nfrom pyiem.util import get_dbconn\n\n\ndef archive(ts):\n    \"\"\"Reprocess an older date\n\n    Currently, we only support the METAR database :(\n    \"\"\"\n    asos = get_dbconn('asos', user='nobody')\n    acursor = asos.cursor()\n    iem = get_dbconn('iem')\n    icursor = iem.cursor()\n\n    table = \"t%s\" % (ts.year,)\n    acursor.execute(\"\"\"WITH data as (\n        SELECT station, max(p01i) from \"\"\" + table + \"\"\"\n        WHERE valid > %s and valid <= %s and p01i is not null\n        GROUP by station)\n\n    SELECT station, network, max, iemid from data d JOIN stations s on\n    (d.station = s.id) WHERE (s.network ~* 'ASOS' or s.network = 'AWOS')\n    \"\"\", (ts, ts + datetime.timedelta(minutes=60)))\n\n    table = \"hourly_%s\" % (ts.year,)\n    for row in acursor:\n        icursor.execute(\"\"\"INSERT into \"\"\" + table + \"\"\"\n        (station, network, valid, phour, iemid)\n        VALUES (%s, %s, %s, %s, %s)\n        \"\"\", (row[0], row[1], ts, row[2], row[3]))\n\n    icursor.close()\n    iem.commit()\n\n\ndef realtime(ts):\n    \"\"\"realtime\"\"\"\n    pgconn = get_dbconn('iem')\n    icursor = pgconn.cursor()\n    table = \"hourly_%s\" % (ts.year,)\n    icursor.execute(\"\"\"\n    INSERT into \"\"\" + table + \"\"\"\n        (SELECT t.id, t.network, %s as v, max(phour) as p, t.iemid\n        from current_log c, stations t WHERE\n            (valid - '1 minute'::interval) >= %s\n            and (valid - '1 minute'::interval) < %s\n            and phour >= 0 and\n            t.network NOT IN ('KCCI','KELO','KIMT')\n            and c.iemid = t.iemid\n            and t.network !~* 'DCP'\n            GROUP by t,id, t.network, v, t.iemid)\n            \"\"\", (ts, ts, ts + datetime.timedelta(minutes=60)))\n    pgconn.commit()\n    pgconn.close()\n\n\ndef main(argv):\n    \"\"\"Do things\"\"\"\n    if len(argv) == 5:\n        # Run for a custom hour\n        ts = datetime.datetime(int(argv[1]), int(argv[2]), int(argv[3]),\n                               int(argv[4]))\n        ts = ts.replace(tzinfo=pytz.utc)\n        archive(ts)\n    else:\n        # We run for the last hour\n        ts = datetime.datetime.utcnow() - datetime.timedelta(hours=1)\n        ts = ts.replace(minute=0, second=0, microsecond=0,\n                        tzinfo=pytz.utc)\n        realtime(ts)\n\n\nif __name__ == '__main__':\n    main(sys.argv)\n","sub_path":"scripts/summary/hourly_precip.py","file_name":"hourly_precip.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"337583111","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_digits\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import to_categorical\nfrom keras import metrics, optimizers\nfrom keras.utils import plot_model\nfrom keras.callbacks import TensorBoard\n\n# set seed for random number\nnp.random.seed(123456)\n\n# load iris data from sklearn\ndata, labels = load_digits(return_X_y=True)\nsample_num, sample_dim = data.shape\nlabels = to_categorical(labels)\nclass_num = labels.shape[1]\n\ntrain_percent = 0.8\ntrain_num = int(sample_num * train_percent)\ntest_num = sample_num - train_num\ntrain_data, test_data = np.split(data, [train_num])\ntrain_labels, test_labels = np.split(labels, [train_num])\n\n# build a model\nmodel = Sequential()\nmodel.add(Dense(units=50, activation='relu', input_dim=sample_dim))\n# model.add(Dense(units=50, activation='relu', input_dim=sample_dim))\nmodel.add(Dense(units=class_num, activation='softmax', input_dim=sample_dim))\n\n# plot the model\nplot_model(model, to_file='model.jpg', show_shapes=True, show_layer_names=True)\n\n# compile the model\noptimizer = optimizers.SGD(lr=0.5, momentum=0.5, decay=0)\nmodel.compile(loss='mse', optimizer=optimizer, metrics=[metrics.categorical_accuracy])\n\n# train the model\nhistory = model.fit(train_data, train_labels, batch_size=train_num // 10, epochs=50, verbose=2)\n\n# test the model\ntest_loss, test_accuracy = model.evaluate(test_data, test_labels, batch_size=test_num)\nprint('\\n--------------------------------------------\\n')\ntitle = 'Accuracy: {}'.format(test_accuracy)\nprint(title)\n\n# plot the accuracy history\nplt.figure()\nplt.suptitle('Accuracy: {}'.format(test_accuracy))\n# plt.tight_layout()\n# plt.subplots_adjust(top=0.88)\n\nplt.subplot('211')\n# plt.title(title)\naccuracy_history = history.history['categorical_accuracy']\nplt.plot(accuracy_history)\n\nplt.subplot('212')\n# plt.title(title)\nloss_history = history.history['loss']\nplt.plot(loss_history)\n\nplt.show()\n","sub_path":"KerasTest.py","file_name":"KerasTest.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"195668560","text":"#!/usr/bin/env python\n\"\"\"This script allows to create and run the regression test.\"\"\"\nfrom blackbox.tests.test_blackbox import *\n\nfor i in range(1000):\n\n    print(' ... iteration ', str(i), '\\n\\n')\n\n    test_1()\n\n    test_3()\n\n    test_4()\n\n    test_6()\n\n    test_7()\n","sub_path":"development/testing/property/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"422868871","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import (\n    render_to_response,\n    redirect,\n)\nfrom django.template import RequestContext\n\nfrom core.models import EmailNotification, PhoneNotification\nfrom core.forms import EmailForm, PhoneForm\n\n\ndef home(request):\n    if request.user.is_authenticated():\n        return redirect('dashboard')\n    else:\n        data = {}\n        return render_to_response(\n            'core/home.html',\n            data,\n            RequestContext(request),\n        )\n\n\n@login_required\ndef notifications(request):\n    user = request.user\n    emails = EmailNotification.objects.filter(user=user)\n    numbers = PhoneNotification.objects.filter(user=user)\n\n    phone_form = PhoneForm()\n    email_form = EmailForm()\n\n    if request.method == 'POST':\n        if 'add-phone' in request.POST:\n            phone_form = PhoneForm(request.POST)\n            if phone_form.is_valid():\n                form = phone_form.save(commit=False)\n                form.user_id = user.id\n                form.save()\n                phone_form = PhoneForm()                \n                \n        if 'add-email' in request.POST:\n            email_form = EmailForm(request.POST)\n            if email_form.is_valid():\n                form = email_form.save(commit=False)\n                form.user_id = user.id\n                form.save()\n                email_form = EmailForm()                \n\n    data = {\n        'emails': emails,\n        'numbers': numbers,\n        'email_form': email_form,\n        'phone_form': phone_form,\n    }\n            \n    return render_to_response(\n        'core/notification.html',\n        data,\n        RequestContext(request),\n    )\n\n\n@login_required\ndef remove_notifications(request):\n    user = request.user\n\n    notify_type = {\n        'email': EmailNotification,\n        'number': PhoneNotification,\n    }\n\n    if request.method == 'POST':\n        notify_id = request.POST.get(\"notification_id\")\n        notify_key = request.POST.get(\"notification_type\")\n\n        notification = notify_type[notify_key].objects.get(id=notify_id)\n        notification.delete()\n        return HttpResponse(\"Deleted\")\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"417265481","text":"import torch\nimport torch.nn as nn\nimport hyperparams as hyp\nimport numpy as np\n# import imageio,scipy\n\nfrom model_base import Model\nfrom nets.feat3dnet import Feat3dNet\nfrom nets.matchnet import MatchNet\n# from nets.entitynet import EntityNet\n\nimport torch.nn.functional as F\n\nimport utils.vox\nimport utils.samp\nimport utils.geom\nimport utils.improc\nimport utils.basic\nimport utils.eval\nimport utils.misc\nimport utils.track\n\nnp.set_printoptions(precision=2)\nnp.random.seed(0)\n\nclass KITTI_ENTITY(Model):\n    def initialize_model(self):\n        print('------ INITIALIZING MODEL OBJECTS ------')\n        self.model = KittiEntityModel()\n        if hyp.do_freeze_feat3d:\n            self.model.feat3dnet.eval()\n            self.set_requires_grad(self.model.feat3dnet, False)\n        # if hyp.do_freeze_entity:\n        #     self.model.entitynet.eval()\n        #     self.set_requires_grad(self.model.entitynet, False)\n            \nclass KittiEntityModel(nn.Module):\n    def __init__(self):\n        super(KittiEntityModel, self).__init__()\n        \n        if hyp.do_feat3d:\n            self.feat3dnet = Feat3dNet(in_dim=4)\n        if hyp.do_match:\n            # self.deglist = [-4, -2, -1, 0, 1, 2, 4]\n            self.deglist = [-4, -2, 0, 2, 4]\n            # self.deglist = [-6, -3, 0, 3, 6]\n            # self.deglist = [-6, 0, 6]\n            # self.deglist = [0]\n            self.radlist = [utils.geom.deg2rad(deg) for deg in self.deglist]\n            self.trim = 5\n            self.matchnet = MatchNet(self.radlist)\n        # if hyp.do_entity:\n        #     self.entitynet = EntityNet(\n        #         num_scales=hyp.entity_num_scales,\n        #         num_rots=hyp.entity_num_rots,\n        #         max_deg=hyp.entity_max_deg,\n        #         max_disp_z=hyp.entity_max_disp_z,\n        #         max_disp_y=hyp.entity_max_disp_y,\n        #         max_disp_x=hyp.entity_max_disp_x)\n\n    def place_scene_at_dr(self, rgb_mem, xyz_cam, dr, Z, Y, X, vox_util):\n        # this function voxelizes the scene with some rotation delta\n\n        # dr is B x 3, containing drx, dry, drz (the rotation delta)\n        # Z, Y, X are the resolution of the zoom\n        # sz, sy, sx are the metric size of the zoom\n        B, N, D = list(xyz_cam.shape)\n        assert(D==3)\n\n        # to help us create some mats:\n        rot0 = utils.geom.eye_3x3(B)\n        t0 = torch.zeros(B, 3).float().cuda()\n\n        camr_T_cam = utils.geom.merge_rt(utils.geom.eul2rotm(dr[:,0], dr[:,1], dr[:,2]), t0)\n\n        xyz_camr = utils.geom.apply_4x4(camr_T_cam, xyz_cam)\n        occ_memr = vox_util.voxelize_xyz(xyz_camr, Z, Y, X)\n        rgb_memr = vox_util.apply_4x4_to_vox(camr_T_cam, rgb_mem)\n        return occ_memr, rgb_memr\n            \n    def prepare_common_tensors(self, feed):\n        results = dict()\n        \n        self.summ_writer = utils.improc.Summ_writer(\n            writer=feed['writer'],\n            global_step=feed['global_step'],\n            log_freq=feed['set_log_freq'],\n            fps=16,\n            just_gif=True)\n        self.global_step = feed['global_step']\n\n        self.B = feed['set_batch_size']\n        self.S = feed['set_seqlen']\n        self.set_name = feed['set_name']\n        self.filename = feed['filename']\n        self.data_ind = feed['data_ind']\n        print('filename', self.filename)\n        print('data_ind', self.data_ind)\n        \n        __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n        __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n\n        self.H, self.W, self.V, self.N = hyp.H, hyp.W, hyp.V, hyp.N\n        self.PH, self.PW = hyp.PH, hyp.PW\n\n        if self.set_name=='test':\n            self.Z, self.Y, self.X = hyp.Z_test, hyp.Y_test, hyp.X_test\n        elif self.set_name=='val':\n            self.Z, self.Y, self.X = hyp.Z_val, hyp.Y_val, hyp.X_val\n        else:\n            self.Z, self.Y, self.X = hyp.Z, hyp.Y, hyp.X\n        self.Z2, self.Y2, self.X2 = int(self.Z/2), int(self.Y/2), int(self.X/2)\n        self.Z4, self.Y4, self.X4 = int(self.Z/4), int(self.Y/4), int(self.X/4)\n\n        self.ZZ, self.ZY, self.ZX = hyp.ZZ, hyp.ZY, hyp.ZX\n        self.pix_T_cams = feed['pix_T_cams']\n\n        # in this mode, we never use R coords, so we can drop the R/X notation\n        self.origin_T_cams = feed['origin_T_camXs']\n        self.xyz_velos = feed['xyz_veloXs']\n        self.cams_T_velos = feed[\"cams_T_velos\"]\n        self.xyz_cams = __u(utils.geom.apply_4x4(__p(self.cams_T_velos), __p(self.xyz_velos)))\n\n        scene_centroid_x = 0.0\n        # scene_centroid_y = 1.0\n        # scene_centroid_z = 18.0\n        scene_centroid_y = 0.0\n        scene_centroid_z = 0.0\n        scene_centroid = np.array([scene_centroid_x,\n                                   scene_centroid_y,\n                                   scene_centroid_z]).reshape([1, 3])\n        self.scene_centroid = torch.from_numpy(scene_centroid).float().cuda()\n        self.vox_util = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=self.scene_centroid, assert_cube=True)\n        \n        self.vox_size_X = self.vox_util.default_vox_size_X\n        self.vox_size_Y = self.vox_util.default_vox_size_Y\n        self.vox_size_Z = self.vox_util.default_vox_size_Z\n        \n        self.rgb_cams = feed['rgb_camXs']\n        self.summ_writer.summ_rgbs('inputs/rgbs', self.rgb_cams.unbind(1))\n\n        return True # OK\n\n    def run_train(self, feed):\n        total_loss = torch.tensor(0.0).cuda()\n        __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n        __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n        results = dict()\n\n        assert(self.S==2)\n\n        origin_T_cam0 = self.origin_T_cams[:, 0]\n        origin_T_cam1 = self.origin_T_cams[:, 1]\n        cam0_T_cam1 = utils.basic.matmul2(utils.geom.safe_inverse(origin_T_cam0), origin_T_cam1)\n\n        # let's immediately discard the true motion and make some fake motion\n\n        xyz0_cam0 = self.xyz_cams[:,0]\n        xyz1_cam0 = utils.geom.apply_4x4(cam0_T_cam1, self.xyz_cams[:,1])\n\n        # camX_T_cam0 = utils.geom.get_random_rt(\n        xyz_cam_g, rx, ry, rz = utils.geom.get_random_rt(\n            self.B,\n            r_amount=4.0,\n            t_amount=2.0,\n            sometimes_zero=False,\n            return_pieces=True)\n        rot = utils.geom.eul2rotm(rx*0.1, ry, rz*0.1)\n        camX_T_cam0 = utils.geom.merge_rt(rot, xyz_cam_g)\n        \n        cam0_T_camX = utils.geom.safe_inverse(camX_T_cam0)\n        xyz1_camX = utils.geom.apply_4x4(camX_T_cam0, xyz1_cam0)\n\n        occ0_mem0 = self.vox_util.voxelize_xyz(xyz0_cam0, self.Z, self.Y, self.X)\n        occ1_memX = self.vox_util.voxelize_xyz(xyz1_camX, self.Z, self.Y, self.X)\n\n        rgb0_mem0 = self.vox_util.unproject_rgb_to_mem(\n            self.rgb_cams[:,0], self.Z, self.Y, self.X, self.pix_T_cams[:,0])\n        rgb1_mem1 = self.vox_util.unproject_rgb_to_mem(\n            self.rgb_cams[:,1], self.Z, self.Y, self.X, self.pix_T_cams[:,1])\n        \n        rgb1_memX = self.vox_util.apply_4x4_to_vox(\n            utils.basic.matmul2(camX_T_cam0, cam0_T_cam1), rgb1_mem1)\n        \n        self.summ_writer.summ_occs('inputs/occ_mems', [occ0_mem0, occ1_memX])\n        self.summ_writer.summ_unps('inputs/rgb_mems', [rgb0_mem0, rgb1_memX], [occ0_mem0, occ1_memX])\n\n        if hyp.do_feat3d:\n            feat_mem0_input = torch.cat([occ0_mem0, occ0_mem0*rgb0_mem0], dim=1)\n            feat_memX_input = torch.cat([occ1_memX, occ1_memX*rgb1_memX], dim=1)\n            feat_loss0, feat_halfmem0 = self.feat3dnet(feat_mem0_input, self.summ_writer)\n            feat_loss1, feat_halfmemX = self.feat3dnet(feat_memX_input, self.summ_writer)\n            total_loss += feat_loss0 + feat_loss1\n\n        # if hyp.do_entity:\n        #     assert(hyp.do_feat3d)\n        #     entity_loss, cam0_T_cam1_e, _ = self.entitynet(\n        #         feat_halfmem0,\n        #         feat_halfmemX,\n        #         cam0_T_camX,\n        #         self.vox_util,\n        #         self.summ_writer)\n        #     total_loss += entity_loss\n\n        if hyp.do_match:\n            assert(hyp.do_feat3d)\n\n            occ_rs = []\n            rgb_rs = []\n            feat_rs = []\n            feat_rs_trimmed = []\n            for ind, rad in enumerate(self.radlist):\n                rad_ = torch.from_numpy(np.array([0, rad, 0])).float().cuda().reshape(1, 3)\n                occ_r, rgb_r = self.place_scene_at_dr(\n                    rgb0_mem0, self.xyz_cams[:,0], rad_,\n                    self.Z, self.Y, self.X, self.vox_util)\n                occ_rs.append(occ_r)\n                rgb_rs.append(rgb_r)\n\n                inp_r = torch.cat([occ_r, occ_r*rgb_r], dim=1)\n                _, feat_r = self.feat3dnet(inp_r)\n                feat_rs.append(feat_r)\n                feat_r_trimmed = feat_r[:,:,self.trim:-self.trim:,self.trim:-self.trim:,self.trim:-self.trim:]\n                # print('feat_r_trimmed', feat_r_trimmed.shape)\n                feat_rs_trimmed.append(feat_r_trimmed)\n                \n            self.summ_writer.summ_occs('entity/occ_rs', occ_rs)\n            self.summ_writer.summ_unps('entity/rgb_rs', rgb_rs, occ_rs)\n            self.summ_writer.summ_feats('entity/feat_rs', feat_rs, pca=True)\n            self.summ_writer.summ_feats('entity/feat_rs_trimmed', feat_rs_trimmed, pca=True)\n\n            match_loss, camX_T_cam0_e, cam0_T_camX_e = self.matchnet(\n                torch.stack(feat_rs_trimmed, dim=1), # templates\n                feat_halfmemX, # search region\n                self.vox_util,\n                xyz_cam_g=xyz_cam_g,\n                rad_g=ry,\n                summ_writer=self.summ_writer)\n            total_loss += match_loss\n\n            occ1_mem0_e = self.vox_util.apply_4x4_to_vox(cam0_T_camX_e, occ1_memX)\n            occ1_mem0_g = self.vox_util.apply_4x4_to_vox(cam0_T_camX, occ1_memX)\n\n            self.summ_writer.summ_occs('entity/occ_mems_0', [occ0_mem0, occ1_memX])\n            self.summ_writer.summ_occs('entity/occ_mems_e', [occ0_mem0, occ1_mem0_e.round()])\n            self.summ_writer.summ_occs('entity/occ_mems_g', [occ0_mem0, occ1_mem0_g.round()])\n            \n        self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n        return total_loss, results, False\n\n    def run_sfm(self, feed):\n        total_loss = torch.tensor(0.0).cuda()\n        __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n        __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n        results = dict()\n\n        occ_vis = []\n        feat_vis = []\n        feat_all = []\n        stab_vis_e = []\n        stab_vis_g = []\n        diff_vis = []\n\n\n        cam0s_T_camIs_e = utils.geom.eye_4x4(self.B*self.S).reshape(self.B, self.S, 4, 4)\n        cam0s_T_camIs_g = utils.geom.eye_4x4(self.B*self.S).reshape(self.B, self.S, 4, 4)\n\n        # xyz_e_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        # xyz_g_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        # xyz_e = utils.geom.apply_4x4(__p(cam0s_T_camIs_e), xyz_e_).reshape(self.B, self.S, 3)\n        # xyz_g = utils.geom.apply_4x4(__p(cam0s_T_camIs_g), xyz_g_).reshape(self.B, self.S, 3)\n        \n        xyz_e = torch.zeros((self.B, self.S, 3), dtype=torch.float32, device=torch.device('cuda'))\n        xyz_g = torch.zeros((self.B, self.S, 3), dtype=torch.float32, device=torch.device('cuda'))\n\n        for s in list(range(self.S-1)):\n            origin_T_cam0 = self.origin_T_cams[:, s]\n            origin_T_cam1 = self.origin_T_cams[:, s+1]\n            cam0_T_origin = utils.geom.safe_inverse(origin_T_cam0)\n            cam0_T_cam1_g = utils.basic.matmul2(cam0_T_origin, origin_T_cam1)\n            cam0s_T_camIs_g[:,s+1] = utils.basic.matmul2(cam0s_T_camIs_g[:,s], cam0_T_cam1_g)\n        xyz_g_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        cam0s_T_camIs_g_ = __p(cam0s_T_camIs_g)\n        xyz_g_ = utils.geom.apply_4x4(cam0s_T_camIs_g_, xyz_g_)\n        xyz_g = xyz_g_.reshape(self.B, self.S, 3)\n\n        assert(self.B==1)\n        if '09_0000' in self.filename[0]:\n            gt_fn = '/home/aharley/SfMLearner/kitti_eval/pose_data/ground_truth/09_full.txt'\n            orb_fn = '/home/aharley/SfMLearner/kitti_eval/pose_data/orb_full_results/09_full.txt'\n            # orb_fn = '/home/aharley/SfMLearner/kitti_eval/pose_data/orb_short_results/09_full.txt'\n        elif '10_0000' in self.filename[0]:\n            gt_fn = '/home/aharley/SfMLearner/kitti_eval/pose_data/ground_truth/10_full.txt'\n            orb_fn = '/home/aharley/SfMLearner/kitti_eval/pose_data/orb_full_results/10_full.txt'\n            # orb_fn = '/home/aharley/SfMLearner/kitti_eval/pose_data/orb_short_results/10_full.txt'\n        else:\n            print('weird filename:', self.filename)\n            assert(False)\n            \n        # # with open(orb_fn) as f:\n        # #     content = f.readlines()\n        # # poses = [line.strip() for line in content]\n        # # # xyz = np.array([[float(value) for value in gtruth_list[a][0:3]] for a,b in matches])\n\n        def read_file_list(filename):\n            \"\"\"\n            Reads a trajectory from a text file. \n\n            File format:\n            The file format is \"stamp d1 d2 d3 ...\", where stamp denotes the time stamp (to be matched)\n            and \"d1 d2 d3..\" is arbitary data (e.g., a 3D position and 3D orientation) associated to this timestamp. \n\n            Input:\n            filename -- File name\n\n            Output:\n            dict -- dictionary of (stamp,data) tuples\n\n            \"\"\"\n            file = open(filename)\n            data = file.read()\n            lines = data.replace(\",\",\" \").replace(\"\\t\",\" \").split(\"\\n\") \n            list = [[v.strip() for v in line.split(\" \") if v.strip()!=\"\"] for line in lines if len(line)>0 and line[0]!=\"#\"]\n            list = [(float(l[0]),l[1:]) for l in list if len(l)>1]\n            return dict(list)\n\n        def associate(first_list, second_list,offset,max_difference):\n            \"\"\"\n            Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim \n            to find the closest match for every input tuple.\n\n            Input:\n            first_list -- first dictionary of (stamp,data) tuples\n            second_list -- second dictionary of (stamp,data) tuples\n            offset -- time offset between both dictionaries (e.g., to model the delay between the sensors)\n            max_difference -- search radius for candidate generation\n\n            Output:\n            matches -- list of matched tuples ((stamp1,data1),(stamp2,data2))\n\n            \"\"\"\n            first_keys = list(first_list.keys())\n            second_keys = list(second_list.keys())\n            potential_matches = [(abs(a - (b + offset)), a, b) \n                                 for a in first_keys \n                                 for b in second_keys \n                                 if abs(a - (b + offset)) < max_difference]\n            potential_matches.sort()\n            matches = []\n            for diff, a, b in potential_matches:\n                if a in first_keys and b in second_keys:\n                    first_keys.remove(a)\n                    second_keys.remove(b)\n                    matches.append((a, b))\n\n            matches.sort()\n            return matches\n\n        gtruth_list = read_file_list(gt_fn)\n        pred_list = read_file_list(orb_fn)\n        matches = associate(gtruth_list, pred_list, 0, 0.01)\n        \n        gtruth_xyz = np.array([[float(value) for value in gtruth_list[a][0:3]] for a,b in matches])\n        pred_xyz = np.array([[float(value) for value in pred_list[b][0:3]] for a,b in matches])\n\n        offset = gtruth_xyz[0] - pred_xyz[0]\n        pred_xyz += offset[None,:]\n\n        # Optimize the scaling factor\n        scale = np.sum(gtruth_xyz * pred_xyz)/np.sum(pred_xyz ** 2)\n        alignment_error = pred_xyz * scale - gtruth_xyz\n        pred_xyz = pred_xyz * scale\n        \n        gtruth_xyz = gtruth_xyz[:100]\n        pred_xyz = pred_xyz[:100]\n\n        print('gtruth_xyz', gtruth_xyz.shape)\n        print('pred_xyz', pred_xyz.shape)\n        \n        xyz_g = torch.from_numpy(gtruth_xyz.astype(np.float32)).float().cuda().reshape(1, 100, 3)\n        xyz_e = torch.from_numpy(pred_xyz.astype(np.float32)).float().cuda().reshape(1, 100, 3)\n        \n        # i just want EPE\n\n        # rmse = rmse/100\n\n        # print('rmse', rmse)\n\n        # for s in list(range(self.S)):\n        #     xyz_e_ = np.array(poses[s].split(' '))[1:4]\n        #     xyz_e_ = xyz_e_.astype(np.float32)\n        #     xyz_e_ = torch.from_numpy(xyz_e_).float().cuda().reshape(1, 1, 3)\n        #     # xyz_e_ = utils.geom.apply_4x4(self.cams_T_velos[:,s], xyz_e_)\n        #     xyz_e[:,s] = xyz_e_.reshape(1, 1, 3)\n            \n        #     print('xyz_e', xyz_e[:,s])\n        #     print('xyz_g', xyz_g[:,s])\n        #     input()\n\n        # mean_epe = torch.mean(torch.norm(xyz_e[:,-1] - xyz_g[:,-1], dim=1))\n        # self.summ_writer.summ_scalar('unscaled_entity/mean_epe', mean_epe)\n\n        # xz_e = torch.stack([xyz_e[:,-1,0], xyz_e[:,-1,2]], dim=1)\n        # xz_g = torch.stack([xyz_g[:,-1,0], xyz_g[:,-1,2]], dim=1)\n        # mean_epe_bev = torch.mean(torch.norm(xz_e - xz_g, dim=1))\n        # self.summ_writer.summ_scalar('unscaled_entity/mean_epe_bev', mean_epe_bev)\n\n        self.vox_util_wide = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=torch.mean(xyz_g[:,:s+1], dim=1), assert_cube=False)\n        wider = 8\n        self.vox_util_wide.XMIN = self.vox_util_wide.XMIN - wider*8\n        self.vox_util_wide.YMIN = self.vox_util_wide.YMIN #- wider*1\n        self.vox_util_wide.ZMIN = self.vox_util_wide.ZMIN - wider*8\n        self.vox_util_wide.XMAX = self.vox_util_wide.XMAX + wider*8\n        self.vox_util_wide.YMAX = self.vox_util_wide.YMAX #+ wider*1\n        self.vox_util_wide.ZMAX = self.vox_util_wide.ZMAX + wider*8\n        occ_mem0 = self.vox_util_wide.voxelize_xyz(self.xyz_cams[:,0], self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n        self.summ_writer.summ_traj_on_occ(\n            'entity/traj',\n            xyz_e,\n            occ_mem0,\n            self.vox_util_wide,\n            traj_g=xyz_g,\n            already_mem=False,\n            sigma=1)\n        # total_loss += mean_epe\n        self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n        return total_loss, results, False\n\n    \n    def run_orb(self, feed):\n        total_loss = torch.tensor(0.0).cuda()\n        __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n        __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n        results = dict()\n\n        # cam0_T_cam1_list_e = []\n        # cam0_T_cam1_list_g = []\n\n        occ_vis = []\n        feat_vis = []\n        feat_all = []\n        stab_vis_e = []\n        stab_vis_g = []\n        diff_vis = []\n\n\n        cam0s_T_camIs_e = utils.geom.eye_4x4(self.B*self.S).reshape(self.B, self.S, 4, 4)\n        cam0s_T_camIs_g = utils.geom.eye_4x4(self.B*self.S).reshape(self.B, self.S, 4, 4)\n\n\n        assert(self.B==1)\n        if '09_0000' in self.filename[0]:\n            # orb_fn = '/projects/katefgroup/slam/ORB_KITTI_STEREO_100/09.txt'\n            orb_fn = '/home/aharley/kitti_data/09_rt_e.txt'\n        elif '10_0000' in self.filename[0]:\n            # orb_fn = '/projects/katefgroup/slam/ORB_KITTI_STEREO_100/10.txt'\n            orb_fn = '/home/aharley/kitti_data/10_rt_e.txt'\n        else:\n            print('weird filename:', self.filename)\n            assert(False)\n        with open(orb_fn) as f:\n            content = f.readlines()\n        content = content[1:]\n        poses = [line.strip() for line in content]\n\n        for s in list(range(self.S-1)):\n\n            xyz_cams = self.xyz_cams[:,:s+1]\n            cam0_T_cams_e = cam0s_T_camIs_e[:,:s+1]\n            cam0_T_cams_g = cam0s_T_camIs_g[:,:s+1]\n            xyz_cam0s_e = __u(utils.geom.apply_4x4(__p(cam0_T_cams_e), __p(xyz_cams)))\n            xyz_cam0s_g = __u(utils.geom.apply_4x4(__p(cam0_T_cams_g), __p(xyz_cams)))\n            xyz_cam0_e = xyz_cam0s_e.reshape(self.B, -1, 3)\n            xyz_cam0_g = xyz_cam0s_g.reshape(self.B, -1, 3)\n            xyz_camI_e = utils.geom.apply_4x4(utils.geom.safe_inverse(cam0_T_cams_e[:,s]), xyz_cam0_e)\n            xyz_camI_g = utils.geom.apply_4x4(utils.geom.safe_inverse(cam0_T_cams_g[:,s]), xyz_cam0_g)\n\n            xyz_e_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n            xyz_g_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n            xyz_e = utils.geom.apply_4x4(__p(cam0s_T_camIs_e), xyz_e_).reshape(self.B, self.S, 3)\n            xyz_g = utils.geom.apply_4x4(__p(cam0s_T_camIs_g), xyz_g_).reshape(self.B, self.S, 3)\n\n            self.vox_util_wide = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=torch.mean(xyz_g[:,:s+1], dim=1), assert_cube=False)\n            wider = 8\n            self.vox_util_wide.XMIN = self.vox_util_wide.XMIN - wider*8\n            self.vox_util_wide.YMIN = self.vox_util_wide.YMIN #- wider*1\n            self.vox_util_wide.ZMIN = self.vox_util_wide.ZMIN - wider*8\n            self.vox_util_wide.XMAX = self.vox_util_wide.XMAX + wider*8\n            self.vox_util_wide.YMAX = self.vox_util_wide.YMAX #+ wider*1\n            self.vox_util_wide.ZMAX = self.vox_util_wide.ZMAX + wider*8\n\n            occ_mem0_e = self.vox_util_wide.voxelize_xyz(xyz_cam0_e, self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n            occ_mem0_g = self.vox_util_wide.voxelize_xyz(xyz_cam0_g, self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n            stab_vis_e.append(self.summ_writer.summ_traj_on_occ(\n                '',\n                xyz_e[:,:s+1],\n                occ_mem0_e,\n                self.vox_util_wide,\n                traj_g=xyz_g[:,:s+1],\n                already_mem=False,\n                sigma=1,\n                only_return=True))\n            stab_vis_g.append(self.summ_writer.summ_traj_on_occ(\n                '',\n                xyz_e[:,:s+1],\n                occ_mem0_g,\n                self.vox_util_wide,\n                traj_g=xyz_g[:,:s+1],\n                already_mem=False,\n                sigma=1,\n                only_return=True))\n            diff_vis.append(self.summ_writer.summ_oned('', torch.abs(occ_mem0_e - occ_mem0_g), bev=True, only_return=True, norm=True))\n\n            if s==0:\n                orb_curr_pose = np.eye(4)\n                orb_next_pose = poses[s]\n                orb_next_pose = np.array(orb_next_pose.split(' '))[1:]\n            else:\n                orb_curr_pose = poses[s-1]\n                orb_next_pose = poses[s]\n                orb_curr_pose = np.array(orb_curr_pose.split(' '))[1:]\n                orb_next_pose = np.array(orb_next_pose.split(' '))[1:]\n                \n            # orb_curr_pose = poses[s]\n            # orb_next_pose = poses[s+1]\n            # print('orb_curr_pose', orb_curr_pose)\n            # orb_curr_pose = np.array(orb_curr_pose.split(' '))\n            # orb_next_pose = np.array(orb_next_pose.split(' '))\n            \n            print('orb_curr_pose', orb_curr_pose, orb_curr_pose.shape)\n            \n            # orb_curr_pose = np.reshape(orb_curr_pose, (1, 3, 4)).astype(np.float32)\n            # orb_next_pose = np.reshape(orb_next_pose, (1, 3, 4)).astype(np.float32)\n            orb_curr_pose = np.reshape(orb_curr_pose, (1, 4, 4)).astype(np.float32)\n            orb_next_pose = np.reshape(orb_next_pose, (1, 4, 4)).astype(np.float32)\n            print('orb_curr_pose', orb_curr_pose)\n            orb_curr_pose = torch.from_numpy(orb_curr_pose).float().cuda()\n            orb_next_pose = torch.from_numpy(orb_next_pose).float().cuda()\n\n            # make these 4x4, by re-packing\n            # orb_curr_pose = utils.geom.merge_rt(utils.geom.split_rt(orb_curr_pose))\n            # orb_next_pose = utils.geom.merge_rt(utils.geom.split_rt(orb_next_pose))\n\n            # make these 4x4, by re-packing\n            \n            # r, t = utils.geom.split_rt(orb_curr_pose)\n            # origin_T_orb0 = utils.geom.merge_rt(r, t)\n            # r, t = utils.geom.split_rt(orb_next_pose)\n            # origin_T_orb1 = utils.geom.merge_rt(r, t)\n            \n            origin_T_orb0 = utils.geom.merge_rt(*utils.geom.split_rt(orb_curr_pose))\n            origin_T_orb1 = utils.geom.merge_rt(*utils.geom.split_rt(orb_next_pose))\n            orb0_T_origin = utils.geom.safe_inverse(origin_T_orb0)\n            orb0_T_orb1 = utils.basic.matmul2(orb0_T_origin, origin_T_orb1)\n\n            cam0_T_cam1_e = orb0_T_orb1.clone()\n            \n            \n            print('seq step %d' % s)\n            \n            origin_T_cam0 = self.origin_T_cams[:, s]\n            origin_T_cam1 = self.origin_T_cams[:, s+1]\n            cam0_T_origin = utils.geom.safe_inverse(origin_T_cam0)\n            cam0_T_cam1_g = utils.basic.matmul2(cam0_T_origin, origin_T_cam1)\n\n\n            # cam0_T_cam1_list_e.append(cam0_T_cam1_e)\n            # cam0_T_cam1_list_g.append(cam0_T_cam1_g)\n\n            cam0s_T_camIs_e[:,s+1] = utils.basic.matmul2(cam0s_T_camIs_e[:,s], cam0_T_cam1_e)\n            cam0s_T_camIs_g[:,s+1] = utils.basic.matmul2(cam0s_T_camIs_g[:,s], cam0_T_cam1_g)\n\n        self.summ_writer.summ_rgbs('inputs/stab_vis_e', stab_vis_e)\n        self.summ_writer.summ_rgbs('inputs/stab_vis_g', stab_vis_g)\n        self.summ_writer.summ_rgbs('inputs/diff_vis', diff_vis)\n\n        xyz_e_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        xyz_g_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        cam0s_T_camIs_e_ = __p(cam0s_T_camIs_e)\n        cam0s_T_camIs_g_ = __p(cam0s_T_camIs_g)\n        xyz_e_ = utils.geom.apply_4x4(cam0s_T_camIs_e_, xyz_e_)\n        xyz_g_ = utils.geom.apply_4x4(cam0s_T_camIs_g_, xyz_g_)\n        xyz_e = xyz_e_.reshape(self.B, self.S, 3)\n        xyz_g = xyz_g_.reshape(self.B, self.S, 3)\n\n        mean_epe = torch.mean(torch.norm(xyz_e[:,-1] - xyz_g[:,-1], dim=1))\n        self.summ_writer.summ_scalar('unscaled_entity/mean_epe', mean_epe)\n\n        xz_e = torch.stack([xyz_e[:,-1,0], xyz_e[:,-1,2]], dim=1)\n        xz_g = torch.stack([xyz_g[:,-1,0], xyz_g[:,-1,2]], dim=1)\n        mean_epe_bev = torch.mean(torch.norm(xz_e - xz_g, dim=1))\n        self.summ_writer.summ_scalar('unscaled_entity/mean_epe_bev', mean_epe_bev)\n\n        occ_mem0 = self.vox_util_wide.voxelize_xyz(self.xyz_cams[:,0], self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n        self.summ_writer.summ_traj_on_occ(\n            'entity/traj',\n            xyz_e,\n            occ_mem0,\n            self.vox_util_wide,\n            traj_g=xyz_g,\n            already_mem=False,\n            sigma=1)\n\n        total_loss += mean_epe\n        self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n        return total_loss, results, False\n    \n            \n        \n        \n    def run_test(self, feed):\n        total_loss = torch.tensor(0.0).cuda()\n        __p = lambda x: utils.basic.pack_seqdim(x, self.B)\n        __u = lambda x: utils.basic.unpack_seqdim(x, self.B)\n        results = dict()\n\n        occ_vis = []\n        feat_vis = []\n        feat_all = []\n        stab_vis_e = []\n        stab_vis_g = []\n        diff_vis = []\n\n        cam0s_T_camIs_e = utils.geom.eye_4x4(self.B*self.S).reshape(self.B, self.S, 4, 4)\n        cam0s_T_camIs_g = utils.geom.eye_4x4(self.B*self.S).reshape(self.B, self.S, 4, 4)\n\n        for s in list(range(self.S-1)):\n            \n            print('seq step %d' % s)\n            \n            origin_T_cam0 = self.origin_T_cams[:, s]\n            origin_T_cam1 = self.origin_T_cams[:, s+1]\n            cam0_T_origin = utils.geom.safe_inverse(origin_T_cam0)\n            cam0_T_cam1_g = utils.basic.matmul2(cam0_T_origin, origin_T_cam1)\n\n            if hyp.do_entity:\n                # get 3d voxelized inputs\n                occ_mem0 = self.vox_util.voxelize_xyz(self.xyz_cams[:,s], self.Z, self.Y, self.X)\n                occ_mem1 = self.vox_util.voxelize_xyz(self.xyz_cams[:,s+1], self.Z, self.Y, self.X)\n                unp_mem0 = self.vox_util.unproject_rgb_to_mem(self.rgb_cams[:,s], self.Z, self.Y, self.X, self.pix_T_cams[:,s])\n                unp_mem1 = self.vox_util.unproject_rgb_to_mem(self.rgb_cams[:,s+1], self.Z, self.Y, self.X, self.pix_T_cams[:,s+1])\n\n                occ_vis.append(self.summ_writer.summ_occ('', occ_mem0, only_return=True))\n                \n                feat_mem0_input = torch.cat([occ_mem0, unp_mem0*occ_mem0], dim=1)\n                feat_mem1_input = torch.cat([occ_mem1, unp_mem1*occ_mem1], dim=1)\n                _, feat_halfmem0 = self.feat3dnet(feat_mem0_input)\n                _, feat_halfmem1 = self.feat3dnet(feat_mem1_input)\n\n                entity_loss, cam0_T_cam1_e, _ = self.entitynet(\n                    feat_halfmem0,\n                    feat_halfmem1,\n                    cam0_T_cam1_g,\n                    self.vox_util)\n                \n            elif hyp.do_match:\n                assert(hyp.do_feat3d)\n\n                # what i want to do here is:\n                # instead of using xyz_cams[:,s]\n                # i want to use the total pointcloud accumulated so far,\n                # in the coordinate frame of s (called 0 here)\n\n                # i have cam0s_T_camIs_e\n                # i think i can back-transform each pointcloud with this,\n                # then forward-transform it to the s sys\n\n                use_map = False\n                use_second_stage = True\n                # use_second_stage = False\n\n                xyz_cams = self.xyz_cams[:,:s+1]\n                cam0_T_cams_e = cam0s_T_camIs_e[:,:s+1]\n                cam0_T_cams_g = cam0s_T_camIs_g[:,:s+1]\n                xyz_cam0s_e = __u(utils.geom.apply_4x4(__p(cam0_T_cams_e), __p(xyz_cams)))\n                xyz_cam0s_g = __u(utils.geom.apply_4x4(__p(cam0_T_cams_g), __p(xyz_cams)))\n                xyz_cam0_e = xyz_cam0s_e.reshape(self.B, -1, 3)\n                xyz_cam0_g = xyz_cam0s_g.reshape(self.B, -1, 3)\n                xyz_camI_e = utils.geom.apply_4x4(utils.geom.safe_inverse(cam0_T_cams_e[:,s]), xyz_cam0_e)\n                xyz_camI_g = utils.geom.apply_4x4(utils.geom.safe_inverse(cam0_T_cams_g[:,s]), xyz_cam0_g)\n\n                xyz_e_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n                xyz_g_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n                xyz_e = utils.geom.apply_4x4(__p(cam0s_T_camIs_e), xyz_e_).reshape(self.B, self.S, 3)\n                xyz_g = utils.geom.apply_4x4(__p(cam0s_T_camIs_g), xyz_g_).reshape(self.B, self.S, 3)\n\n                self.vox_util_wide = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=torch.mean(xyz_g[:,:s+1], dim=1), assert_cube=False)\n                wider = 8\n                self.vox_util_wide.XMIN = self.vox_util_wide.XMIN - wider*8\n                self.vox_util_wide.YMIN = self.vox_util_wide.YMIN #- wider*1\n                self.vox_util_wide.ZMIN = self.vox_util_wide.ZMIN - wider*8\n                self.vox_util_wide.XMAX = self.vox_util_wide.XMAX + wider*8\n                self.vox_util_wide.YMAX = self.vox_util_wide.YMAX #+ wider*1\n                self.vox_util_wide.ZMAX = self.vox_util_wide.ZMAX + wider*8\n\n                occ_mem0_e = self.vox_util_wide.voxelize_xyz(xyz_cam0_e, self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n                occ_mem0_g = self.vox_util_wide.voxelize_xyz(xyz_cam0_g, self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n                stab_vis_e.append(self.summ_writer.summ_traj_on_occ(\n                    '',\n                    xyz_e[:,:s+1],\n                    occ_mem0_e,\n                    self.vox_util_wide,\n                    traj_g=xyz_g[:,:s+1],\n                    already_mem=False,\n                    sigma=1,\n                    only_return=True))\n                stab_vis_g.append(self.summ_writer.summ_traj_on_occ(\n                    '',\n                    xyz_e[:,:s+1],\n                    occ_mem0_g,\n                    self.vox_util_wide,\n                    traj_g=xyz_g[:,:s+1],\n                    already_mem=False,\n                    sigma=1,\n                    only_return=True))\n                diff_vis.append(self.summ_writer.summ_oned('', torch.abs(occ_mem0_e - occ_mem0_g), bev=True, only_return=True, norm=True))\n\n                if not use_map:\n                    xyz_camI_e = self.xyz_cams[:,s].clone()\n                    \n                occ0_mem0 = self.vox_util.voxelize_xyz(xyz_camI_e, self.Z, self.Y, self.X)\n                rgb0_mem0 = self.vox_util.unproject_rgb_to_mem(\n                    self.rgb_cams[:,s], self.Z, self.Y, self.X, self.pix_T_cams[:,s])\n                \n                occ1_mem1 = self.vox_util.voxelize_xyz(self.xyz_cams[:,s+1], self.Z, self.Y, self.X)\n                rgb1_mem1 = self.vox_util.unproject_rgb_to_mem(\n                    self.rgb_cams[:,s+1], self.Z, self.Y, self.X, self.pix_T_cams[:,s+1])\n\n                occ_vis.append(self.summ_writer.summ_occ('', occ0_mem0, only_return=True))\n                \n                occ_rs = []\n                rgb_rs = []\n                feat_rs = []\n                feat_rs_trimmed = []\n                for ind, rad in enumerate(self.radlist):\n                    rad_ = torch.from_numpy(np.array([0, rad, 0])).float().cuda().reshape(1, 3)\n                    occ_r, rgb_r = self.place_scene_at_dr(\n                        rgb0_mem0, xyz_camI_e, rad_,\n                        self.Z, self.Y, self.X, self.vox_util)\n                    occ_rs.append(occ_r)\n                    rgb_rs.append(rgb_r)\n\n                    inp_r = torch.cat([occ_r, occ_r*rgb_r], dim=1)\n                    _, feat_r = self.feat3dnet(inp_r)\n                    feat_rs.append(feat_r)\n                    feat_r_trimmed = feat_r[:,:,self.trim:-self.trim:,self.trim:-self.trim:,self.trim:-self.trim:]\n                    feat_rs_trimmed.append(feat_r_trimmed)\n\n                    if rad==0:\n                        # feat_vis.append(self.summ_writer.summ_feat('', feat_r, pca=True, only_return=True))\n                        feat_all.append(feat_r)\n                \n                feat_mem1_input = torch.cat([occ1_mem1, occ1_mem1*rgb1_mem1], dim=1)\n                \n                _, feat_halfmem1 = self.feat3dnet(feat_mem1_input)\n\n                _, cam1_T_cam0_e, cam0_T_cam1_e = self.matchnet(\n                    torch.stack(feat_rs_trimmed, dim=1), # templates\n                    feat_halfmem1, # search region\n                    self.vox_util)\n\n                if use_second_stage:\n                    # let's re-name our output, to make clear that it's just partway to the end\n                    camP_T_cam0_e = cam1_T_cam0_e.clone()\n                    cam0_T_camP_e = cam0_T_cam1_e.clone()\n\n                    # xyz_camI_e is almost good;\n                    # we just need to apply the transformation we got from the first step, to bring it a bit closer to the future\n                    xyz_camI2_e = utils.geom.apply_4x4(cam1_T_cam0_e, xyz_camI_e)\n                    rgb0_mem0 = self.vox_util.unproject_rgb_to_mem(\n                        self.rgb_cams[:,s], self.Z, self.Y, self.X, self.pix_T_cams[:,s])\n                    occ_rs = []\n                    rgb_rs = []\n                    feat_rs = []\n                    feat_rs_trimmed = []\n                    for ind, rad in enumerate(self.radlist):\n                        rad_ = torch.from_numpy(np.array([0, rad, 0])).float().cuda().reshape(1, 3)\n                        occ_r, rgb_r = self.place_scene_at_dr(\n                            rgb0_mem0, xyz_camI2_e, rad_,\n                            self.Z, self.Y, self.X, self.vox_util)\n                        occ_rs.append(occ_r)\n                        rgb_rs.append(rgb_r)\n\n                        inp_r = torch.cat([occ_r, occ_r*rgb_r], dim=1)\n                        _, feat_r = self.feat3dnet(inp_r)\n                        feat_rs.append(feat_r)\n                        feat_r_trimmed = feat_r[:,:,self.trim:-self.trim:,self.trim:-self.trim:,self.trim:-self.trim:]\n                        feat_rs_trimmed.append(feat_r_trimmed)\n\n                    feat_mem1_input = torch.cat([occ1_mem1, occ1_mem1*rgb1_mem1], dim=1)\n                    _, feat_halfmem1 = self.feat3dnet(feat_mem1_input)\n                    # this time, we are transforming between P and 1\n                    _, cam1_T_camP_e, camP_T_cam1_e = self.matchnet(\n                        torch.stack(feat_rs_trimmed, dim=1), # templates\n                        feat_halfmem1, # search region\n                        self.vox_util)\n                    # print('cam1_T_camP_e', cam1_T_camP_e.detach().cpu().numpy())\n                    cam1_T_cam0_e = utils.basic.matmul2(cam1_T_camP_e, camP_T_cam0_e)\n                    cam0_T_cam1_e = utils.basic.matmul2(cam0_T_camP_e, camP_T_cam1_e)                \n\n            # chain cam0_T_camN * camN_T_camM to get cam0_T_camM\n            cam0s_T_camIs_e[:,s+1] = utils.basic.matmul2(cam0s_T_camIs_e[:,s], cam0_T_cam1_e)\n            cam0s_T_camIs_g[:,s+1] = utils.basic.matmul2(cam0s_T_camIs_g[:,s], cam0_T_cam1_g)\n\n        # diffs = [torch.abs(e - g) for (e,g) in zip(stab_vis_e, stab_vis_g)]\n        self.summ_writer.summ_rgbs('inputs/occ_vis', occ_vis)\n        # self.summ_writer.summ_rgbs('inputs/feat_vis', feat_vis)\n        self.summ_writer.summ_rgbs('inputs/stab_vis_e', stab_vis_e)\n        self.summ_writer.summ_rgbs('inputs/stab_vis_g', stab_vis_g)\n        # self.summ_writer.summ_rgbs('inputs/stab_vis_d', diffs)\n        self.summ_writer.summ_rgbs('inputs/diff_vis', diff_vis)\n        self.summ_writer.summ_feats('inputs/feat_vis', feat_all, pca=True) # pca all together!\n\n        xyz_e_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        xyz_g_ = torch.zeros((self.B*self.S, 1, 3), dtype=torch.float32, device=torch.device('cuda'))\n        cam0s_T_camIs_e_ = __p(cam0s_T_camIs_e)\n        cam0s_T_camIs_g_ = __p(cam0s_T_camIs_g)\n        xyz_e_ = utils.geom.apply_4x4(cam0s_T_camIs_e_, xyz_e_)\n        xyz_g_ = utils.geom.apply_4x4(cam0s_T_camIs_g_, xyz_g_)\n        xyz_e = xyz_e_.reshape(self.B, self.S, 3)\n        xyz_g = xyz_g_.reshape(self.B, self.S, 3)\n\n        mean_epe = torch.mean(torch.norm(xyz_e[:,-1] - xyz_g[:,-1], dim=1))\n        self.summ_writer.summ_scalar('unscaled_entity/mean_epe', mean_epe)\n        \n        xz_e = torch.stack([xyz_e[:,-1,0], xyz_e[:,-1,2]], dim=1)\n        xz_g = torch.stack([xyz_g[:,-1,0], xyz_g[:,-1,2]], dim=1)\n        mean_epe_bev = torch.mean(torch.norm(xz_e - xz_g, dim=1))\n        self.summ_writer.summ_scalar('unscaled_entity/mean_epe_bev', mean_epe_bev)\n\n        # wide_centroid = torch.mean(xyz_g, dim=1)\n        # self.vox_util_wide = utils.vox.Vox_util(self.Z, self.Y, self.X, self.set_name, scene_centroid=wide_centroid, assert_cube=True)\n        # wider = 16\n        # self.vox_util_wide.XMIN = self.vox_util_wide.XMIN - wider*4\n        # self.vox_util_wide.YMIN = self.vox_util_wide.YMIN - wider*1\n        # self.vox_util_wide.ZMIN = self.vox_util_wide.ZMIN - wider*4\n        # self.vox_util_wide.XMAX = self.vox_util_wide.XMAX + wider*4\n        # self.vox_util_wide.YMAX = self.vox_util_wide.YMAX + wider*1\n        # self.vox_util_wide.ZMAX = self.vox_util_wide.ZMAX + wider*4\n        \n        occ_mem0 = self.vox_util_wide.voxelize_xyz(self.xyz_cams[:,0], self.Z*2, self.Y*1, self.X*2, assert_cube=False)\n        self.summ_writer.summ_traj_on_occ(\n            'entity/traj',\n            xyz_e,\n            occ_mem0,\n            self.vox_util_wide,\n            traj_g=xyz_g,\n            already_mem=False,\n            sigma=1)\n\n        total_loss += mean_epe\n        self.summ_writer.summ_scalar('loss', total_loss.cpu().item())\n        return total_loss, results, False\n    \n    def forward(self, feed):\n        data_ok = self.prepare_common_tensors(feed)\n        data_ok = False\n        \n        if not data_ok:\n            # return early\n            total_loss = torch.tensor(0.0).cuda()\n            return total_loss, None, True\n        else:\n            if self.set_name=='train':\n                return self.run_train(feed)\n            elif self.set_name=='test':\n                return self.run_sfm(feed)\n                # return self.run_orb(feed)\n                # return self.run_test(feed)\n            else:\n                print('not prepared for this set_name:', set_name)\n                assert(False)\n                \n","sub_path":"pytorch_disco_recovery/model_kitti_entity.py","file_name":"model_kitti_entity.py","file_ext":"py","file_size_in_byte":40437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"3114904","text":"#!/usr/bin/env python\nfrom entrypoint import get_bots\nimport os\nimport shutil\n\ndef delete_screen(screen_name):\n    os.system(f\"screen -S {screen_name} -X quit\")\n\n\ndef cleanup(*args):\n    for arg in args:\n        try:\n            shutil.rmtree(arg)\n        except Exception as err:\n            print(err)\n\n\nif __name__ == '__main__':\n    input(\"Các màn hình gnu đang chạy tất cả các chương trình của bots.yml sẽ bị dừng! ↵\")\n    input(\"Các thư mục bộ nhớ đệm của mỗi bot sẽ bị xóa ↵\")\n    for botname in get_bots().keys():\n        delete_screen(botname)\n        cleanup(botname)\n","sub_path":"clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"467031804","text":"# 1. SELECT * FROM data;\nimport pandas as pd\ndata = {'id':[x for x in range(1,7)], 'Name':['张三','李四','王五','赵六','翠花', '二丫'], 'Sex': ['男','男','男','男','女','女'], 'age':[23, 26, 24, 19, 18, 15]}\ndf = pd.DataFrame(data)\nprint(df)\n\nimport pymysql\nsql  =  'SELECT *  FROM data'\nconn = pymysql.connect('ip','name','pass','dbname','charset=utf8')\ndf = pd.read_sql(sql,conn)\n\n# 2. SELECT * FROM data LIMIT 10;\nprint(df.head(10))\n\n# 3. SELECT id FROM data;  //id 是 data 表的特定一列\nprint(df['id'])\n\n# 4. SELECT COUNT(id) FROM data;\nprint(df.shape[0])\n\n# 5. SELECT * FROM data WHERE id<1000 AND age>30;\nprint( df[(df['id'] < 1000) & (df['age'] > 30)])\n\n# 6. SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id;\ndf1 = df1.groupby('id')\ncount_order_id = df1.drop_duplicates(subset=order_id,inplace=False).shape[0]\ndf1['id', 'count_order_id']\n\n# 7. SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id;\npd.merge(table1, table2, on='id', how='inner')\n\n# 8. SELECT * FROM table1 UNION SELECT * FROM table2;\ndf4 = pd.concat([table1, table2])\nprint(df4)\n\n# 9. DELETE FROM table1 WHERE id=10;\ndf.drop(df[df.id == 10].index, inplace=True)\n\n# 10. ALTER TABLE table1 DROP COLUMN xis\ndf.drop('age',axis=1, inplace=True)","sub_path":"week04/sql_pandas.py","file_name":"sql_pandas.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"248399300","text":"# _*_ coding:utf-8 _*_\n# 文件作者: ZHMing123\n# 开发时间:2020/2/4 20:50\n# 文件名称:self_ex.py\n# 开发工具:PyCharm\n\n# python对象的自省机制\n# 自省是通过一定的机制查询到对象的内部结构\nfrom chapter04.static_class_instance_method import Date\nclass Person:\n    \"\"\"\n    zhming\n    \"\"\"\n    name = \"Person\"\n\nclass Student(Person):\n    def __init__(self, school_name):\n        self.school_name = school_name\n\n\nif __name__ == '__main__':\n    user = Student(\"广东工业大学\")\n    print(user.__dict__)\n    print(user.name)\n    print(dir(user))    # 比.__dict__功能更强大\n    print(dir(Person))\n    print(Person.__dict__)","sub_path":"chapter04/self_ex.py","file_name":"self_ex.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"562461106","text":"# Author: Lucas Galleguillos\n# Filename: webScrape.py\n# Description: Task described at http://rosettacode.org/wiki/Web_scraping\n\nimport urllib.request\nwith urllib.request.urlopen(\"http://tycho.usno.navy.mil/cgi-bin/timer.pl\") as response:\n\thtml = response.readlines()\n\nresponse.close()\n\na = []\n\nfor line in html:\n\tif \"UTC\" in line.decode():\n\t\ta = line.decode().split(\" \")\n\t\tfor l in a:\n\t\t\tif \":\" in l:\n\t\t\t\tprint(\"Current time is \" + l + \" UTC\")\n\t\t\t\tbreak\n\t\tbreak\n\n","sub_path":"ProgrammingTasks/WebScraping/webScrape.py","file_name":"webScrape.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"51579645","text":"# encoding: UTF-8\nfrom PyQt4 import QtGui, QtCore\n\nfrom btcore import BackTestRunner\n\n\nclass GuiSignal(QtCore.QObject):\n    def __init__(self):\n        pass\n\n\nclass MainWindow(QtGui.QWidget):\n    def __init__(self, ):\n        super(MainWindow, self).__init__()\n\n        self.initUI()\n\n        self.runner = BackTestRunner(onTestComplete=self.onTestComplete)\n\n    def initUI(self):\n\n        self.btn1 = QtGui.QPushButton('button 1')\n        self.btn2 = QtGui.QPushButton('button 2')\n        self.btn3 = QtGui.QPushButton('button 3')\n        self.btn4 = QtGui.QPushButton('button 4')\n        self.displayTable = DisplayTable()\n        self.logArea = QtGui.QTextEdit()\n        self.logArea.setReadOnly(True)\n        self.logArea.setMaximumHeight(300)\n\n        hbox = QtGui.QHBoxLayout()\n        hbox.addWidget(self.btnRefresh)\n        hbox.addWidget(self.btn2)\n        hbox.addWidget(self.btn3)\n        hbox.addWidget(self.btn4)\n        hbox.addStretch()\n\n        vbox = QtGui.QVBoxLayout()\n        vbox.addLayout(hbox)\n        vbox.addWidget(self.displayTable)\n        vbox.addWidget(self.logArea)\n\n        self.setLayout(vbox)\n\n    def addTest(self, testConfig):\n        test = self.runner.add(testConfig)\n        self.displayTable.updateDataCell(test)\n\n    def run(self):\n        self.runner.runAll()\n\n    def refresh(self):\n        for test in self.runner.d.values():\n            self.displayTable.updateDataCell(test)\n\n    def onTestComplete(self, id):\n        self.displayTable.updateDataCell(self.runner.d[id])\n\n\nclass DisplayTable(QtGui.QTableWidget):\n    def __init__(self):\n        super(DisplayTable, self).__init__()\n\n        self.dataCellDict = {}\n\n        self.pkey = 'id'\n\n        self.headers = ['id', 'database', 'vtSymbol', 'startDate', 'endDate', 'initDays', 'status']\n\n        # 设置表格的列数\n        self.setColumnCount(len(self.headers))\n\n        # 设置列表头\n        self.setHorizontalHeaderLabels(self.headers)\n\n        # 关闭左边的垂直表头\n        self.verticalHeader().setVisible(False)\n\n        # 设为不可编辑\n        self.setEditTriggers(self.NoEditTriggers)\n\n        # 设为行交替颜色\n        self.setAlternatingRowColors(True)\n\n        # 设置允许排序\n        self.setSortingEnabled(True)\n\n    def updateDataCell(self, test):\n        data = test.__dict__\n\n        pkey = data[self.pkey]\n        # 新增\n        if pkey not in self.dataCellDict:\n            rowCount = self.rowCount()\n            self.insertRow(rowCount)\n\n            d = {}\n            for n, header in enumerate(self.headers):\n                cell = DataCell(data[header])\n                self.setItem(rowCount, n, cell)\n                d[header] = cell\n\n            self.dataCellDict[pkey] = d\n        # 更新\n        else:\n            statusCell = self.dataCellDict[pkey]['status']\n            statusCell.setText(str(data['status']))\n\n            # for header in self.headers:\n            #     cell = cells[header]\n            #     cell.setText(str(data[header]))\n\n\nclass DataCell(QtGui.QTableWidgetItem):\n    def __init__(self, data):\n        super(DataCell, self).__init__()\n        self.setData(QtCore.Qt.DisplayRole, data)\n\nif __name__ == '__main__':\n    import platform\n    import ctypes\n    import sys\n    from common.component import DbClient\n\n    # 重载sys模块,设置默认字符串编码方式为utf8\n    reload(sys)\n    sys.setdefaultencoding('utf8')\n\n    # 设置Windows底部任务栏图标\n    if 'Windows' in platform.uname():\n        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('BackTestWindow')\n\n    # 初始化Qt应用对象\n    app = QtGui.QApplication(sys.argv)\n\n    # 设置Qt的皮肤\n    try:\n        import qdarkstyle\n        app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))\n    except:\n        pass\n\n    mw = MainWindow()\n    mw.showMaximized()\n\n    testConfig = {'database': 'BAR_1DAY',\n               'startDate': '20150101',\n               'endDate': '20161231',\n               'initDays': 10,\n               'testMode': True,\n               'dataMode': 'BAR',\n               'tradeSetting': {'className': 'SimpleTrade'},\n               'signalSetting': {'className': 'SimpleSignal'}}\n\n    collections = DbClient().getCollections('BAR_1DAY')\n    for i in range(100):\n        for vtSymbol in collections:\n            testConfig['vtSymbol'] = str(vtSymbol)\n            mw.addTest(testConfig)\n\n    mw.run()\n    sys.exit(app.exec_())\n\n","sub_path":"backtest/btGui.py","file_name":"btGui.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"406074462","text":"\"\"\"\nWstep do programowania\nKolokwium termin 0\n9.01.2019 grupa P11-57j\nimie:\nnazwisko:\nindeks:\n\"\"\"\n\n'''\nZadanie 2 (15 pkt.)\nPrzygotuj program, w którego zadaniem będzie wydrukowanie alfabetu\nw porządku rosnącym (od a do z). Wykorzystaj informację,\nże w kodzie ASCI literom a-z odpowiadają liczby od 65 do 90.\nSformatuj napis wyjściowy tak aby w jednym wierszu znalazły się\n3 kolejne litery alfabetu rozdzielone znakiem ;.\n\nPamiętaj o dobrych praktykach pisania kodu,\ntzn. przygotuj funkcję main() oraz jej wywołanie.\n\nOczekiwany komunikat na ekranie:\n\nAlfabet w porządku rosnacym:\nA;B;C\nD;E;F\nG;H;I\nJ;K;L\nM;N;O\nP;Q;R\nS;T;U\nV;W;X\nY;Z;\n'''\n\ndef main(): # definicja funkcji main 1pkt\n    print(\"Alfabet w porządku rosnacym:\")\n    x = 0 # zapewnienie sobie zmiennej do\n    for i in range(65, 91): # poprawna pętla 4 pkt\n        x+=1\n        if x%3: # warunek na ; 2pkt\n            print(chr(i), end=\";\") # poprawna zamiana kodu ASCI na znak 3\n        else: # kiedy enter 2 pkt\n            print(chr(i), end=\"\\n\") # drukowanie komunikatów 2\n\nmain() # wywołanie funkcji main 1 pkt\n","sub_path":"Laboratory 13/answers/wdp_ftopt_l12z02r_A.py","file_name":"wdp_ftopt_l12z02r_A.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"325339972","text":"### LINEAR AND CIRCULAR CONVOLUTION \ndef reverse(arg):\n    if isinstance(arg,list):\n        arg.reverse()\n        return arg\n    return\n\ndef right_shift(rh):    \n    temp=[]\n    lrh = len(rh)\n    for i in range(lrh):\n        if i==0:\n           temp.append(rh[-1])\n        else:\n            temp.append(rh[i-1])\n    #print(rh,temp)\n    return temp\n\n### linear convolution by matrix method\ndef linear(x,h):\n    ### get length of x(n)\n    lx=len(x)\n    \n    ### get length of h(n)\n    lh=len(h)\n    \n    ### create lx+1 x lh+1 matrix \n    mat=[[0 for i in range(lh+1)] for i in range(lx+1)]\n    #print mat\n    \n    ### begin to fill matrix\n    for i in range(lx+1):\n        for j in range(lh+1):\n            #print i,j\n            \n            ### top left corner is not required. Hence initialized it with -1\n            if i==0 and j==0:\n                mat[i].insert(j,-1)\n                #print mat[i][j],mat[i][j+1]\n                del mat[i][j+1]\n            \n            ### first row : insert values of h(n)\n            elif i==0:\n                mat[i].insert(j,h[j-1])\n                del mat[i][j+1]\n                \n            ### first column : insert values of x(n)\n            elif j==0:\n                mat[i].insert(j,x[i-1])\n                #print mat[i][j],mat[i][j+1]\n                del mat[i][j+1]\n                \n            ### for all other entries, val = mat[first_row][current_colum]*mat[first_column][current_row]\n            else:\n                #print i,j,mat[i][0]*mat[0][j]\n                mat[i].insert(j,mat[i][0]*mat[0][j])\n                del mat[i][j+1]\n        ### display matrix row by row\n        #print mat[i]\n        #print(mat[i])\n    \n    ### initialize output response y(n)\n    y={2:0,3:0,4:0,5:0,6:0,7:0,8:0}\n    \n    ### calculate each value of y(n) from matrix\n    for i in range(1,lx+1):\n        for j in range(1,lh+1):\n            if i!=0 or j!=0:\n                \n                y[i+j]=mat[i][j]\n                #print y[i+j],i,j\n    print(\"linear convolution= \",y)\n    return\n    \n\ndef circular(x,h):\n    lx = len(x)\n    lh = len(h)\n    \n    if lx>lh:\n        d=lx-lh\n        for i in range(d):\n            h.append(0)\n        lh = len(h)\n    elif lh>lx:\n        d=lh-lx\n        for i in range(d):\n            x.append(0)\n        lx = len(x)\n    #print(x,h)\n    \n    \n    #mat_h=[[0 for i in range(lh)] for j in range(lh)]\n    mat_h=[]\n    #print(mat_h)\n    \n    ### form mat h\n    \n    rh=reverse(h)\n    #print(rh)\n    \n    ### form matrix by circular right shift each row in each iteration\n    rh=right_shift(rh)\n    mat_h.append(rh)\n    for i in range(lh):\n        \n        if i==lh-1:\n            break\n        else:\n            rh=right_shift(rh)\n            mat_h.append(rh)\n    #print(mat_h)\n    #result_in_json(\"x(n)\",x,False)\n    #result_in_json(\"h(n)\",h,True)\n    #result_in_json(\"matrix_h\",mat_h)\n    \n    ### matrix multiplication\n    result=[]\n    for i in range(lx):\n        temp=0\n        for j in range(lx):\n            temp+=mat_h[i][j]*x[j]\n        result.append(temp)\n    print(\"circular convolution= \",result)\n\n### start point of program\n#x = raw_input(\"Enter values of x(n){Ex:1,2,3}\").split(\",\")\nx=[1,2,3,1]\n\n### Read values of impulse response h(n) from user\n#h = raw_input(\"Enter values of h(n){Ex:2,3}\").split(\",\")\nh=[4,3,2,2]\n\n### perform linear convolution\nlinear(x,h)\n\n### perform linear convolution\ncircular(x,h)\n    \n    \n","sub_path":"final_convolution.py","file_name":"final_convolution.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"321727514","text":"__author__ = 'zihaozhu'\nimport tkinter as tk\n\nclass MainWindow(tk.Tk):\n\n    def __init__(self, *args, **kwargs):\n        tk.Tk.__init__(self, *args, **kwargs)\n        container = self.Frame(self)\n\n        container.pack(side=\"top\", fill=\"both\", expand=True)\n\n        container.grid_rowconfigure(0, weight = 1)\n        container.grid_columnconfigure(0, weight = 1)\n\n        self.frames = {}\n\n        \n\n","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"252938129","text":"#!/usr/bin/env python\n#\n\nimport sys, os\nsys.path.insert(0, os.path.abspath(\"../data\"))\n\nimport unittest\nimport numpy\n\n\nclass TestCase(unittest.TestCase):\n\n    def test1(self):\n        \"multiphonon.forward.phonon.DWExp\"\n        from multiphonon.forward.phonon import DWExp\n        from dos import loadDOS\n        E, g = loadDOS()\n        dE = E[1]-E[0]\n        import numpy as np\n        Q = np.arange(0,20,0.1)\n        M = 50.94 # vanadium\n        # M = 58.6934 # nicole\n        \n        kelvin2mev = 0.0862\n        T = 300\n        beta = 1./(T*kelvin2mev)\n        dwexp = DWExp(Q, M, E,g, beta, dE)\n        print(dwexp)\n        return\n        \n        \n    pass  # end of TestCase\n\n\nif __name__ == \"__main__\": unittest.main()\n    \n# End of file \n","sub_path":"tests/forward/phonon_TestCase2.py","file_name":"phonon_TestCase2.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"157371018","text":"def accuracy(label, predictedY):\n    assert len(label) == len(predictedY)\n    return sum([label[i] == predictedY[i] for i in range(len(label))]) / len(label)\n\ndef f1_score(label, predictedY):\n    assert len(label) == len(predictedY)\n    try:\n        p = len([x for x in range(len(label)) if label[x] == predictedY[x] == 1]) * 1.0 / len([x for x in label if x == 1])\n        r = len([x for x in range(len(label)) if label[x] == predictedY[x] == 1]) / len([x for x in predictedY if x == 1])\n\n        return p * r * 200 / (p + r), p, r\n    except ZeroDivisionError:\n        return -1,0,0\n\ndef get_score(label, predictedY):\n    print(\"===== score =====\")\n    print(\"accuracy:{}\".format(accuracy(label,predictedY)))\n    f1,precision,recall = f1_score(label, predictedY)\n    print(\"f1:{},precision:{},recall:{}\".format(f1,precision,recall))\n\n","sub_path":"tf_demo_code/phish/dnn_tools/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"21864128","text":"from pmdarima import auto_arima\nfrom datetime import datetime\nimport pandas as pd\nfrom pathlib import Path\nimport statsmodels.api as sm\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom pathlib import Path\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n\ndata_folder = Path(\"../data/\")\n\ndata = pd.read_csv(data_folder / 'che.csv')\n\ndta = data[['new_cases', 'date']]\ndta = dta['new_cases'].replace(to_replace=0, method='ffill')\ndates = list(data['date'])\n\ndta.index = [datetime.strptime(f\"{date}{datetime.now().year}\", \"%d%b%Y\") for date in dates]\nresult = seasonal_decompose(dta,\n                            model='additive')\n\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n# Fit auto_arima function to AirPassengers dataset\nstepwise_fit = auto_arima(dta, start_p=1, start_q=1,\n                          max_p=3, max_q=3, m=1,\n                          start_P=0, seasonal=False,\n                          d=None, D=None, trace=True,\n                          error_action='ignore',  # we don't want to know if an order does not work\n                          suppress_warnings=True,  # we don't want convergence warnings\n                          stepwise=True)  # set to stepwise\n\n# To print the summary\nstepwise_fit.summary()\narma_mod11 = sm.tsa.ARMA(dta, (1, 1), freq='D').fit(disp=False)\npred = arma_mod11.predict(datetime(2020, 4, 30, 0, 0), datetime(2020, 5, 9, 0, 0))\n\nx = np.asarray(data['new_cases'])\n\ndf = pd.read_csv('che.csv')[['date', 'new_cases']]\ndf.columns = ['Date', 'Number of new daily cases']\n\nx = ['30Apr','01May','02May','03May','04May','05May','06May','07May','08May','09May']\n\n\nfig = px.bar(df, x='Date', y='Number of new daily cases')\nX = list(list(df['Date'])+x)\nY = list(list(df['Number of new daily cases'])+list(pred))\n\nfig = go.Figure(data=[go.Bar(\n    x= X,\n    y=Y,\n    marker_color=['rgba(82,95,216, 1)' for x in range(len(X)-len(pred))] +\n                 ['rgba(242,63,63, 1)' for x in range(len(pred))]\n)])\n\nfig.update_layout(\n    title='Predicted evolution of new daily COVID-19 cases\\n'\n             'in Switzerland using ARMA model',\n    autosize=False,\n    width=680,\n    height=500,\n    xaxis=dict(title='Date', tickangle=45, tickfont=dict(size=10), titlefont=dict(size=10)),\n    yaxis=dict(title='New daily cases', tickfont=dict(size=10), titlefont=dict(size=10)),\n    titlefont=dict(size=12),\n    title_x=0.5\n)\n\nfig.write_html('plotly_prediction_cases.html', include_plotlyjs='cdn')","sub_path":"scripts/prediction_cases_interactive.py","file_name":"prediction_cases_interactive.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"306398819","text":"\"\"\"Salp Swarm Algorithm.\n\"\"\"\n\nimport numpy as np\n\nimport opytimizer.math.random as r\nimport opytimizer.utils.logging as l\nfrom opytimizer.core import Optimizer\n\nlogger = l.get_logger(__name__)\n\n\nclass SSA(Optimizer):\n    \"\"\"A SSA class, inherited from Optimizer.\n\n    This is the designed class to define SSA-related\n    variables and methods.\n\n    References:\n        S. Mirjalili et al. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems.\n        Advances in Engineering Software (2017).\n\n    \"\"\"\n\n    def __init__(self, params=None):\n        \"\"\"Initialization method.\n\n        Args:\n            params (dict): Contains key-value parameters to the meta-heuristics.\n\n        \"\"\"\n\n        logger.info('Overriding class: Optimizer -> SSA.')\n\n        # Overrides its parent class with the receiving params\n        super(SSA, self).__init__()\n\n        # Builds the class\n        self.build(params)\n\n        logger.info('Class overrided.')\n\n    def update(self, space, iteration, n_iterations):\n        \"\"\"Wraps Salp Swarm Algorithm over all agents and variables.\n\n        Args:\n            space (Space): Space containing agents and update-related information.\n            iteration (int): Current iteration.\n            n_iterations (int): Maximum number of iterations.\n\n        \"\"\"\n\n        # Calculates the `c1` coefficient (eq. 3.2)\n        c1 = 2 * np.exp(-(4 * iteration / n_iterations) ** 2)\n\n        # Iterates through every agent\n        for i, _ in enumerate(space.agents):\n            # Checks if it is the first agent\n            if i == 0:\n                # Iterates through every decision variable\n                for j, (lb, ub) in enumerate(zip(space.agents[i].lb, space.agents[i].ub)):\n                    # Generates two uniform random numbers\n                    c2 = r.generate_uniform_random_number()\n                    c3 = r.generate_uniform_random_number()\n\n                    # Checks if random number is smaller than 0.5\n                    if c3 < 0.5:\n                        # Updates the leading salp position (eq. 3.1 - part 1)\n                        space.agents[i].position[j] = space.best_agent.position[j] + c1 * ((ub - lb) * c2 + lb)\n\n                    # If random number is bigger or equal to 0.5\n                    else:\n                        # Updates the leading salp position (eq. 3.1 - part 2)\n                        space.agents[i].position[j] = space.best_agent.position[j] - c1 * ((ub - lb) * c2 + lb)\n\n            # If it is not the first agent\n            else:\n                # Updates the follower salp position (eq. 3.4)\n                space.agents[i].position = 0.5 * (space.agents[i].position + space.agents[i-1].position)\n","sub_path":"opytimizer/optimizers/swarm/ssa.py","file_name":"ssa.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"34502359","text":"import cv2\n\nI = cv2.imread('sq/office/input/in000001.jpg')\nI = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)\nI = cv2.threshold(I, 100, 255, cv2.THRESH_BINARY)\nI = I[1]\n\ni_step = 3\ni_start = 570\ni_stop = 2050\nfgbg = cv2.createBackgroundSubtractorMOG2(10, 2, 1)\nfor i in range(i_start, i_stop, i_step):\n    TP_p = 0\n    TN_p = 0\n    FP_p = 0\n    FN_p = 0\n    I_clr = cv2.imread('sq/office/input/in00' + str('{0:04}'.format(i)) + '.jpg')\n    fgmask = fgbg.apply(I_clr)\n    cv2.imshow('frame', fgmask)\n    cv2.waitKey(20)","sub_path":"lab2_background_model/zad4.py","file_name":"zad4.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"512153097","text":"from django.urls import path, re_path\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.utils.safestring import mark_safe\nfrom django.urls import reverse\nfrom django.forms import ModelForm\nfrom django.http import QueryDict\nfrom curd.service.views import ShowView\n\n\nclass CURDConfig:\n    \"\"\"  为每一个`model_class`模型类生成url路径与视图函数之间的映射关系\n\n    Methods 分类:\n        路由部分:\n                add_request_decorator\n                get_urls\n                extra_url\n\n        功能权限部分:\n                get_list_display\n                get_show_add_btn\n                get_show_search_form\n                get_search_list\n                get_show_action_form\n                get_action_list\n\n        记录操作权限部分:\n                delete\n                change\n                checkbox\n\n        反向解析url部分:\n                get_delete_url\n                get_change_url\n                get_add_url\n                get_show_url\n\n        视图函数部分:\n                show_view\n                add_view\n                delete_view\n                change_view\n\n        表单部分:\n                get_model_form_class\n\n        搜索功能部分:\n                create_search_condition\n                get_combain_search_field_list\n\n    \"\"\"\n\n    def __init__(self, model_class, curb_site_obj):\n        self.model_class = model_class\n        self.site = curb_site_obj\n        self.request = None\n        self._query_str_key = '_filter'\n\n    def get_app_model(self):\n        \"\"\" 获取当前模型类的名称和该模型类所在应用的名称\n        Return:\n              返回一个存放二元元组: (模型类名, 应用名)\n        \"\"\"\n\n        app_model = (\n            self.model_class._meta.app_label,\n            self.model_class._meta.model_name\n        )\n        return app_model\n\n    def add_request_decorator(self, view_func):\n        \"\"\" 在执行进入视图函数之前为config对象添加request属性\n            本项目中没有使用语法糖\"@\",而是使用了比较原始的方式.\n            比如:\n                使用\"self.add_request_decorator(self.show_view)\"\n        Args:\n            view_func: 要被装饰的视图函数\n        \"\"\"\n\n        def inner(request, *args, **kwargs):\n            self.request = request\n            return view_func(request, *args, **kwargs)\n        return inner\n\n    def get_urls(self):\n        \"\"\" 生成路径与视图函数映射关系的列表,并扩展该列表\n        Return:\n            返回存放路由关系的列表\n        \"\"\"\n\n        # 生成增、删、改、查基本映射关系\n        app_model = self.get_app_model()\n        urlpatterns = [\n            re_path(r'^$', self.add_request_decorator(self.show_view), name='%s_%s_show' % app_model),\n            re_path(r'^add/$', self.add_request_decorator(self.add_view), name='%s_%s_add' % app_model),\n            re_path(r'^(\\d+)/delete/$', self.add_request_decorator(self.delete_view), name='%s_%s_delete' % app_model),\n            re_path(r'^(\\d+)/change/$', self.add_request_decorator(self.change_view), name='%s_%s_change' % app_model),\n        ]\n\n        # 扩展路由映射关系\n        extra_patterns = self.extra_url()\n        urlpatterns.extend(extra_patterns)\n        return urlpatterns\n\n    @property\n    def urls(self):\n        return self.get_urls()\n\n    def extra_url(self):\n        \"\"\" 为用户扩展urls提供的接口,只需要在CURDConfig派生类中派生覆盖此方法即可\n        Return:\n            存放了路径与视图函数映射关系的列表(re_path, path, url)\n        \"\"\"\n\n        return []\n\n    list_display = []  # 存放列表页面表格要显示的字段\n\n    def get_list_display(self):\n        \"\"\" 处理用户权限之内的相关操作,派生CURDConfig类中可以根据用户权限来分配响应的功能按钮/链接,\n            实现每个类中可以在增删改查之外,再扩展自己类的URL\n        Return:\n            包含了权限操作按钮/链接在内的列表\n        \"\"\"\n\n        data = []\n        if self.list_display:\n            data.extend(self.list_display)\n            data.append(CURDConfig.delete)      # 注意:是函数而不是方法!\n            data.append(CURDConfig.change)\n            data.insert(0, CURDConfig.checkbox)\n        return data\n\n    show_add_btn = False        # 先否显示添加按钮权限接口\n\n    def get_show_add_btn(self):\n        \"\"\" CURDConfig中,根据用户权限来判断用户是否有添加记录按钮对应的权限,如果有则返回True\n        Return:\n            布尔值,代表用户是否有权限,该值将传递给上下文中用于渲染页面添加按钮\n        \"\"\"\n\n        # 中间存放业务逻辑\n        return self.show_add_btn\n\n    def delete(self, obj=None, is_header=False):\n        \"\"\" 列表页面单条记录删除按钮/链接,可以在CURDConfig派生类中根据用户权限分配该功能\n        Args:\n            obj: 该记录对象\n            is_header: 当用于生成列表标题\"\"的时候为True\n        Return:\n            一个SafeText对象,可以将字符串中的html内容转化为标签,\n            此处为删除功能的超链接\n        \"\"\"\n\n        if is_header:\n            return '删除'\n        return mark_safe('删除' % (self.get_delete_url(obj.id), ))\n\n    def change(self, obj=None, is_header=False):\n        \"\"\" 列表页面单条记录编辑按钮/链接,可以在CURDConfig派生类中根据用户权限分配该功能\n        Args:\n            obj: 该记录对象\n            is_header: 当用于生成列表标题\"\"的时候为True\n        Return:\n            编辑功能超链接\n        \"\"\"\n\n        if is_header:\n            return '编辑'\n        query_str = self.request.GET.urlencode()\n        if not query_str:\n            return mark_safe('编辑' % (self.get_change_url(obj.id), ))\n        else:\n            params = QueryDict(mutable=True)\n            params[self._query_str_key] = query_str\n            return mark_safe('编辑' % (self.get_change_url(obj.id), params.urlencode(), ))\n\n    def checkbox(self, obj=None, is_header=False):\n        \"\"\" 列表页面单条记录的选择checkbox,用于批量记录操作,可以在CURDConfig派生类中根据用户权限分配该功能\n        Args:\n            obj: 该checkbox所在记录对象\n            is_header: 当用于生成列表标题\"\"的时候为True\n        Return:\n            关于选择该条记录的checkbox框\n        \"\"\"\n\n        if is_header:\n            return '选择'\n        return mark_safe('' % (obj.id, ))\n\n    def get_delete_url(self, nid):\n        \"\"\" 获取删除记录对应的路径\n        Args:\n            nid: 该记录的id\n        Return:\n            字符串形式的路径\n        \"\"\"\n\n        alias = 'curd:%s_%s_delete' % self.get_app_model()\n        return reverse(alias, args=(nid, ))\n\n    def get_change_url(self, nid):\n        \"\"\" 获取编辑记录对应的url\n        Args:\n            nid: 该记录的id\n        Return:\n            字符串形式的路径\n        \"\"\"\n\n        alias = 'curd:%s_%s_change' % self.get_app_model()\n        return reverse(alias, args=(nid, ))\n\n    def get_show_url(self):\n        \"\"\" 获取列表页面的url\n        Return:\n            字符串形式的路径\n        \"\"\"\n\n        alias = 'curd:%s_%s_show' % self.get_app_model()\n        return reverse(alias)\n\n    def get_add_url(self):\n        \"\"\" 获取增加记录对应的url\n        Return:\n            字符串形式的路径\n        \"\"\"\n\n        alias = 'curd:%s_%s_add' % self.get_app_model()\n        return reverse(alias)\n\n    def show_view(self, request, *args, **kwargs):\n        \"\"\" 列表页面对应的视图函数\n        功能:\n            1. 对于GET请求,返回列表页面\n            2. 对于批量操作action的POST请求,执行该action,执行完该action之后,可以自定义返回值,也可以没有,按需求而定\n        Return:\n            HttpResponse: 返回包含渲染好了的页面的响应对象\n        \"\"\"\n\n        if request.method == 'POST' and self.get_show_action_form():            # action操作提交的POEST请求\n            func_name = request.POST.get('action')\n            func = getattr(self, func_name)\n            if func:\n                ret = func(request, *args, **kwargs)                            # 可以根据权限自定义返回值\n\n        combain_condition = {}                                                  # 组装组合搜索的条件\n        option_list = self.get_combain_search_field_list()\n        for key in request.GET.keys():\n            value_list = request.GET.getlist(key)\n            flag = False\n            for option in option_list:\n                if option.field_name == key:\n                    flag = True\n                    break\n            if flag:\n                combain_condition['%s__in' % key] = value_list\n\n        objects = self.model_class.objects.filter(self.create_search_condition()).filter(**combain_condition)\n        show_obj = ShowView(self, objects)\n        return render(request, 'curd/show.html', {\"show_obj\": show_obj})\n\n    model_form_class = None\n\n    def get_model_form_class(self):\n        \"\"\" 获取modelform表单,如果在派生的CURDConfig中创建了ModelForm派\n            生类,就使用该类,否则使用默认的ViewModelForm\n\n        Return:\n            ModelForm类的派生类\n        \"\"\"\n\n        if self.model_form_class:\n            return self.model_form_class\n        else:\n            meta_class = type(\n                'Meta',\n                (object, ),\n                {\"model\": self.model_class,\n                 \"fields\": \"__all__\"}\n            )\n\n            ViewModelForm = type(\n                'ViewModelForm',\n                (ModelForm, ),\n                {\"Meta\": meta_class}\n            )\n            return ViewModelForm\n\n    show_search_form = False\n\n    def get_show_search_form(self):\n        \"\"\" 获取用户搜索权限对应的值。show_search_form默认为false,\n            可以在派生类中根据用户权限修改\n        Return:\n            用户有搜索权限(\"show_search_form=True\")对应的布尔值\n        \"\"\"\n\n        return self.show_search_form\n\n    search_list = []\n\n    def get_search_list(self):\n        \"\"\" 获取要被搜索的字段,该字段来源于列表search_list,\n            可以在派生类中覆盖该列表或根据用户搜索的权限范围划定\n\n        \"\"\"\n\n        result = []\n        if self.search_list:\n            result.extend(self.search_list)\n        return result\n\n    def create_search_condition(self):\n        \"\"\" 根据列表页面搜索框中提交的value创建查询条件\n        Return:\n            返回一个包含了查询条件的Q对象\n        \"\"\"\n\n        from django.db.models import Q\n\n        query_str = self.request.GET.get('query')\n        query_condition = Q()\n        query_condition.connector = 'OR'\n        if query_str and self.get_show_search_form():       # self.get_show_search_form()判断是为了防止没有所有权限的用户通过url搜索\n            for field in self.get_search_list():\n                query_condition.children.append((field, query_str), )\n        return query_condition\n\n    combain_search_field_list = []\n\n    def get_combain_search_field_list(self):\n        \"\"\" 获取组合搜索中要作为搜索条件的字段,可以在派生类中指定字��\n\n        \"\"\"\n\n        result = []\n        if self.combain_search_field_list:\n            result.extend(self.combain_search_field_list)\n        return result\n\n    show_action_form = False\n\n    def get_show_action_form(self):\n        \"\"\" 获取用户action批量操作功能对应的权限。show_action_form默认为false,\n            同样需要在派生类中根据用户权限来修改该值\n        Returrn:\n            用户action权限对应的布尔值\n        \"\"\"\n\n        return self.show_action_form\n\n    action_list = []\n\n    def get_action_list(self):\n        \"\"\" 获取action批量操作的具体内容,比如批量删除\"multi_delete\",\n            action_list中的元素需要是函数/方法。\n\n        \"\"\"\n        result = []\n        if self.action_list:\n            result.extend(self.action_list)\n        return result\n\n    def add_view(self, request):\n        \"\"\" 添加记录路径对应的视图函数\n        Args:\n            request: 当前请求对象\n        Return:\n            HttpResponse: 包含响应结果的响应对象。如果是GET请求,返回页面,如果是POST请求,将重定向至列表页面\n        \"\"\"\n\n        model_form_class = self.get_model_form_class()\n\n        if request.method == 'GET':\n            return render(request, 'curd/add.html', {\"form\":model_form_class()})\n        else:\n            form = model_form_class(data=request.POST)\n            if form.is_valid():\n                obj = form.save()\n\n                _popbackid = request.GET.get('_popbackid')                  # 是否是通过popup添加\n                if _popbackid:\n                    response_data = {\n                        \"id\": obj.pk,\n                        \"text\": str(obj),\n                        \"_popbackid\": _popbackid\n                    }\n                    return render(request, \"curd/popback.html\", {\"response_data\": response_data})\n                else:\n                    return redirect(to=self.get_show_url())\n            else:\n                return render(request, 'curd/add.html', {\"form\": form})\n\n    def delete_view(self, request, nid):\n        \"\"\" 删除一条记录\n        Args:\n            request: 当前请求对象\n            nid: 当前要被删除的记录的id\n        Return:\n            HttpResponse: 重定向到列表页面\n        \"\"\"\n\n        obj = self.model_class.objects.filter(id=nid)\n        obj.delete()\n        return redirect(self.get_show_url())\n\n    def change_view(self, request, nid):\n        \"\"\" 编辑一条记录\n        Args:\n            request: 当前请求对象\n            nid: 当前要被编辑的记录的id\n        Return:\n            GET请求: 返回编辑页面\n            POST请求: 验证编辑后的数据\n                1. 验证通过,重定向到列表页面\n                2. 验证失败,返回包含错误信息的编辑页面\n        \"\"\"\n\n        obj = self.model_class.objects.filter(id=nid).first()\n        if not obj:\n            return redirect(self.get_show_url())\n\n        model_form_class = self.get_model_form_class()\n\n        if request.method == 'GET':\n            form = model_form_class(instance=obj)\n            return render(request, 'curd/change.html', {\"form\":form})\n        else:\n            form =model_form_class(data=request.POST, instance=obj)\n            if form.is_valid():\n                form.save()\n                # 保证编辑完返回查询的结果路径\n                if request.GET.get(self._query_str_key):\n                    url_redirect = '%s?%s' % (self.get_show_url(), request.GET.get(self._query_str_key))\n                else:\n                    url_redirect = self.get_show_url()\n                return redirect(to=url_redirect)\n            else:\n                return render(request, 'curd/change.html', {\"form\": form})\n\n\n\nclass CURDSite:\n    \"\"\" 可以看作一个容器,其静态属性`_registry`放置着`model_class`模\n        型类和模型对应的`config_obj`配置对象。\n\n\n    \"\"\"\n    def __init__(self):\n        self._registry = {}         # 存放model及其对应的CURBConfig()实例键值对\n\n    def register(self, model_class, curd_config_class=None):\n        \"\"\" 注册传入的model模型类,如果没有提供配置类curd_config_class,默认使用CURDConfig类\n        Args:\n            model_class: models.py中要注册的模型类\n            curd_config_class: 模型类对应的配置类\n        Return:\n            None\n        \"\"\"\n\n        if not curd_config_class:\n            curd_config_class = CURDConfig\n        self._registry[model_class] = curd_config_class(model_class, self)\n\n    def get_urls(self):\n        \"\"\" 编辑包含已注册模型类的字典,生成路径与下一级路由分发的映射关系\n        Return:\n            包含映射关系的列表\n        \"\"\"\n\n        urlpatterns = []\n        for model_class, curd_config_obj in self._registry.items():\n            app_name = model_class._meta.app_label\n            model_name = model_class._meta.model_name\n            temp_path = path(\n                '{app_name}/{model_name}/'.format(app_name=app_name, model_name=model_name),\n                (curd_config_obj.urls, None, None)\n            )\n            urlpatterns.append(temp_path)\n        return urlpatterns\n\n    @property\n    def urls(self):\n        return self.get_urls(), 'curd', None\n\n\nsite = CURDSite()       # 实现单例模式\n","sub_path":"curd/service/sites.py","file_name":"sites.py","file_ext":"py","file_size_in_byte":17009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"235409452","text":"from django.conf import settings\nfrom django.core.mail import get_connection\nfrom django.core.mail.message import EmailMultiAlternatives\n\n\ndef send_HTML_email(subject, recipient, text_content, html_content):\n\n    # If you get the return_path header wrong, this may impede mail delivery. It appears that the SMTP server\n    # has to recognize the return_path as being valid for the sending host. If we set it to, say, our SMTP\n    # server, this will always be the case (as the server is explicitly serving the host).\n    email_return_path = getattr(settings, 'EMAIL_RETURN_PATH', None)\n    if email_return_path is None:\n        # Get last two parts of the SMTP server as a proxy for the domain name from which this mail is sent.\n        # This works for gmail, anyway.\n        email_return_path = settings.EMAIL_LOGIN\n\n    email_from = getattr(settings, 'EMAIL_FROM', None)\n    if email_from is None:\n        email_from = email_return_path\n    from_header = {'From': email_from}  # From-header\n    connection = get_connection()\n\n    msg = EmailMultiAlternatives(subject, text_content, email_return_path, [recipient], headers=from_header, connection=connection)\n    msg.attach_alternative(html_content, \"text/html\")\n    msg.send()\n","sub_path":"dimagi/utils/django/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"133163603","text":"#!/bin/env python -tt\n#######################################################################\n# Search AD to see if UID matches any others in Microsoft AD\n#\n# Helpful video:  https://www.youtube.com/watch?v=fhQE342ZTrk\n#\n# Created by: J.Lickey\n# 20220317\n#######################################################################\n\n# How to connect to AD from a machine that is not a member of the domain\nfrom ldap3 import Connection,Server\nimport ADenv,ADip\nimport subprocess,argparse,sys,os\n\ndef uidsearch(uid2search):\n    # Variables\n    entry_lst = []\n    uid_lst = []\n\n    # Sets up SSL connection to AD Server\n    server = Server(ADip.ip, use_ssl=True)\n\n    # Sets up actual connection to AD Server, passing in user and credentials\n    con = Connection(server, ADenv.admin_user + \"@\" + ADenv.domain, ADenv.admin_passwd, auto_bind=True)\n\n    # Search AD and pull out user ID if it exists\n    con.search(ADenv.base_dn, \"(uid={})\".format(uid2search), attributes=['uid','gecos'])\n    uid_list = con.entries\n    con.unbind()\n    \n    for entry in uid_list:\n        entry_lst.append(str(entry).split())\n    \n    # Check to see if entry_lst is empty\n    if len(entry_lst) == 0:\n        return False\n    else:\n        for uid in entry_lst:\n            if uid[-1] == uid2search:\n                gecos = ' '.join(uid[11:13])\n                userid = uid[-1]\n                return True, gecos, userid\n\n\nif __name__ == \"__main__\":\n    uid2search = ''\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-u\", \"--user_id\", help=\"Enter user ID to search on\", type=str)\n    args = parser.parse_args()\n    try:\n        uid2search = str(sys.argv[2])\n        print(uidsearch(uid2search))\n    except Exception as Err:\n        cmd = 'python ADUserIDsearch.py -h'\n        output = subprocess.getoutput(cmd)\n        print(output)\n","sub_path":"ADAddUser/ADUserIDsearch.py","file_name":"ADUserIDsearch.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"486481401","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport os\n\ndef write(data):\n    if os.path.isfile(\"proxies_data.txt\"):\n        print(\"Unable to write to file\")\n    else:\n        f = open(\"proxies_data.txt\", \"w\")\n        f.write(data)\n        \ndef main():\n    #提取网页源码\n    url = \"http://ip.zdaye.com/dayProxy/ip/920.html\"\n    headers = {\"User-Agent\" : \"Mozilla/5.0 (Windows NT 6.1; rv:47.0) Gecko/20100101 Firefox/47.0\",}\n    req = urllib.request.Request(url, headers = headers)\n    resp = urllib.request.urlopen(req) #data=urllib.request.urlopen(url).read()  \n    respHtml = (resp.read()).decode(\"gb2312\")\n    #print(respHtml)\n\n    soup = BeautifulSoup(respHtml, \"html.parser\")\n    items = soup.find_all(\"div\", \"cont\")\n    #print(items)\n    for item in items:\n        link = item.find('br').get_text() \n        print(link + \"\\n\")\n        write(link)\nif __name__ == \"__main__\":\n    main()\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"633319711","text":"import redis\nimport qpython\nimport numpy\nimport time\nimport random\nfrom qpython import qconnection\nimport pandas as pd\nfrom datetime import datetime\nfrom qpython.qcollection import qlist\nfrom qpython.qtype import QException,QTIME_LIST,QSYMBOL_LIST,QFLOAT_LIST\n\n# print(numpy.datetime64(datetime.now()))\n# c = random.randint(1, 10)\n# ask=[random.random()*random.randint(1,100) for x in range(c)]\n# print(ask)\n# print()\n# data_Sym=['600040.SH']\n# print(qlist(data_Sym,qtype=QSYMBOL_LIST))\ndef publish_data(FTD_list):\n    #data_Sym=['600045.SH']\n    data_Sym=FTD_list[1]+'.SH'\n    #data_Timestamp=[numpy.datetime64(datetime.now(),'ns')]\n    data_Timestamp=numpy.datetime64(datetime.now().strftime(\"%Y-%m-%d\")+' '+old_FTD_list[0],'ns')\n    data_Open=float(FTD_list[4])\n    data_High=float(FTD_list[5])\n    data_Low=float(FTD_list[6])\n    data_Preclose=float(FTD_list[3])\n    data_Px=float(FTD_list[7])\n    data_Match=float(FTD_list[10])\n    data_Volume=float(FTD_list[11])\n    data_Asks_Array=list(map(float,old_FTD_list[42:62:2]))\n    data_AvgAsk=float(FTD_list[16])\n    data_AskSizes_Array=list(map(float,old_FTD_list[43:63:2]))\n    data_TotalAsk=float(FTD_list[15])\n    data_Bids_Array=list(map(float,old_FTD_list[62:82:2]))\n    data_AvgBid=float(FTD_list[14])\n    data_BidSizes_Array=list(map(float,old_FTD_list[63:83:2]))\n    data_TotalBid=float(FTD_list[13])\n    #期货的前结算价\n    data_Presettle=None\n    data_Settle=None\n    data_to_publish=[numpy.string_(data_Sym),data_Timestamp,data_Open,data_High,data_Low,data_Preclose,data_Px,data_Match,data_Volume,data_Asks_Array,data_AskSizes_Array,data_AvgAsk,data_AskSizes_Array,data_TotalAsk,data_Bids_Array,data_AvgBid,data_BidSizes_Array,data_TotalBid,data_Presettle,data_Settle]\n    return data_to_publish\n\n\nif __name__=='__main__':\n    #publish_data()\n    #print(datetime.now())\n    #print(type(datetime.now()))\n    '''\n    lisitest=[6444005,\"2018-12-13 13:33:37.541653\",1.1,7]\n    #转换成字符串\n    old_sym=str(lisitest[0])+'.SH'\n    #转换成浮点数\n    new_num=float(lisitest[2])\n    #切片操作,不包括最后一个\n    cut=lisitest[1:3]\n\n    print(old_sym,new_num)\n    print(type(old_sym),type(new_num))\n    print(cut)\n    '''\n    print(\"connect to redis...\")\n    #r = redis.Redis(host='10.20.104.29', port=9379, db=0)\n    #增加参数decode_responses=True,不然,接收的数据需要重新编码\n    r = redis.Redis(host='127.0.0.1', port=9379, db=0,decode_responses=True)\n    ret = r.execute_command('mget', 'mdl.4.4.')\n    print(ret)\n    #print(ret[0])\n    #print(type(ret[0]))\n    old_FTD_list=ret[0].split(',')\n    #print(old_FTD_list)\n    #对接收到的list进行处理\n    #print(old_FTD_list[1])\n    print(old_FTD_list[0])\n    print(float(old_FTD_list[2]))\n\n    #data_to_publish=publish_data(old_FTD_list)\n    #print(data_to_publish)\n    del r\n\n\n\n\n'''\n    #对于pandas对象\n    #自动进行类型转换\n    cmc_data=lisitest.infer_objects()\n    #将类型强制转为为时间戳类型\n    #cmc_data['DATES']=pd.to_datetime(cmc_data['DATES'])\n    cmc_data.index=pd.DatetimeIndex(cmc_data[\"DATES\"])\n    print(cmc_data.dtypes)\n'''","sub_path":"通联数据/draft.py","file_name":"draft.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"107001111","text":"def solution(N):\n    zero = []\n    N = bin(N)[2:]\n    if (N.count('0') == 0) or (N.count('1') == 1):\n        return 0\n    else:\n        N = N[1:]\n        y = N.split('1')\n        del y[-1]\n        for i in range(len(y)):\n            zero.append(len(y[i]))\n        zero.sort(reverse = True)\n        return zero[0]","sub_path":"Lesson 1/binarygap.py","file_name":"binarygap.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"620642159","text":"\"\"\"\n    - Nhập một số n nguyên dương bất kỳ từ bàn phím với n <1000\n        + Nếu số nhập vào không đúng điều kiện thì yêu cầu nhập lại\n    - Tính tổng các chữ số của số đó\n        + Ta phải tách số n ra thành các số hàng trăm, hàng chục và hàng đơn vị\n        + Sau đó cộng tổng lại với nhau.\n    - Hiển thị kết quả ra màn hình\n\"\"\"\nwhile True:\n    n = int(input('Nhap vao so nguyen duong n (n < 1000) '))\n    if 0 < n < 1000:\n        break\n\n'''\n    Ta cũng có thể viết theo cách 2: tuy nhiên cách này ta phải gán giá trị cho n trước\n    \n    n = 0\n    while n <= 0 or n >=1000:\n        n = int(input('Nhap vao so nguyen duong n (n < 1000) ')) \n        \n'''\n\n# Tiến hành tách số n ra thành hàng trăm, hàng chục, hàng đơn vị\n# Tách lấy số hàng trăm bằng cách lấy n // 1000\n# Tách lấy số hàng chục bằng phép toán lấy số dư của phép chia n cho 100\n# chia cho 10 ta lấy phần nguyên sẽ ra được số hàng chục, còn phần dư sẽ\n# là số đơn vị\n# ví dụ 123 // 100 = 1 - hàng trăm\n#       123 % 100 = 23\n#       23 // 10 = 2 - hàng chục\n#       23 % 10 =3 - hàng đơn vị\nso_hang_tram = n // 100\nso_hang_chuc = (n % 100) // 10\nso_hang_donvi = (n % 100) % 10\n\nprint('Số n = {} có tổng các chữ số bằng = {}'.format(n, so_hang_tram + so_hang_chuc + so_hang_donvi))\n","sub_path":"KiemtrasoN.py","file_name":"KiemtrasoN.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"522316175","text":"import numpy as np\nfrom scipy import ndimage as ndi\nfrom skimage.measure import regionprops\nfrom joblib import Memory\nfrom scipy.ndimage.morphology import binary_dilation\n\n\nlocation = './cachedir'\nmemory = Memory(location, verbose=0)\n\n\ndef remove_antenna(half_binary):\n    \"\"\"Remove antenna if connected to the wing\n\n    Arguments\n    ---------\n    half_binary : 2D array\n        binary image of left/right wing\n\n    Returns\n    -------\n    without_antenna : 2D array\n        binary image, same shape as input without antenna (if it touches the\n        wing)\n    \"\"\"\n\n    markers, _ = ndi.label(1-half_binary, ndi.generate_binary_structure(2, 1))\n    regions = regionprops(markers)\n\n    areas = np.array([r.area for r in regions])\n    idx_sorted = 1 + np.argsort(-areas)[:2]\n\n    try:\n        dilated_bg = binary_dilation(markers == idx_sorted[0], iterations=35)\n        dilated_hole = binary_dilation(markers == idx_sorted[1], iterations=35)\n        intersection = np.minimum(dilated_bg, dilated_hole)\n        without_antenna = np.copy(half_binary)\n        without_antenna[intersection] = 0\n    except IndexError:\n        return half_binary\n\n    return without_antenna\n\n\ndef detect_outer_pix(half_binary, side):\n    \"\"\"Relative (r, c) coordinates of outer pixel (wing's tip)\n\n    Arguments\n    ---------\n    half_binary : 2D array\n        binary image of left/right wing\n    side : str\n        left ('l') or right ('r') wing\n\n    Returns\n    -------\n    outer_pix : 1D array\n        relative coordinates of the outer pixel (r, c)\n    \"\"\"\n    if side == 'r':\n        width = half_binary.shape[1]\n        corner = np.array([0, width])\n    else:\n        corner = np.array([0, 0])\n\n    markers, _ = ndi.label(half_binary,\n                           ndi.generate_binary_structure(2, 1))\n    regions = regionprops(markers)\n    areas = [r.area for r in regions]\n    idx_max = np.argmax(areas)\n\n    coords = regions[idx_max].coords\n    distances = np.linalg.norm(coords - corner, axis=1)\n    idx_outer_pix = np.argmin(distances)\n    outer_pix = coords[idx_outer_pix]\n\n    return outer_pix\n\n\ndef detect_inner_pix(half_binary, outer_pix, side):\n    \"\"\"Relative (r, c) coordinates of the inner pixel (between wing and body)\n\n    Arguments\n    ---------\n    half_binary : 2D array\n        binary image of left/right wing\n    outer_pix : 1D array\n        (r, c) coordinates (relative) of the outer pixel\n    side : str\n        left ('l') or right ('r') wing\n\n    Returns\n    -------\n    inner_pix : 2D array\n        relative coordinates of the inner pixel (r, c)\n    \"\"\"\n    lower_bound = int(half_binary.shape[0]*0.75)\n\n    if side == 'l':\n        focus = half_binary[:lower_bound, outer_pix[1]:]\n    else:\n        focus = half_binary[:lower_bound, :outer_pix[1]]\n\n    focus_inv = 1 - focus\n\n    markers, _ = ndi.label(focus_inv, ndi.generate_binary_structure(2, 1))\n    regions = regionprops(markers)\n    areas = [r.area for r in regions]\n    idx_max = np.argmax(areas)\n    coords = regions[idx_max].coords\n    y_max = np.max(coords[:, 0])\n    mask = (coords[:, 0] == y_max)\n    selection = coords[mask]\n    if side == 'l':\n        idx = np.argmax(selection[:, 1])\n    else:\n        idx = np.argmin(selection[:, 1])\n\n    outer_pix = selection[idx]\n\n    return outer_pix\n\n\ndef split_picture(binary):\n    \"\"\"Calculate the middle of the butterfly.\n\n    Parameters\n    ----------\n    binary : ndarray of bool\n        Binary butterfly mask.\n\n    Returns\n    -------\n    midpoint : int\n        Horizontal coordinate for middle of butterfly.\n\n    Notes\n    -----\n    Currently, this is calculated by finding the center\n    of gravity of the butterfly.\n    \"\"\"\n\n    means = np.mean(binary, 0)\n    normalized = means / np.sum(means)\n    sum_values = 0\n    for i, value in enumerate(normalized):\n        sum_values += i * value\n    return int(sum_values)\n\n\n@memory.cache()\ndef main(binary, axes=None):\n    \"\"\"Find and retunrs the coordinates of the 4 points of interest\n\n    Arguments\n    ---------\n    binary : 2D array\n        Binarized and and cropped version of the butterfly\n    ax : obj\n        If any is provided, POI, smoothed wings boundaries and binary will\n        be plotted on it\n\n    Returns\n    -------\n    points_interest : dictionary \n        dictionary containing the points of interest in the form [y, x],\n        keyed with \"outer_pix_l\", \"inner_pix_l\", \"outer_pix_r\", \"inner_pix_r\", \n        \"body_center\"\n    \"\"\"\n    binary = binary_dilation(binary, iterations=2)\n\n    # Split the butterfly\n    middle = split_picture(binary)\n\n    binary_left = binary[:, :middle]\n    binary_right = binary[:, middle:]\n\n    # Left wing\n    without_antenna_l = remove_antenna(binary_left)\n    outer_pix_l = detect_outer_pix(without_antenna_l, 'l')\n    inner_pix_l = detect_inner_pix(without_antenna_l, outer_pix_l, 'l')\n    inner_pix_l = inner_pix_l + np.array([0, outer_pix_l[1]])\n\n    # Right wing\n    without_antenna_r = remove_antenna(binary_right)\n    outer_pix_r = detect_outer_pix(without_antenna_r, 'r')\n    inner_pix_r = detect_inner_pix(without_antenna_r, outer_pix_r, 'r')\n    inner_pix_r = inner_pix_r + np.array([0, middle])\n    outer_pix_r = outer_pix_r + np.array([0, middle])\n\n    # Centroid of central column\n    middle_arr = binary[:, middle]\n    middle_y = int(np.mean(np.argwhere(middle_arr)))\n    body_center = (middle_y, middle)\n\n    points_interest = {\n        \"outer_pix_l\": outer_pix_l,\n        \"inner_pix_l\": inner_pix_l,\n        \"outer_pix_r\": outer_pix_r,\n        \"inner_pix_r\": inner_pix_r,\n        \"body_center\": body_center\n    }\n\n    # Reconstruct binary image without antennae\n    without_antennae = np.concatenate((without_antenna_l, without_antenna_r),\n                                      axis=1)\n    if axes and axes[2]:\n        axes[2].set_title('Points of interest')\n        axes[2].imshow(without_antennae)\n        axes[2].axvline(middle, color='m', linestyle='dashed')\n        markersize = 10\n        if axes[3]:\n            markersize = 2\n        points_interest_arr = np.array(list(points_interest.values()))\n        axes[2].scatter(points_interest_arr[:, 1], points_interest_arr[:, 0],\n                        color='r', s=markersize)\n\n    return points_interest\n","sub_path":"butterfly/tracing.py","file_name":"tracing.py","file_ext":"py","file_size_in_byte":6192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"530632686","text":"# -*- coding: utf-8 -*-\n##\n## This file is part of Invenio.\n## Copyright (C) 2011, HGF\n##\n## Invenio is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 2 of the\n## License, or (at your option) any later version.\n##\n## Invenio is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n## General Public License for more details.\n##\n## You should have received a copy of the GNU General Public License\n## along with Invenio; if not, write to the Free Software Foundation, Inc.,\n## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n\"\"\"\nUse statistics fields from 915 to notify about open access\nAlso evaluates arXiv and pmc stanzas from 0247_\n@author: arwagner\n\"\"\"\n__revision__ = \"$Id$\"\n\ndef format_element(bfo, src, separator=' ', onlyfirst='no'):\n    \"\"\"\n    Process StatID-fields (Marc 915) and produce links thereof\n\n    \"\"\"\n\n    # get an array of hashes for the identifier fields\n\n    tag    = \"915__\"\n    fields = bfo.fields(tag)\n    logos  = []\n    \n    imgnatli   = \"http://images.opac.d-nb.de/hermes/search/logo_dfg.jpg\"\n    imgallianz = \"http://images.opac.d-nb.de/hermes/search/logo_dfg.jpg\"\n    imgallianz = \"http://k1www.gbv.de/images/logos/natliz_logo.jpg\"\n    imgOA      = \"http://upload.wikimedia.org/wikipedia/commons/5/57/Oa_80x15_orange.png\"\n    hasOA      = 0\n    for i in fields:\n        # if['0'] == 'StatID:(DE-HGF)0420':\n        #   logos.append('')\n        if i['0'] == 'StatID:(DE-HGF)0500':\n          logos.append('')\n          hasOA = 1\n\n    # We also have OA if we have a PMC ID or arXiv or ... ?\n    tag    = \"0247_\"\n    fields = bfo.fields(tag)\n    for i in fields:\n        if i['2'] == 'pmc':\n          if hasOA == 0:\n             logos.append('')\n             hasOA = 1\n        if i['2'] == 'arXiv':\n          if hasOA == 0:\n             logos.append('')\n             hasOA = 1\n\n\n    if onlyfirst == 'yes':\n       return logos[0]\n    else:\n       return separator.join(logos)\n\ndef escape_values(bfo):\n    \"\"\"\n    Called by BibFormat in order to check if output of this element\n    should be escaped.\n    \"\"\"\n    return 0\n","sub_path":"lib/python/invenio/bibformat_elements/bfe_openaccess.py","file_name":"bfe_openaccess.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"597616251","text":"n = input()\nn = int(n)\ns = []\nfor i in range(n):\n    op,x = input().split()\n    if op == 'T':\n        s.append(x)\n    elif op == 'U':\n        for p in range(int(x)):\n            s.pop()\n    elif op =='Q':\n        print(s[int(x)-1])\n    else:\n        print('命令不合法')","sub_path":"Code/CodeRecords/2660/8246/306533.py","file_name":"306533.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"14797079","text":"from scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom socrata.items import SocrataItem\n\nclass MySpider(BaseSpider):\n\tname = 'socrata'\n\n\tallowed_urls = [\"opendata.socrata.com\"]\n\n\tstart_urls = [\"https://opendata.socrata.com\"]\n\n\tdef parse(self, response):\n\t\thxs = HtmlXPathSelector(response)\n\t\ttitles = hxs.select('//tr[@itemscope=\"itemscope\"]')\n\t\titems = []\n\t\tfor title in titles:\n\t\t\titem = SocrataItem()\n\t\t\titem['text'] = title.select(\"td[2]/div/span/text()\").extract()\n\t\t\titem['url'] = title.select(\"td[2]/div/a/@href\").extract()\n\t\t\titem['views'] = title.select(\"td[3]/span/text()\").extract()\n\t\t\titems.append(item)\n\t\treturn items","sub_path":"realpython/socrata/socrata/spiders/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"222163676","text":"All = open('./Gene&GO_F_With_Lethality.txt', mode='rb')\nMel = open('./Gene&GO_F_With_Lethality_Filtered.txt', mode='rb')\nOut = open('./Missing_From_Filtered.txt', mode='wb')\n\n\nMelList = []\nfor line in Mel:\n    #line = line.split(\"\\t\")\n    MelList.append(str(line))\n\nfor line in All:\n    #line = line.split(\",\")\n    g = line[0]\n    line = str(line)\n    if line not in MelList:\n        #line = ','.join(line)\n        Out.write(str(line))","sub_path":"Lost_Genes.py","file_name":"Lost_Genes.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"516360316","text":"# -*- coding: utf-8 -*-\nfrom maxclient.client import get_max_info\nfrom maxclient.client import get_max_url_from_hub_domain\nfrom maxclient.rest import MaxClient\nfrom hubclient.routes import ROUTES\n\n\nclass HubClient(MaxClient):\n    __routes__ = ROUTES\n    __defaults__ = {}\n\n    def __init__(self, domain, hub, max_server=None, **kwargs):\n        self.__max_server__ = max_server\n        self.domain = domain\n        kwargs['oauth_server'] = None\n        super(HubClient, self).__init__(hub, **kwargs)\n\n    @property\n    def max_server(self):\n        if self.__max_server__ is None:\n            self.__max_server__ = get_max_url_from_hub_domain(self.url, self.domain)\n        return self.__max_server__\n\n    @property\n    def oauth_server(self):\n        if self.__oauth_server__ is None:\n            max_info = get_max_info(self.max_server)\n            self.__oauth_server__ = max_info['max.oauth_server']\n        return self.__oauth_server__.rstrip('/')\n\n    def OAuth2AuthHeaders(self):\n        \"\"\"\n        \"\"\"\n        headers = {\n\n            'X-Oauth-Token': str(self.token),\n            'X-Oauth-Username': str(self.actor['username']),\n            'X-Oauth-Scope': str(self.scope),\n            'X-Oauth-Domain': str(self.domain),\n\n        }\n        return headers\n","sub_path":"hubclient/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"483617421","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nCopyright (c) 2014,MagickCode\nAll rights reserved.\n\n摘    要: routes.py\n创 建 者: WangLichao\n创建日期: 2014-08-07\n'''\n\nimport os\nroute_list = [\n    #(r\"/\", my_controller.MyHandler ),\n]\n\nimport tornado.web\n\nclass route(object):\n    \"\"\"修饰RequestHandlers 并且构造handler的url路由配置list\n    每次@route('...')被调用,都将自动添加配置的路径的路由URI到list中\n    并提供了重定向功能\n    Example\n    -------\n    @route('/some/path')\n    class SomeRequestHandler(RequestHandler):\n        def get(self):\n            goto = self.reverse_url('other')\n            self.redirect(goto)\n\n    @route('/some/other/path', name='other')\n    class SomeOtherRequestHandler(RequestHandler):\n        def get(self):\n            goto = self.reverse_url('SomeRequestHandler')\n            self.redirect(goto)\n\n    my_routes = route.get_routes()\n    \"\"\"\n\n    _routes = []\n\n    def __init__(self, uri, name=None):\n        self._uri = uri\n        self.name = name\n\n    def __call__(self, _handler):\n        \"\"\"如果类中有该修饰器,则该函数会被调用\n        Args:\n            _handler: tornado.web.RequestHandler对象\n        \"\"\"\n        name = self.name or _handler.__name__\n        self._routes.append(tornado.web.url(self._uri, _handler, name=name))\n        return _handler\n\n    @classmethod\n    def get_routes(self):\n        return self._routes\n\n# route_redirect\n# Example:\n#   from routes import route, route_redirect\n#   route_redirect('/smartphone$', '/smartphone/')\n#   route_redirect('/iphone/$', '/smartphone/iphone/', name='iphone_shortcut')\n#   @route('/smartphone/$')\n#   class SmartphoneHandler(RequestHandler):\n#        def get(self):\n#            ...\ndef route_redirect(from_, to, name=None):\n    route._routes.append(tornado.web.url(from_,\n                                         tornado.web.RedirectHandler,\n                                         dict(url=to),\n                                         name=name))\n\nclass RouteLoader(object):\n    '''获取路由配置规则\n    '''\n    @staticmethod\n    def load(package_name, include_routes_file=True):\n        loader = RouteLoader()\n        return loader.init_routes(package_name,include_routes_file)\n\n    def init_routes(self,package_name,include_routes_file=True):\n        import pkgutil,sys\n\n        package = __import__(package_name)\n        controllers_module = sys.modules[package_name]\n\n        prefix = controllers_module.__name__ + \".\"\n\n        # 支持子模块\n        path = os.path.abspath(controllers_module.__path__[0])\n        root_length = len(os.path.dirname(path) + '/')\n        for root, dirs, files in os.walk(path):\n            module_root = root\n            module_prefix = root[root_length:].replace(os.sep, '.') + '.'\n            for importer, modname, ispkg in pkgutil.iter_modules([module_root], module_prefix):\n                module = __import__(modname)\n\n        # 通过修饰器获取路由配置\n        url_routes = route.get_routes()\n\n        # 扩展路由配置\n        if include_routes_file:\n            url_routes.extend(route_list)\n        return url_routes\n\nif __name__ == '__main__':\n    pass\n\n","sub_path":"lib/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"240842418","text":"import math\nimport sys\nimport os\n\nprint(\"Welcome to HIKcalc!!\")\nprint(\"-----------------------------------------------\")\nprint(\"See commands and examples by typing 'help'\")\nprint(\"\")\nresult = 0\ncurrentMethod = \"addition\"\n\ndef addition(num1, num2):\n    returnSum = 0\n    returnSum = num1 + num2\n\n    return returnSum\n\ndef subtraction(num1, num2):\n    returnSum = 0\n    returnSum = num1 - num2\n\n    return returnSum\n\ndef multiplication(num1, num2):\n    returnSum = 0\n    returnSum = num1 * num2\n\n    return returnSum\n\ndef divison(num1, num2):\n    returnSum = 0\n    returnSum = num1 / num2\n\n    return returnSum\n\ndef sqareroot(num1):\n    returnSum = math.sqrt(num1)\n    return returnSum\n\ndef power(num1, num2):\n    returnSum = math.pow(num1, num2)\n    return returnSum\n\ndef userHelp():\n    print(\"\"\"\nCALCULATOR COMMANDS\n# plus -- Plus two numbers with each other. Takes 2 arguments.\n# min -- Minus a number with a number. Takes 2 arguments.\n# mult -- Multiply numbers. Takes 2 arguments.\n# divd -- Divide numbers. Takes 2 arguments.\n# sqrt -- Get sqareroot of number. Takes 1 argument.\n# pow -- Get det power of number. Takes 2 arguments.\n# deci -- End your command with 'deci' followed by how many decimals you want. Default is 2.\n\nEXAMPLES\n# Input: 'plus 40 5'\n# Output: '45'\n\n# Input: 'divd 243 34 deci 4'\n# Output: '7.1471'\n\n# Input: 'pow 4 2'\n# Output: '16'\n\nOTHER COMMANDS\n# exit -- Exit HIKcalc.\n# help -- List of commands and examples.\n# clear -- Clear the screen.\n\nSEE MORE\n# http://ingvar.hahnkristensen.dk/hikcalc\n# https://github.com/HikBit/HIKcalc\n\"\"\")\n\n\n#for x in range(0, 1):\nwhile True:\n    \n    decimals = 2\n    userInput = input(\"> \")\n    \n    if \"pi\" in userInput:\n        userInput = userInput.replace('pi', str(math.pi))\n    \n    if \" deci \" in userInput:\n        decimalsPosition = userInput.find('deci ') + 5\n        decimals = int(userInput[decimalsPosition : ])\n        \n        deleteDecimals = userInput.find(' deci ')\n        \n        userInput = userInput.replace(userInput[deleteDecimals : ], '')\n        \n    if userInput == \"help\":\n        userHelp()\n        \n\n#        PLUS\n    elif userInput.startswith('plus '):\n        userInput = userInput.replace('plus ', '', 1)\n        \n        try:\n            numbers = userInput.split(' ')\n                \n            if len(numbers) != 2:\n                print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            else:\n                i = 0\n            \n            for number in numbers:      \n                if i == 0:\n                    num1 = float(number)\n                    i =+ 1\n                else:\n                    num2 = float(number)\n            print(\"RESULT: \" + str(round(addition(num1, num2), decimals)))\n        except Exception:\n            print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            \n#        MINUS\n    elif userInput.startswith('min '):\n        userInput = userInput.replace('min ', '', 1)\n        \n        try:\n            numbers = userInput.split(' ')\n                \n            if len(numbers) != 2:\n                print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            else:\n                i = 0\n                \n                for number in numbers:      \n                    if i == 0:\n                        num1 = float(number)\n                        i =+ 1\n                    else:\n                        num2 = float(number)\n                print(\"RESULT: \" + str(round(subtraction(num1, num2), decimals)))\n        except Exception:\n            print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            \n#        MULTIPLY\n    elif userInput.startswith('mult '):\n        userInput = userInput.replace('mult ', '', 1)\n        \n        try:\n            numbers = userInput.split(' ')\n                \n            if len(numbers) != 2:\n\n                print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            else:\n                i = 0\n                \n                for number in numbers:      \n                    if i == 0:\n                        num1 = float(number)\n                        i =+ 1\n                    else:\n                        num2 = float(number)\n                print(\"RESULT: \" + str(round(multiplication(num1, num2), decimals)))\n        except Exception:\n            print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            \n#        DIVIDE\n    elif userInput.startswith('divd '):\n        userInput = userInput.replace('divd ', '', 1)\n        \n        try:\n            numbers = userInput.split(' ')\n                \n            if len(numbers) != 2:\n                print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            else:\n                i = 0\n                \n                for number in numbers:      \n                    if i == 0:\n                        num1 = float(number)\n                        i =+ 1\n                    else:\n                        num2 = float(number)\n                print(\"RESULT: \" + str(round(divison(num1, num2), decimals)))\n        except Exception:\n            print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            \n#        SQAREROOT\n    elif userInput.startswith('sqrt '):\n        userInput = userInput.replace('sqrt ', '', 1)\n        \n        try:\n            numbers = userInput.split(' ')\n                \n            if len(numbers) != 1:\n                print(\"ERROR: Make sure you are not using any letters. This command can only take 1 argument\")\n            else:\n                i = 0\n                \n                for number in numbers:      \n                    if i == 0:\n                        num1 = float(number)\n                        i =+ 1\n                    else:\n                        num2 = float(number)\n                print(\"RESULT: \" + str(round(sqareroot(num1), decimals)))\n        except Exception:\n            print(\"ERROR: Make sure you are not using any letters. This command can only take 1 argument\")\n            \n#        POWER\n    elif userInput.startswith('pow '):\n        userInput = userInput.replace('pow ', '', 1)\n        \n        try:\n            numbers = userInput.split(' ')\n                \n            if len(numbers) != 2:\n                print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            else:\n                i = 0\n                \n                for number in numbers:      \n                    if i == 0:\n                        num1 = float(number)\n                        i =+ 1\n                    else:\n                        num2 = float(number)\n                print(\"RESULT: \" + str(round(power(num1, num2), decimals)))\n        except Exception:\n            print(\"ERROR: Make sure you are not using any letters. This command can only take 2 arguments\")\n            \n    elif userInput == \"exit\":\n        sys.exit()\n    \n    elif userInput == \"clear\":\n        os.system('cls')\n    \n        \n    elif userInput == \"\":\n        pass\n    \n    else:\n        print(\"Not a valid command!!\")\n        \n\n        \n\n\n\n\n\n","sub_path":"HIKcalc.py","file_name":"HIKcalc.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"229008209","text":"#Join the contents of col1.txt and col2.txt, and create a text file whose each line contains the values of the first and second columns (separated by tab character) of the original file. Confirm the result by using paste command.\nfile_1 = open('/users/kcnco/github/100knock2021/pan/chapter02/col1.txt','r')\ncol1_lines = [line for line in file_1.readlines()]\nfile_2 = open('/users/kcnco/github/100knock2021/pan/chapter02/col2.txt','r')\ncol2_lines = [line for line in file_2.readlines()]\n\nfile_3 = open('/users/kcnco/github/100knock2021/pan/chapter02/col3.txt','w')\n\nfor i in range(len(col1_lines)):\n    file_3.write(col1_lines[i].strip()+'\\t'+col2_lines[i])\n\n#memo\n#strip() : delete beginning and ending\n","sub_path":"pan/chapter02/X13.py","file_name":"X13.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"224181972","text":"import re\n\ndef preprocess_token(w):\n    eyes = \"8:=;\"\n    nose = \"'`\\-\"\n    \n    w = re.sub('https?:\\/\\/\\S*|www\\.(\\w+\\.)+\\S*',\"  \",w)\n    w = re.sub(\"/\",\" / \",w)\n    w = re.sub('^@\\w+', \"\",w)\n    w = re.sub('['+re.escape(eyes)+']['+re.escape(nose)+']?[)d]+|[)d]+['+\\\n                  re.escape(nose)+']?['+re.escape(eyes)+']',\"  \",w)\n    w = re.sub('['+re.escape(eyes)+']['+re.escape(nose)+']?p+' ,\"  \",w)\n    w = re.sub('['+re.escape(eyes)+']['+re.escape(nose)+']?\\(+|\\)+['+\\\n                  re.escape(nose)+']?['+re.escape(eyes)+']',\"  \",w)\n    w = re.sub('['+re.escape(eyes)+']['+re.escape(nose)+']?(\\/|l*)', \"  \",w)\n    w = re.sub('<3',\"  \",w)\n    w = re.sub(r'([!?.])\\1{2,}',r\" \\1 \",w)\n    w = re.sub('^[-+]?.?[\\d]+[:,.\\d]*', \"  \",w)\n    w = re.sub(r'(\\S*?)(.)\\2{2,}', r'\\1\\2 ', w)   \n    return w\n\ndef preprocess_text(text):\n    text = text.lower().split()\n    for i in range(len(text)):\n        text[i] = preprocess_token(text[i])\n    text = ' '.join(text)\n    return text\n\nt = ' https://lol word2vector:-):-P:-(:-l d@ta @disij <3 A/B test -€2,500!!! Wayyy #senior2015'\nprint(preprocess_text(t)) \n\n\n\"\"\"\nOUTPUT:\n   word2vector         d@ta     a / b test    !  way  #senior2015\n\"\"\"","sub_path":"tokenize_tw.py","file_name":"tokenize_tw.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"15215331","text":"import requests\nimport json\nimport os\nimport collections\ntry:\n    import StringIO as io\nexcept:\n    import io\nimport logging\nimport time\nimport argparse\nfrom abc import abstractmethod\nfrom BCBio import GFF\nfrom Bio import SeqIO\nlogging.getLogger(\"requests\").setLevel(logging.CRITICAL)\nlog = logging.getLogger()\n\n\n#############################################\n###### BEGIN IMPORT OF CACHING LIBRARY ######\n#############################################\n# This code is licensed under the MIT       #\n# License and is a copy of code publicly    #\n# available in rev.                         #\n# e27332bc82f4e327aedaec17c9b656ae719322ed  #\n# of https://github.com/tkem/cachetools/    #\n#############################################\nclass DefaultMapping(collections.MutableMapping):\n\n    __slots__ = ()\n\n    @abstractmethod\n    def __contains__(self, key):  # pragma: nocover\n        return False\n\n    @abstractmethod\n    def __getitem__(self, key):  # pragma: nocover\n        if hasattr(self.__class__, '__missing__'):\n            return self.__class__.__missing__(self, key)\n        else:\n            raise KeyError(key)\n\n    def get(self, key, default=None):\n        if key in self:\n            return self[key]\n        else:\n            return default\n\n    __marker = object()\n\n    def pop(self, key, default=__marker):\n        if key in self:\n            value = self[key]\n            del self[key]\n        elif default is self.__marker:\n            raise KeyError(key)\n        else:\n            value = default\n        return value\n\n    def setdefault(self, key, default=None):\n        if key in self:\n            value = self[key]\n        else:\n            self[key] = value = default\n        return value\n\nDefaultMapping.register(dict)\n\n\nclass _DefaultSize(object):\n    def __getitem__(self, _):\n        return 1\n\n    def __setitem__(self, _, value):\n        assert value == 1\n\n    def pop(self, _):\n        return 1\n\n\nclass Cache(DefaultMapping):\n    \"\"\"Mutable mapping to serve as a simple cache or cache base class.\"\"\"\n\n    __size = _DefaultSize()\n\n    def __init__(self, maxsize, missing=None, getsizeof=None):\n        if missing:\n            self.__missing = missing\n        if getsizeof:\n            self.__getsizeof = getsizeof\n            self.__size = dict()\n        self.__data = dict()\n        self.__currsize = 0\n        self.__maxsize = maxsize\n\n    def __repr__(self):\n        return '%s(%r, maxsize=%r, currsize=%r)' % (\n            self.__class__.__name__,\n            list(self.__data.items()),\n            self.__maxsize,\n            self.__currsize,\n        )\n\n    def __getitem__(self, key):\n        try:\n            return self.__data[key]\n        except KeyError:\n            return self.__missing__(key)\n\n    def __setitem__(self, key, value):\n        maxsize = self.__maxsize\n        size = self.getsizeof(value)\n        if size > maxsize:\n            raise ValueError('value too large')\n        if key not in self.__data or self.__size[key] < size:\n            while self.__currsize + size > maxsize:\n                self.popitem()\n        if key in self.__data:\n            diffsize = size - self.__size[key]\n        else:\n            diffsize = size\n        self.__data[key] = value\n        self.__size[key] = size\n        self.__currsize += diffsize\n\n    def __delitem__(self, key):\n        size = self.__size.pop(key)\n        del self.__data[key]\n        self.__currsize -= size\n\n    def __contains__(self, key):\n        return key in self.__data\n\n    def __missing__(self, key):\n        value = self.__missing(key)\n        try:\n            self.__setitem__(key, value)\n        except ValueError:\n            pass  # value too large\n        return value\n\n    def __iter__(self):\n        return iter(self.__data)\n\n    def __len__(self):\n        return len(self.__data)\n\n    @staticmethod\n    def __getsizeof(value):\n        return 1\n\n    @staticmethod\n    def __missing(key):\n        raise KeyError(key)\n\n    @property\n    def maxsize(self):\n        \"\"\"The maximum size of the cache.\"\"\"\n        return self.__maxsize\n\n    @property\n    def currsize(self):\n        \"\"\"The current size of the cache.\"\"\"\n        return self.__currsize\n\n    def getsizeof(self, value):\n        \"\"\"Return the size of a cache element's value.\"\"\"\n        return self.__getsizeof(value)\n\n\nclass _Link(object):\n\n    __slots__ = ('key', 'expire', 'next', 'prev')\n\n    def __init__(self, key=None, expire=None):\n        self.key = key\n        self.expire = expire\n\n    def __reduce__(self):\n        return _Link, (self.key, self.expire)\n\n    def unlink(self):\n        next = self.next\n        prev = self.prev\n        prev.next = next\n        next.prev = prev\n\n\nclass _Timer(object):\n\n    def __init__(self, timer):\n        self.__timer = timer\n        self.__nesting = 0\n\n    def __call__(self):\n        if self.__nesting == 0:\n            return self.__timer()\n        else:\n            return self.__time\n\n    def __enter__(self):\n        if self.__nesting == 0:\n            self.__time = time = self.__timer()\n        else:\n            time = self.__time\n        self.__nesting += 1\n        return time\n\n    def __exit__(self, *exc):\n        self.__nesting -= 1\n\n    def __reduce__(self):\n        return _Timer, (self.__timer,)\n\n    def __getattr__(self, name):\n        return getattr(self.__timer, name)\n\n\nclass TTLCache(Cache):\n    \"\"\"LRU Cache implementation with per-item time-to-live (TTL) value.\"\"\"\n\n    def __init__(self, maxsize, ttl, timer=time.time, missing=None,\n                 getsizeof=None):\n        Cache.__init__(self, maxsize, missing, getsizeof)\n        self.__root = root = _Link()\n        root.prev = root.next = root\n        self.__links = collections.OrderedDict()\n        self.__timer = _Timer(timer)\n        self.__ttl = ttl\n\n    def __contains__(self, key):\n        try:\n            link = self.__links[key]  # no reordering\n        except KeyError:\n            return False\n        else:\n            return not (link.expire < self.__timer())\n\n    def __getitem__(self, key, cache_getitem=Cache.__getitem__):\n        try:\n            link = self.__getlink(key)\n        except KeyError:\n            expired = False\n        else:\n            expired = link.expire < self.__timer()\n        if expired:\n            return self.__missing__(key)\n        else:\n            return cache_getitem(self, key)\n\n    def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):\n        with self.__timer as time:\n            self.expire(time)\n            cache_setitem(self, key, value)\n        try:\n            link = self.__getlink(key)\n        except KeyError:\n            self.__links[key] = link = _Link(key)\n        else:\n            link.unlink()\n        link.expire = time + self.__ttl\n        link.next = root = self.__root\n        link.prev = prev = root.prev\n        prev.next = root.prev = link\n\n    def __delitem__(self, key, cache_delitem=Cache.__delitem__):\n        cache_delitem(self, key)\n        link = self.__links.pop(key)\n        link.unlink()\n        if link.expire < self.__timer():\n            raise KeyError(key)\n\n    def __iter__(self):\n        root = self.__root\n        curr = root.next\n        while curr is not root:\n            # \"freeze\" time for iterator access\n            with self.__timer as time:\n                if not (curr.expire < time):\n                    yield curr.key\n            curr = curr.next\n\n    def __len__(self):\n        root = self.__root\n        curr = root.next\n        time = self.__timer()\n        count = len(self.__links)\n        while curr is not root and curr.expire < time:\n            count -= 1\n            curr = curr.next\n        return count\n\n    def __setstate__(self, state):\n        self.__dict__.update(state)\n        root = self.__root\n        root.prev = root.next = root\n        for link in sorted(self.__links.values(), key=lambda obj: obj.expire):\n            link.next = root\n            link.prev = prev = root.prev\n            prev.next = root.prev = link\n        self.expire(self.__timer())\n\n    def __repr__(self, cache_repr=Cache.__repr__):\n        with self.__timer as time:\n            self.expire(time)\n            return cache_repr(self)\n\n    @property\n    def currsize(self):\n        with self.__timer as time:\n            self.expire(time)\n            return super(TTLCache, self).currsize\n\n    @property\n    def timer(self):\n        \"\"\"The timer function used by the cache.\"\"\"\n        return self.__timer\n\n    @property\n    def ttl(self):\n        \"\"\"The time-to-live value of the cache's items.\"\"\"\n        return self.__ttl\n\n    def expire(self, time=None):\n        \"\"\"Remove expired items from the cache.\"\"\"\n        if time is None:\n            time = self.__timer()\n        root = self.__root\n        curr = root.next\n        links = self.__links\n        cache_delitem = Cache.__delitem__\n        while curr is not root and curr.expire < time:\n            cache_delitem(self, curr.key)\n            del links[curr.key]\n            next = curr.next\n            curr.unlink()\n            curr = next\n\n    def clear(self):\n        with self.__timer as time:\n            self.expire(time)\n            Cache.clear(self)\n\n    def get(self, *args, **kwargs):\n        with self.__timer:\n            return Cache.get(self, *args, **kwargs)\n\n    def pop(self, *args, **kwargs):\n        with self.__timer:\n            return Cache.pop(self, *args, **kwargs)\n\n    def setdefault(self, *args, **kwargs):\n        with self.__timer:\n            return Cache.setdefault(self, *args, **kwargs)\n\n    def popitem(self):\n        \"\"\"Remove and return the `(key, value)` pair least recently used that\n        has not already expired.\n\n        \"\"\"\n        with self.__timer as time:\n            self.expire(time)\n            try:\n                key = next(iter(self.__links))\n            except StopIteration:\n                raise KeyError('%s is empty' % self.__class__.__name__)\n            else:\n                return (key, self.pop(key))\n\n    if hasattr(collections.OrderedDict, 'move_to_end'):\n        def __getlink(self, key):\n            value = self.__links[key]\n            self.__links.move_to_end(key)\n            return value\n    else:\n        def __getlink(self, key):\n            value = self.__links.pop(key)\n            self.__links[key] = value\n            return value\n\n\n#############################################\n######  END IMPORT OF CACHING LIBRARY  ######\n#############################################\n\ncache = TTLCache(\n    100, # Up to 100 items\n    5 * 60 # 5 minute cache life\n)\nuserCache = TTLCache(\n    2, # Up to 2 items\n    60 # 1 minute cache life\n)\n\nclass UnknownUserException(Exception):\n    pass\n\ndef WAAuth(parser):\n    parser.add_argument('apollo', help='Complete Apollo URL')\n    parser.add_argument('username', help='WA Username')\n    parser.add_argument('password', help='WA Password')\n\n\ndef OrgOrGuess(parser):\n    parser.add_argument('--org_json', type=argparse.FileType(\"r\"), help='Apollo JSON output, source for common name')\n    parser.add_argument('--org_raw', help='Common Name')\n    parser.add_argument('--org_id', help='Organism ID')\n\n\ndef CnOrGuess(parser):\n    OrgOrGuess(parser)\n    parser.add_argument('--seq_fasta', type=argparse.FileType(\"r\"), help='Fasta file, IDs used as sequence sources')\n    parser.add_argument('--seq_raw', nargs='*', help='Sequence Names')\n\n\ndef GuessOrg(args, wa):\n    if args.org_json:\n        orgs = [x.get('commonName', None)\n                for x in json.load(args.org_json)]\n        orgs = [x for x in orgs if x is not None]\n        return orgs\n    elif args.org_raw:\n        org = args.org_raw.strip()\n        if len(org) > 0:\n            return [org]\n        else:\n            raise Exception(\"Organism Common Name not provided\")\n    elif args.org_id:\n        return [wa.organisms.findOrganismById(args.org_id).get('commonName', None)]\n    else:\n        raise Exception(\"Organism Common Name not provided\")\n\n\ndef GuessCn(args, wa):\n    org = GuessOrg(args, wa)\n    seqs = []\n    if args.seq_fasta:\n        # If we have a fasta, pull all rec ids from that.\n        for rec in SeqIO.parse(args.seq_fasta, 'fasta'):\n            seqs.append(rec.id)\n    elif args.seq_raw:\n        # Otherwise raw list.\n        seqs = [x.strip() for x in args.seq_raw if len(x.strip()) > 0]\n\n    return org, seqs\n\n\ndef AssertUser(user_list):\n    if len(user_list) == 0:\n        raise UnknownUserException()\n    elif len(user_list) == 1:\n        return user_list[0]\n    else:\n        raise Exception(\"Too many users!\")\n\n\ndef AssertAdmin(user):\n    if user.role == 'ADMIN':\n        return True\n    else:\n        raise Exception(\"User is not an administrator. Permission denied\")\n\n\nclass WebApolloInstance(object):\n\n    def __init__(self, url, username, password):\n        self.apollo_url = url\n        self.username = username\n        self.password = password\n\n        self.annotations = AnnotationsClient(self)\n        self.groups = GroupsClient(self)\n        self.io = IOClient(self)\n        self.organisms = OrganismsClient(self)\n        self.users = UsersClient(self)\n        self.metrics = MetricsClient(self)\n        self.bio = RemoteRecord(self)\n        self.status = StatusClient(self)\n        self.canned_comments = CannedCommentsClient(self)\n        self.canned_keys = CannedKeysClient(self)\n        self.canned_values = CannedValuesClient(self)\n\n    def __str__(self):\n        return '' % self.apollo_url\n\n    def requireUser(self, email):\n        cacheKey = 'user-list'\n        try:\n            # Get the cached value\n            data = userCache[cacheKey]\n        except KeyError:\n            # If we hit a key error above, indicating that\n            # we couldn't find the key, we'll simply re-request\n            # the data\n            data = self.users.loadUsers()\n            userCache[cacheKey] = data\n\n        return AssertUser([x for x in data if x.username == email])\n\n\nclass GroupObj(object):\n    def __init__(self, **kwargs):\n        self.name = kwargs['name']\n\n        if 'id' in kwargs:\n            self.groupId = kwargs['id']\n\n\nclass UserObj(object):\n    ROLE_USER = 'USER'\n    ROLE_ADMIN = 'ADMIN'\n\n    def __init__(self, **kwargs):\n        # Generally expect 'userId', 'firstName', 'lastName', 'username' (email)\n        for attr in kwargs.keys():\n            setattr(self, attr, kwargs[attr])\n\n        if 'groups' in kwargs:\n            groups = []\n            for groupData in kwargs['groups']:\n                groups.append(GroupObj(**groupData))\n            self.groups = groups\n\n        self.__props = kwargs.keys()\n\n    def isAdmin(self):\n        if hasattr(self, 'role'):\n            return self.role == self.ROLE_ADMIN\n        return False\n\n    def refresh(self, wa):\n        # This method requires some sleeping usually.\n        newU = wa.users.loadUser(self).toDict()\n        for prop in newU:\n            setattr(self, prop, newU[prop])\n\n    def toDict(self):\n        data = {}\n        for prop in self.__props:\n            data[prop] = getattr(self, prop)\n        return data\n\n    def __str__(self):\n        return '>' % (self.userId, self.firstName,\n                                          self.lastName, self.username)\n\n\nclass Client(object):\n\n    def __init__(self, webapolloinstance, **requestArgs):\n        self._wa = webapolloinstance\n\n        self.__verify = requestArgs.get('verify', True)\n        self._requestArgs = requestArgs\n\n        if 'verify' in self._requestArgs:\n            del self._requestArgs['verify']\n\n    def request(self, clientMethod, data, post_params={}, isJson=True):\n        url = self._wa.apollo_url + self.CLIENT_BASE + clientMethod\n\n        headers = {\n            'Content-Type': 'application/json'\n        }\n\n        data.update({\n            'username': self._wa.username,\n            'password': self._wa.password,\n        })\n\n        r = requests.post(url, data=json.dumps(data), headers=headers,\n                          verify=self.__verify, params=post_params, allow_redirects=False, **self._requestArgs)\n\n        if r.status_code == 200 or r.status_code == 302:\n            if isJson:\n                d = r.json()\n                if 'username' in d:\n                    del d['username']\n                if 'password' in d:\n                    del d['password']\n                return d\n            else:\n                return r.text\n\n        # @see self.body for HTTP response body\n        raise Exception(\"Unexpected response from apollo %s: %s\" %\n                        (r.status_code, r.text))\n\n    def get(self, clientMethod, get_params):\n        url = self._wa.apollo_url + self.CLIENT_BASE + clientMethod\n        headers = {}\n\n        r = requests.get(url, headers=headers, verify=self.__verify,\n                         params=get_params, **self._requestArgs)\n        if r.status_code == 200:\n            d = r.json()\n            if 'username' in d:\n                del d['username']\n            if 'password' in d:\n                del d['password']\n            return d\n        # @see self.body for HTTP response body\n        raise Exception(\"Unexpected response from apollo %s: %s\" %\n                        (r.status_code, r.text))\n\n\nclass MetricsClient(Client):\n    CLIENT_BASE = '/metrics/'\n\n    def getServerMetrics(self):\n        return self.get('metrics', {})\n\n\nclass AnnotationsClient(Client):\n    CLIENT_BASE = '/annotationEditor/'\n\n    def _update_data(self, data):\n        if not hasattr(self, '_extra_data'):\n            raise Exception(\"Please call setSequence first\")\n\n        data.update(self._extra_data)\n        return data\n\n    def setSequence(self, sequence, organism):\n        self._extra_data = {\n            'sequence': sequence,\n            'organism': organism,\n        }\n\n    def setDescription(self, featureDescriptions):\n        data = {\n            'features': featureDescriptions,\n        }\n        data = self._update_data(data)\n        return self.request('setDescription', data)\n\n    def setName(self, uniquename, name):\n        # TODO\n        data = {\n            'features': [\n                {\n                    'uniquename': uniquename,\n                    'name': name,\n                }\n            ],\n        }\n        data = self._update_data(data)\n        return self.request('setName', data)\n\n    def setNames(self, features):\n        # TODO\n        data = {\n            'features': features,\n        }\n        data = self._update_data(data)\n        return self.request('setName', data)\n\n    def setStatus(self, statuses):\n        # TODO\n        data = {\n            'features': statuses,\n        }\n        data = self._update_data(data)\n        return self.request('setStatus', data)\n\n    def setSymbol(self, symbols):\n        data = {\n            'features': symbols,\n        }\n        data.update(self._extra_data)\n        return self.request('setSymbol', data)\n\n    def getComments(self, feature_id):\n        data = {\n            'features': [{'uniquename': feature_id}],\n        }\n        data = self._update_data(data)\n        return self.request('getComments', data)\n\n    def addComments(self, feature_id, comment):\n        #TODO: This is probably not great and will delete comments, if I had to guess...\n        data = {\n            'features': [\n                {\n                    'uniquename': feature_id,\n                    'comments': [comment]\n                }\n            ],\n        }\n        data = self._update_data(data)\n        return self.request('getComments', data)\n\n    def addAttribute(self, features):\n        data = {\n            'features': features,\n        }\n        data = self._update_data(data)\n        return self.request('addAttribute', data)\n\n    def getFeatures(self):\n        data = self._update_data({})\n        return self.request('getFeatures', data)\n\n    def getSequence(self, uniquename):\n        data = {\n            'features': [\n                {'uniquename': uniquename}\n            ]\n        }\n        data = self._update_data(data)\n        return self.request('getSequence', data)\n\n    def addFeature(self, feature, trustme=False):\n        if not trustme:\n            raise NotImplementedError(\"Waiting on better docs from project. If you know what you are doing, pass trustme=True to this function.\")\n\n        data = {\n            'features': feature,\n        }\n        data = self._update_data(data)\n        return self.request('addFeature', data)\n\n    def addTranscript(self, transcript, trustme=False):\n        if not trustme:\n            raise NotImplementedError(\"Waiting on better docs from project. If you know what you are doing, pass trustme=True to this function.\")\n\n        data = {}\n        data.update(transcript)\n        data = self._update_data(data)\n        return self.request('addTranscript', data)\n\n    # addExon, add/delete/updateComments, addTranscript skipped due to docs\n\n    def duplicateTranscript(self, transcriptId):\n        data = {\n            'features': [{'uniquename': transcriptId}]\n        }\n\n        data = self._update_data(data)\n        return self.request('duplicateTranscript', data)\n\n    def setTranslationStart(self, uniquename, start):\n        data = {\n            'features': [{\n                'uniquename': uniquename,\n                'location': {\n                    'fmin': start\n                }\n            }]\n        }\n        data = self._update_data(data)\n        return self.request('setTranslationStart', data)\n\n    def setTranslationEnd(self, uniquename, end):\n        data = {\n            'features': [{\n                'uniquename': uniquename,\n                'location': {\n                    'fmax': end\n                }\n            }]\n        }\n        data = self._update_data(data)\n        return self.request('setTranslationEnd', data)\n\n    def setLongestOrf(self, uniquename):\n        data = {\n            'features': [{\n                'uniquename': uniquename,\n            }]\n        }\n        data = self._update_data(data)\n        return self.request('setLongestOrf', data)\n\n    def setBoundaries(self, uniquename, start, end):\n        data = {\n            'features': [{\n                'uniquename': uniquename,\n                'location': {\n                    'fmin': start,\n                    'fmax': end,\n                }\n            }]\n        }\n        data = self._update_data(data)\n        return self.request('setBoundaries', data)\n\n    def getSequenceAlterations(self):\n        data = {\n        }\n        data = self._update_data(data)\n        return self.request('getSequenceAlterations', data)\n\n    def setReadthroughStopCodon(self, uniquename):\n        data = {\n            'features': [{\n                'uniquename': uniquename,\n            }]\n        }\n        data = self._update_data(data)\n        return self.request('setReadthroughStopCodon', data)\n\n    def deleteSequenceAlteration(self, uniquename):\n        data = {\n            'features': [{\n                'uniquename': uniquename,\n            }]\n        }\n        data = self._update_data(data)\n        return self.request('deleteSequenceAlteration', data)\n\n    def flipStrand(self, uniquenames):\n        data = {\n            'features': [\n                {'uniquename': x} for x in uniquenames\n            ]\n        }\n        data = self._update_data(data)\n        return self.request('flipStrand', data)\n\n    def mergeExons(self, exonA, exonB):\n        data = {\n            'features': [\n                {'uniquename': exonA},\n                {'uniquename': exonB},\n            ]\n        }\n        data = self._update_data(data)\n        return self.request('mergeExons', data)\n\n    # def splitExon(): pass\n\n    def deleteFeatures(self, uniquenames):\n        assert isinstance(uniquenames, collections.Iterable)\n        data = {\n            'features': [\n                {'uniquename': x} for x in uniquenames\n            ]\n        }\n        data = self._update_data(data)\n        return self.request('deleteFeature', data)\n\n    # def deleteExon(): pass\n\n    # def makeIntron(self, uniquename, ): pass\n\n    def getSequenceSearchTools(self):\n        return self.get('getSequenceSearchTools', {})\n\n    def getCannedComments(self):\n        return self.get('getCannedComments', {})\n\n    def searchSequence(self, searchTool, sequence, database):\n        data = {\n            'key': searchTool,\n            'residues': sequence,\n            'database_id': database,\n        }\n        return self.request('searchSequences', data)\n\n    def getGff3(self, uniquenames):\n        assert isinstance(uniquenames, collections.Iterable)\n        data = {\n            'features': [\n                {'uniquename': x} for x in uniquenames\n            ]\n        }\n        data = self._update_data(data)\n        return self.request('getGff3', data, isJson=False)\n\n\nclass GroupsClient(Client):\n    CLIENT_BASE = '/group/'\n\n    def createGroup(self, name):\n        data = {'name': name}\n        return self.request('createGroup', data)\n\n    def getOrganismPermissionsForGroup(self, group):\n        data = {\n            'id': group.groupId,\n            'name': group.name,\n        }\n        return self.request('getOrganismPermissionsForGroup', data)\n\n    def loadGroup(self, group):\n        return self.loadGroupById(group.groupId)\n\n    def loadGroupById(self, groupId):\n        res = self.request('loadGroups', {'groupId': groupId})\n        if isinstance(res, list):\n            # We can only match one, right?\n            return GroupObj(**res[0])\n        else:\n            return res\n\n    def loadGroupByName(self, name):\n        res = self.request('loadGroups', {'name': name})\n        if isinstance(res, list):\n            # We can only match one, right?\n            return GroupObj(**res[0])\n        else:\n            return res\n\n    def loadGroups(self, group=None):\n        res = self.request('loadGroups', {})\n        data = [GroupObj(**x) for x in res]\n        if group is not None:\n            data = [x for x in data if x.name == group]\n\n        return data\n\n    def deleteGroup(self, group):\n        data = {\n            'id': group.groupId,\n            'name': group.name,\n        }\n        return self.request('deleteGroup', data)\n\n    def updateGroup(self, group, newName):\n        # TODO: Sure would be nice if modifying ``group.name`` would invoke\n        # this?\n        data = {\n            'id': group.groupId,\n            'name': newName,\n        }\n        return self.request('updateGroup', data)\n\n    def updateOrganismPermission(self, group, organismName,\n                                 administrate=False, write=False, read=False,\n                                 export=False):\n        data = {\n            'groupId': group.groupId,\n            'organism': organismName,\n            'ADMINISTRATE': administrate,\n            'WRITE': write,\n            'EXPORT': export,\n            'READ': read,\n        }\n        return self.request('updateOrganismPermission', data)\n\n    def updateMembership(self, group, users):\n        data = {\n            'groupId': group.groupId,\n            'user': [user.email for user in users]\n        }\n        return self.request('updateMembership', data)\n\n\nclass IOClient(Client):\n    CLIENT_BASE = '/IOService/'\n\n    def write(self, exportType='FASTA', seqType='peptide',\n              exportFormat='text', sequences=None, organism=None,\n              output='text', exportAllSequences=False,\n              exportGff3Fasta=False):\n        if exportType not in ('FASTA', 'GFF3'):\n            raise Exception(\"exportType must be one of FASTA, GFF3\")\n\n        if seqType not in ('peptide', 'cds', 'cdna', 'genomic'):\n            raise Exception(\"seqType must be one of peptide, cds, dna, genomic\")\n\n        if exportFormat not in ('gzip', 'text'):\n            raise Exception(\"exportFormat must be one of gzip, text\")\n\n        if output not in ('file', 'text'):\n            raise Exception(\"output must be one of file, text\")\n\n        data = {\n            'type': exportType,\n            'seqType': seqType,\n            'format': exportFormat,\n            'sequences': sequences,\n            'organism': organism,\n            'output': output,\n            'exportAllSequences': exportAllSequences,\n            'exportGff3Fasta': exportGff3Fasta,\n        }\n\n        return self.request('write', data, isJson=output == 'file')\n\n    def download(self, uuid, outputFormat='gzip'):\n\n        if outputFormat.lower() not in ('gzip', 'text'):\n            raise Exception(\"outputFormat must be one of file, text\")\n\n        data = {\n            'format': outputFormat,\n            'uuid': uuid,\n        }\n        return self.request('write', data)\n\n\nclass StatusClient(Client):\n    CLIENT_BASE = '/availableStatus/'\n\n    def addStatus(self, value):\n        data = {\n            'value': value\n        }\n\n        return self.request('createStatus', data)\n\n    def findAllStatuses(self):\n        return self.request('showStatus', {})\n\n    def findStatusByValue(self, value):\n        statuses = self.findAllStatuses()\n        statuses = [x for x in statuses if x['value'] == value]\n        if len(statuses) == 0:\n            raise Exception(\"Unknown status value\")\n        else:\n            return statuses[0]\n\n    def findStatusById(self, id_number):\n        statuses = self.findAllStatuses()\n        statuses = [x for x in statuses if str(x['id']) == str(id_number)]\n        if len(statuses) == 0:\n            raise Exception(\"Unknown ID\")\n        else:\n            return statuses[0]\n\n    def updateStatus(self, id_number, new_value):\n        data = {\n            'id': id_number,\n            'new_value': new_value\n        }\n\n        return self.request('updateStatus', data)\n\n    def deleteStatus(self, id_number):\n        data = {\n            'id': id_number\n        }\n\n        return self.request('deleteStatus', data)\n\n\nclass CannedCommentsClient(Client):\n    CLIENT_BASE = '/cannedComment/'\n\n    def addComment(self, comment, metadata=\"\"):\n        data = {\n            'comment': comment,\n            'metadata': metadata\n        }\n\n        return self.request('createComment', data)\n\n    def findAllComments(self):\n        return self.request('showComment', {})\n\n    def findCommentByValue(self, value):\n        comments = self.findAllComments()\n        comments = [x for x in comments if x['comment'] == value]\n        if len(comments) == 0:\n            raise Exception(\"Unknown comment\")\n        else:\n            return comments[0]\n\n    def findCommentById(self, id_number):\n        comments = self.findAllComments()\n        comments = [x for x in comments if str(x['id']) == str(id_number)]\n        if len(comments) == 0:\n            raise Exception(\"Unknown ID\")\n        else:\n            return comments[0]\n\n    def updateComment(self, id_number, new_value, metadata=None):\n        data = {\n            'id': id_number,\n            'new_comment': new_value\n        }\n\n        if metadata is not None:\n            data['metadata'] = metadata\n\n        return self.request('updateComment', data)\n\n    def deleteComment(self, id_number):\n        data = {\n            'id': id_number\n        }\n\n        return self.request('deleteComment', data)\n\n\nclass CannedKeysClient(Client):\n    CLIENT_BASE = '/cannedKey/'\n\n    def addKey(self, key, metadata=\"\"):\n        data = {\n            'key': key,\n            'metadata': metadata\n        }\n\n        return self.request('createKey', data)\n\n    def findAllKeys(self):\n        return self.request('showKey', {})\n\n    def findKeyByValue(self, value):\n        keys = self.findAllKeys()\n        keys = [x for x in keys if x['label'] == value]\n        if len(keys) == 0:\n            raise Exception(\"Unknown key\")\n        else:\n            return keys[0]\n\n    def findKeyById(self, id_number):\n        keys = self.findAllKeys()\n        keys = [x for x in keys if str(x['id']) == str(id_number)]\n        if len(keys) == 0:\n            raise Exception(\"Unknown ID\")\n        else:\n            return keys[0]\n\n    def updateKey(self, id_number, new_key, metadata=None):\n        data = {\n            'id': id_number,\n            'new_key': new_key\n        }\n\n        if metadata is not None:\n            data['metadata'] = metadata\n\n        return self.request('updateKey', data)\n\n    def deleteKey(self, id_number):\n        data = {\n            'id': id_number\n        }\n\n        return self.request('deleteKey', data)\n\n\nclass CannedValuesClient(Client):\n    CLIENT_BASE = '/cannedValue/'\n\n    def addValue(self, value, metadata=\"\"):\n        data = {\n            'value': value,\n            'metadata': metadata\n        }\n\n        return self.request('createValue', data)\n\n    def findAllValues(self):\n        return self.request('showValue', {})\n\n    def findValueByValue(self, value):\n        values = self.findAllValues()\n        values = [x for x in values if x['label'] == value]\n        if len(values) == 0:\n            raise Exception(\"Unknown value\")\n        else:\n            return values[0]\n\n    def findValueById(self, id_number):\n        values = self.findAllValues()\n        values = [x for x in values if str(x['id']) == str(id_number)]\n        if len(values) == 0:\n            raise Exception(\"Unknown ID\")\n        else:\n            return values[0]\n\n    def updateValue(self, id_number, new_value, metadata=None):\n        data = {\n            'id': id_number,\n            'new_value': new_value\n        }\n\n        if metadata is not None:\n            data['metadata'] = metadata\n\n        return self.request('updateValue', data)\n\n    def deleteValue(self, id_number):\n        data = {\n            'id': id_number\n        }\n\n        return self.request('deleteValue', data)\n\n\nclass OrganismsClient(Client):\n    CLIENT_BASE = '/organism/'\n\n    def addOrganism(self, commonName, directory, blatdb=None, species=None,\n                    genus=None, public=False):\n        data = {\n            'commonName': commonName,\n            'directory': directory,\n            'publicMode': public,\n        }\n\n        if blatdb is not None:\n            data['blatdb'] = blatdb\n        if genus is not None:\n            data['genus'] = genus\n        if species is not None:\n            data['species'] = species\n\n        return self.request('addOrganism', data)\n\n    def findAllOrganisms(self):\n        return self.request('findAllOrganisms', {})\n\n    def findOrganismByCn(self, cn):\n        orgs = self.findAllOrganisms()\n        orgs = [x for x in orgs if x['commonName'] == cn]\n        if len(orgs) == 0:\n            raise Exception(\"Unknown common name\")\n        else:\n            return orgs[0]\n\n    def findOrganismById(self, id_number):\n        orgs = self.findAllOrganisms()\n        orgs = [x for x in orgs if str(x['id']) == str(id_number)]\n        if len(orgs) == 0:\n            raise Exception(\"Unknown ID\")\n        else:\n            return orgs[0]\n\n    def deleteOrganism(self, organismId):\n        return self.request('deleteOrganism', {'id': organismId})\n\n    def deleteOrganismFeatures(self, organismId):\n        return self.request('deleteOrganismFeatures', {'id': organismId})\n\n    def getSequencesForOrganism(self, commonName):\n        return self.request('getSequencesForOrganism', {'organism': commonName})\n\n    def updateOrganismInfo(self, organismId, commonName, directory, blatdb=None, species=None, genus=None, public=False):\n        data = {\n            'id': organismId,\n            'name': commonName,\n            'directory': directory,\n            'publicMode': public,\n        }\n\n        if blatdb is not None:\n            data['blatdb'] = blatdb\n        if genus is not None:\n            data['genus'] = genus\n        if species is not None:\n            data['species'] = species\n\n        return self.request('updateOrganismInfo', data)\n\n\nclass UsersClient(Client):\n    CLIENT_BASE = '/user/'\n\n    # Real one\n    # def getOrganismPermissionsForUser(self, user):\n    # data = {\n    # 'userId': user.userId,\n    # }\n    # return self.request('getOrganismPermissionsForUser', data)\n\n    # Utter frigging hack\n    def getOrganismPermissionsForUser(self, user):\n        return self.loadUser(user).organismPermissions\n\n    def updateOrganismPermission(self, user, organism, administrate=False,\n                                 write=False, export=False, read=False):\n        data = {\n            'userId': user.userId,\n            'organism': organism,\n            'ADMINISTRATE': administrate,\n            'WRITE': write,\n            'EXPORT': export,\n            'READ': read,\n        }\n        return self.request('updateOrganismPermission', data)\n\n    def loadUser(self, user):\n        return self.loadUserById(user.userId)\n\n    def loadUserById(self, userId):\n        res = self.request('loadUsers', {'userId': userId})\n        if isinstance(res, list):\n            # We can only match one, right?\n            return UserObj(**res[0])\n        else:\n            return res\n\n    def loadUsers(self, email=None):\n        res = self.request('loadUsers', {})\n        data = [UserObj(**x) for x in res]\n        if email is not None:\n            data = [x for x in data if x.username == email]\n\n        return data\n\n    def addUserToGroup(self, group, user):\n        data = {'group': group.name, 'userId': user.userId}\n        return self.request('addUserToGroup', data)\n\n    def removeUserFromGroup(self, group, user):\n        data = {'group': group.name, 'userId': user.userId}\n        return self.request('removeUserFromGroup', data)\n\n    def createUser(self, email, firstName, lastName, newPassword, role=\"user\", groups=None):\n        data = {\n            'firstName': firstName,\n            'lastName': lastName,\n            'email': email,\n            'role': role,\n            'groups': [] if groups is None else groups,\n            # 'availableGroups': [],\n            'newPassword': newPassword,\n            # 'organismPermissions': [],\n        }\n        return self.request('createUser', data)\n\n    def deleteUser(self, user):\n        return self.request('deleteUser', {'userId': user.userId})\n\n    def updateUser(self, user, email, firstName, lastName, newPassword):\n        data = {\n            'userId': user.userId,\n            'email': email,\n            'firstName': firstName,\n            'lastName': lastName,\n            'newPassword': newPassword,\n        }\n        return self.request('updateUser', data)\n\n\nclass RemoteRecord(Client):\n    CLIENT_BASE = None\n\n    def ParseRecord(self, cn):\n        org = self._wa.organisms.findOrganismByCn(cn)\n        self._wa.annotations.setSequence(org['commonName'], org['id'])\n\n        data = io.StringIO(self._wa.io.write(\n            exportType='GFF3',\n            seqType='genomic',\n            exportAllSequences=False,\n            exportGff3Fasta=True,\n            output=\"text\",\n            exportFormat=\"text\",\n            sequences=cn,\n        ))\n        data.seek(0)\n\n        for record in GFF.parse(data):\n            yield WebApolloSeqRecord(record, self._wa)\n\n\nclass WebApolloSeqRecord(object):\n    def __init__(self, sr, wa):\n        self._sr = sr\n        self._wa = wa\n\n    def __dir__(self):\n        return dir(self._sr)\n\n    def __getattr__(self, key):\n        if key in ('_sr', '_wa'):\n            return self.__dict__[key]\n        else:\n            if key == 'features':\n                return (WebApolloSeqFeature(x, self._wa)\n                        for x in self._sr.__dict__[key])\n            else:\n                return self._sr.__dict__[key]\n\n    def __setattr__(self, key, value):\n        if key in ('_sd', '_wa'):\n            self.__dict__[key] = value\n        else:\n            self._sr.__dict__[key] = value\n            # Methods acting on the SeqRecord object\n\n\nclass WebApolloSeqFeature(object):\n    def __init__(self, sf, wa):\n        self._sf = sf\n        self._wa = wa\n\n    def __dir__(self):\n        return dir(self._sf)\n\n    def __getattr__(self, key):\n        if key in ('_sf', '_wa'):\n            return self.__dict__[key]\n        else:\n            return self._sf.__dict__[key]\n\n    def __setattr__(self, key, value):\n        if key in ('_sf', '_wa'):\n            self.__dict__[key] = value\n        else:\n            # Methods acting on the SeqFeature object\n            if key == 'location':\n                if value.strand != self._sf.location.strand:\n                    self.wa.annotations.flipStrand(\n                        self._sf.qualifiers['ID'][0]\n                    )\n\n                self.wa.annotations.setBoundaries(\n                    self._sf.qualifiers['ID'][0],\n                    value.start,\n                    value.end,\n                )\n\n                self._sf.__dict__[key] = value\n            else:\n                self._sf.__dict__[key] = value\n\n\ndef _tnType(feature):\n    if feature.type in ('gene', 'mRNA', 'exon', 'CDS'):\n        return feature.type\n    else:\n        return 'exon'\n\n\ndef _yieldFeatData(features):\n    for f in features:\n        current = {\n            'location': {\n                'strand': f.strand,\n                'fmin': int(f.location.start),\n                'fmax': int(f.location.end),\n            },\n            'type': {\n                'name': _tnType(f),\n                'cv': {\n                    'name': 'sequence',\n                }\n            },\n        }\n        if f.type in ('gene', 'mRNA'):\n            current['name'] = f.qualifiers.get('Name', [f.id])[0]\n        if hasattr(f, 'sub_features') and len(f.sub_features) > 0:\n            current['children'] = [x for x in _yieldFeatData(f.sub_features)]\n\n        yield current\n\n\ndef featuresToFeatureSchema(features):\n    compiled = []\n    for feature in features:\n        # if feature.type != 'gene':\n            # log.warn(\"Not able to handle %s features just yet...\", feature.type)\n            # continue\n\n        for x in _yieldFeatData([feature]):\n            compiled.append(x)\n    return compiled\n\n\ndef accessible_organisms(user, orgs):\n    permissionMap = {\n        x['organism']: x['permissions']\n        for x in user.organismPermissions\n        if 'WRITE' in x['permissions'] or\n        'READ' in x['permissions'] or\n        'ADMINISTRATE' in x['permissions'] or\n        user.role == 'ADMIN'\n    }\n\n    if 'error' in orgs:\n        raise Exception(\"Error received from Apollo server: \\\"%s\\\"\" % orgs['error'])\n\n    return [\n        (org['commonName'], org['id'], False)\n        for org in sorted(orgs, key=lambda x: x['commonName'])\n        if org['commonName'] in permissionMap\n    ]\n\n\ndef galaxy_list_groups(trans, *args, **kwargs):\n    email = trans.get_user().email\n    wa = WebApolloInstance(\n        os.environ['GALAXY_WEBAPOLLO_URL'],\n        os.environ['GALAXY_WEBAPOLLO_USER'],\n        os.environ['GALAXY_WEBAPOLLO_PASSWORD']\n    )\n    # Assert that the email exists in apollo\n    try:\n        gx_user = wa.requireUser(email)\n    except UnknownUserException:\n        return []\n\n    # Key for cached data\n    cacheKey = 'groups-' + email\n    # We don't want to trust \"if key in cache\" because between asking and fetch\n    # it might through key error.\n    if cacheKey not in cache:\n        # However if it ISN'T there, we know we're safe to fetch + put in\n        # there.\n        data = _galaxy_list_groups(wa, gx_user, *args, **kwargs)\n        cache[cacheKey] = data\n        return data\n    try:\n        # The cache key may or may not be in the cache at this point, it\n        # /likely/ is. However we take no chances that it wasn't evicted between\n        # when we checked above and now, so we reference the object from the\n        # cache in preparation to return.\n        data = cache[cacheKey]\n        return data\n    except KeyError:\n        # If access fails due to eviction, we will fail over and can ensure that\n        # data is inserted.\n        data = _galaxy_list_groups(wa, gx_user, *args, **kwargs)\n        cache[cacheKey] = data\n        return data\n\n\ndef _galaxy_list_groups(wa, gx_user, *args, **kwargs):\n    # Fetch the groups.\n    group_data = []\n    for group in wa.groups.loadGroups():\n        # Reformat\n        group_data.append((group.name, group.groupId, False))\n    return group_data\n\n\ndef galaxy_list_orgs(trans, *args, **kwargs):\n    email = trans.get_user().email\n    wa = WebApolloInstance(\n        os.environ['GALAXY_WEBAPOLLO_URL'],\n        os.environ['GALAXY_WEBAPOLLO_USER'],\n        os.environ['GALAXY_WEBAPOLLO_PASSWORD']\n    )\n    try:\n        gx_user = wa.requireUser(email)\n    except UnknownUserException:\n        return []\n\n    # Key for cached data\n    cacheKey = 'orgs-' + email\n    if cacheKey not in cache:\n        data = _galaxy_list_orgs(wa, gx_user, *args, **kwargs)\n        cache[cacheKey] = data\n        return data\n    try:\n        data = cache[cacheKey]\n        return data\n    except KeyError:\n        data = _galaxy_list_orgs(wa, gx_user, *args, **kwargs)\n        cache[cacheKey] = data\n        return data\n\n\ndef _galaxy_list_orgs(wa, gx_user, *args, **kwargs):\n    # Fetch all organisms\n    all_orgs = wa.organisms.findAllOrganisms()\n    # Figure out which are accessible to the user\n    orgs = accessible_organisms(gx_user, all_orgs)\n    # Return org list\n    return orgs\n\n## This is all for implementing the command line interface for testing.\n\nclass obj(object):\n    pass\n\n\nclass fakeTrans(object):\n\n    def __init__(self, username):\n        self.un = username\n\n    def get_user(self):\n        o = obj()\n        o.email = self.un\n        return o\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(description='Test access to apollo server')\n    parser.add_argument('email', help='Email of user to test')\n    parser.add_argument('--action', choices=['org', 'group'], default='org', help='Data set to test, fetch a list of groups or users known to the requesting user.')\n    args = parser.parse_args()\n\n    trans = fakeTrans(args.email)\n    if args.action == 'org':\n        for f in galaxy_list_orgs(trans):\n            print(f)\n    else:\n        for f in galaxy_list_groups(trans):\n            print(f)\n","sub_path":"webapollo.py","file_name":"webapollo.py","file_ext":"py","file_size_in_byte":45767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"312697997","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu August 10 23:52:55 2022\n\n@author: jmmauricio\n\"\"\"\n\nimport numpy as np\nimport sympy as sym\n\n\ndef leon_gvsg(grid,name,bus_name,data_dict):\n    \"\"\"\n \n    \"\"\"\n\n    sin = sym.sin\n    cos = sym.cos\n    buses = grid.data['buses']\n    buses_list = [bus['name'] for bus in buses]                  \n    bus_name = vsg_data['bus']\n    name = bus_name\n\n    idx_bus = buses_list.index(bus_name) # get the number of the bus where the syn is connected\n    if not 'idx_powers' in buses[idx_bus]: buses[idx_bus].update({'idx_powers':0})\n    buses[idx_bus]['idx_powers'] += 1\n\n    # inputs:\n    p_ref,q_ref = sym.symbols(f'p_ref_{name},q_ref_{name}', real=True)\n\n    # dynamical states:\n    delta,x_v,x_w,xi_q = sym.symbols(f'delta_{name},x_v_{name},x_w_{name},xi_q_{name}', real=True)\n    \n    # algebraic states:\n    i_d_ref,i_q_ref,p,q,e_qv = sym.symbols(f'i_d_ref_{name},i_q_ref_{name},p_{name},q_{name},e_qv_{name}', real=True)\n\n    # params:\n    S_base = sym.Symbol('S_base', real = True) # S_base = global power base, S_n = machine power base\n    S_n,F_n,K_delta = sym.symbols(f'S_n_{name},F_n_{name},K_delta_{name}', real=True)\n    F,T_d,K,H,D_s = sym.symbols(f'F_{name},T_d_{name},K_{name},H_{name},D_s_{name}', real=True)\n    R_v,X_v = sym.symbols(f'R_v_{name},X_v_{name}', real=True)\n    K_q,T_q = sym.symbols(f'K_q_{name},T_q_{name}', real=True)\n    params_list = ['S_n','F_n','K_delta','F','T_d','K','H','D_s','R_v','X_v','K_q','T_q']\n\n    # auxiliar variables and constants\n    omega_coi = sym.Symbol(\"omega_coi\", real=True) # from global system\n    V = sym.Symbol(f\"V_{bus_name}\", real=True) # from global system\n    theta = sym.Symbol(f\"theta_{bus_name}\", real=True) # from global system\n    i_d = sym.Symbol(f\"i_d_{name}\", real=True)\n    i_q = sym.Symbol(f\"i_q_{name}\", real=True)\n\n    # auxiliar equations\n    Omega_b = 2*np.pi*F_n\n    omega_s = omega_coi\n    v_D = V*sin(theta)  # e^(-j)\n    v_Q = V*cos(theta) \n    v_d = v_D * cos(delta) - v_Q * sin(delta)   \n    v_q = v_D * sin(delta) + v_Q * cos(delta)\n\n    Domega = (x_v + F*(p_ref - p))/K\n    e_dv = 0.0\n    epsilon_q = q_ref - q\n    i_d = i_d_ref\n    i_q = i_q_ref\n    omega_v = Domega + 1.0\n\n    # dynamical equations\n    ddelta   = Omega_b*(omega_v - omega_s) - K_delta*delta\n    dx_v = p_ref - p - D_s*Domega\n    dx_w = x_v + T_d*(p_ref - p) - 2*H*Domega\n    dxi_q = epsilon_q # PI agregado\n\n    # algebraic equations\n    g_i_d_ref  = e_dv - R_v * i_d_ref - X_v * i_q_ref - v_d \n    g_i_q_ref  = e_qv - R_v * i_q_ref + X_v * i_d_ref - v_q \n    g_p  = v_d*i_d + v_q*i_q - p  \n    g_q  = v_d*i_q - v_q*i_d - q \n    g_e_qv = -e_qv +  K_q*(epsilon_q + xi_q/T_q) + 1.0\n    \n    # DAE system update\n    grid.dae['f'] += [ddelta,dx_v,dx_w,dxi_q]\n    grid.dae['x'] += [ delta, x_v, x_w, xi_q]\n    grid.dae['g'] +=     [g_i_d_ref,g_i_q_ref,g_p,g_q,g_e_qv]\n    grid.dae['y_ini'] += [  i_d_ref,  i_q_ref,  p,  q,  e_qv]\n    grid.dae['y_run'] += [  i_d_ref,  i_q_ref,  p,  q,  e_qv]\n            \n    # default inputs\n    grid.dae['u_ini_dict'].update({f'p_ref_{name}':0.0})\n    grid.dae['u_ini_dict'].update({f'q_ref_{name}':0.0})\n    grid.dae['u_run_dict'].update({f'p_ref_{name}':0.0})\n    grid.dae['u_run_dict'].update({f'q_ref_{name}':0.0})\n\n\n    # default parameters\n    for item in params_list:\n        grid.dae['params_dict'].update({item + f'_{name}':data_dict[item]})\n\n\n    # add speed*H term to global for COI speed computing\n    grid.H_total += H\n    grid.omega_coi_numerator += omega_v*H*S_n\n    grid.omega_coi_denominator += H*S_n\n\n    # DAE outputs update\n    grid.dae['h_dict'].update({f\"omega_v_{bus_name}\":omega_v})\n\n\n    p_W   = p * S_n\n    q_var = q * S_n\n\n    return p_W,q_var\n\n","sub_path":"src/pydae/bmapu/vsgs/leon_gvsg.py","file_name":"leon_gvsg.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"568179234","text":"\"\"\"\nExtract 3d coordinates fte that the format of text should be something like this:\n====================\n20 (point index)\nDeltaX (x coordinate)\nDeltaY (y coordinate)\nDeltaZ (z coordinate)rom .txt file and save as a numpy array.\nNo\n\n\"\"\"\nimport numpy as np\nfile = open('C:\\\\Users\\\\Xu Yang\\\\Desktop\\\\3Dcoordinates.txt')\ncontents = file.readlines()\nnumofFeatures = 103\ncoordinates = np.zeros((numofFeatures, 3))\nfor i in range(len(contents)):\n    if contents[i][0] == '=':\n        ptIndex = int(contents[i+1])\n        x = float(contents[i+2][9:-4])\n        y = float(contents[i+3][9:-4])\n        z = float(contents[i+4][9:-4])\n        coordinates[ptIndex, :] = x, y, z\nfile.close()\n\n","sub_path":"extract3Dcoordinates.py","file_name":"extract3Dcoordinates.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"346984753","text":"# Code \t\t\t\tcoding: UTF-8\n# FileName\t\t\tSyncToAssets.py  \n# Desciption\t    同步资源文件至Assets目录\n\nimport sys,os.path,os,stat,re,subprocess\n\ndef getFileList(path):\n    if os.path.exists(path):\n        filelist = []\n        for name in os.listdir(path):\n            fullname = os.path.join(path, name)\n            st = os.lstat(fullname)\n            appendName = fullname.replace(\"\\\\\", '/')\n            if stat.S_ISDIR(st.st_mode):\n                # print(\"filePath --> \" + fullname)\n                filelist += getFileList(fullname)\n            elif os.path.isfile(fullname):\n                filelist.append(appendName)\n            else:\n                pass\n        return filelist\n    else:\n        return []                \n\ndef getDirs(path):\n    dirlist=[]\n    for f in os.listdir(path):\n        fullname = os.path.join(path, f)\n        st = os.lstat(fullname)\n        if stat.S_ISDIR(st.st_mode):   \n            appendName = fullname.replace(\"\\\\\", '/')\n            dirlist.append(appendName)\n    return dirlist\n\ndef copyFiles(sourceDir,  targetDir): \n    if sourceDir.find(\".svn\") > 0: \n        return\n    for file in os.listdir(sourceDir): \n        sourceFile = os.path.join(sourceDir,  file) \n        targetFile = os.path.join(targetDir,  file) \n        #print(\"\\n\"+sourceFile)\n        if os.path.isfile(sourceFile): \n            if not os.path.exists(targetDir):  \n                os.makedirs(targetDir)  \n            if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):  \n                print(\"Copy file : ----> \"+sourceFile)\n                sourceFileOepn = open(sourceFile, \"rb\")\n                targetFileOpen = open(targetFile, \"wb\")\n                targetFileOpen.write(sourceFileOepn.read())\n                sourceFileOepn.close()\n                targetFileOpen.close()\n        if os.path.isdir(sourceFile): \n            copyFiles(sourceFile, targetFile) \n\ndef excuteCommandAndReturnErrcode():\n    #1.打包UI资源   \n    uiResZipCommand = 'python ' + currPath + '/ui/UIResZip.py'\n    ret = subprocess.call(uiResZipCommand, shell=True)\n    print(\"uiResZipCommand ret:\" + str(ret))\n    if ret != 0 :\n        return ret\n\nif __name__ == \"__main__\":\n    svnCommand = \"svn update\"\n    os.system(svnCommand)\n\n    filename = sys.argv[0] \n    dirname = os.path.dirname(filename) \n    abspath = os.path.abspath(dirname)\n    currPath = abspath.replace(\"\\\\\", '/')\n\n    #1拷贝font\n    copyFontCommand = 'python ' + currPath + '/font/CopyFont.py'\n    os.system(copyFontCommand)\n\n    #2拷贝icon\n    copyIconCommand = 'python ' + currPath + '/icon/CopyIcon.py'\n    os.system(copyIconCommand)\n\n    #3拷贝audio\n    copySoundCommand = 'python ' + currPath + '/audio/CopyAudio.py'\n    os.system(copySoundCommand) \n\n    excuteCommandAndReturnErrcode()","sub_path":"SyncToAssets.py","file_name":"SyncToAssets.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"78969902","text":"\"\"\"\nhttps://leetcode.com/problems/longest-substring-without-repeating-characters/\n\"\"\"\n\nclass Solution:\n\n    def get_ind(self, c):\n        return ord(c) - 97\n\n    def lengthOfLongestSubstring(self, s):\n\n        ls = []\n        current_min = 0\n        tracker = [-1] * 26\n\n        for i in range(0, len(s)):\n\n            k = self.get_ind(s[i])\n\n            # this char is not encountered\n            if tracker[k] == -1:\n                tracker[k] = i\n            else:\n\n                # encountered char, get previous index\n                pre_ind = tracker[k]\n                tracker[k] = i  # set new tracker position\n\n                # from current min to i should be the not repeated char\n                ls.append(i - current_min)\n\n                # update current min to the one after last counter of this character\n                current_min = max(current_min, pre_ind + 1)\n\n        ls.append(len(s) - current_min)\n\n        return max(ls)\n\n\n\ns = Solution()\n\nprint(s.lengthOfLongestSubstring(\"\"))","sub_path":"p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"652570871","text":"'''\n Core classes for strategies\n order format: (timestamp, limit_price, volume, direction)\n\n'''\n\nimport logging\nLOGGING_LEVEL = logging.INFO\n\n\nclass Strategy(object):\n\n    def __init__(self, name=None, log_level=None):\n        self.orders = []\n        if name == None:\n            name = self.__class__.__name__\n        self.name = name\n        self.log = logging.getLogger(self.name)\n        self.log.setLevel(log_level or LOGGING_LEVEL)\n\n    def order_callback(self, order):\n        \"\"\" Order callback should be set by backtester before\n            the first `step`. \"\"\"\n        raise NotImplementedError\n\n    def process_datapoint(self, datapoint):\n        \"\"\" Method for hiding all internal operations, (e.g. tracking prices).\n            Backtester calls this before it calls `step`.\n            Use `super` when overriding. \"\"\"\n        self.step(datapoint)\n\n    def step(self, datapoint):\n        \"\"\" Main method, strategy decisions should start here.\n            Do not use `super` when overriding. \"\"\"\n        raise NotImplementedError\n\n    def finalize(self):\n        \"\"\" Finalize everything before close, i.e. shut down the position,\n            reset indicators, etc.\"\"\"\n        raise NotImplementedError\n\n    def order(self, timestamp, limit_price, volume):\n        \"\"\" Send order method. \"\"\"\n        order = (timestamp, limit_price, volume)\n        self.orders.append(order)\n        self.log.debug('sent order %s', order)\n        self.order_callback(order)\n\nclass PositionalStrategy(Strategy):\n    ''' PositionalStrategy will handle all order generation resulting from\n        changing its position via `change_posiiton` method. '''\n\n    def __init__(self, name=None, volume=1.0, slippage=0., log_level=None):\n        '''\n        Initialize PositionalStrategy.\n\n        `slippage` determines assumed transaction costs when using naive\n            backtester; when using matching engine backtester, slippage becomes\n            actual limit price shift.\n\n        `volume` determines max size for backtesting. E.g., setting volume=5\n            followed by self.change_position(0.5) will yield a buy order with\n            volume=2.5.\n\n        And do not forget to call the constructor when overriding.\n        '''\n        self.positions = []\n        self.volume = volume\n        self.slippage = slippage\n        self._current_point = None\n        self._first_timestamp = None\n        self._price_overrides = 0\n        super(PositionalStrategy, self).__init__(name, log_level)\n\n    @property\n    def position(self):\n        ''' Current position. Always in range [-1, 1]. '''\n        return self.positions[-1][2]\n\n    def process_datapoint(self, datapoint):\n        ''' Accept `datapoint` and prepare to execute next `step`.\n            Datapoint is assumed to be OHLC bar with associated timestamp\n            in corresponding attributes. '''\n        timestamp = datapoint.timestamp\n        if self._current_point and self._current_point.timestamp.date() != \\\n          timestamp.date():\n            self._first_timestamp = timestamp\n        self._current_point = datapoint\n        if len(self.positions) == 0: # initialize position at 0\n            self.positions.append((timestamp, datapoint.C, 0))\n        super(PositionalStrategy, self).process_datapoint(datapoint)\n\n    def change_position(self, position, price='close', defaulting='open',\n                        timestamp=None, ignore_timecheck=False):\n        '''\n        Change position of strategy, which is the main way to initiate\n        trades.\n\n        `position` should be in range [-1, 1]. 1 means `go full long`,\n            -1 `go full short`.\n\n        `price` sould be 'close' if entry should by performed on close\n            price, or some number if entry should be made by stop order.\n\n        `defaulting` determines a way to resolve stop price\n            unavailability: if stop price is not available in current bar,\n            execute order by 'open' or 'close' prices, or pass 'override' to\n            execute order by requested price regardless.\n\n        `timestamp` is used if you want to double-check if your strategy\n            trades on current bar; otherwise, omit it from your args.\n\n        `ignore_timecheck` allows you to bypass timestamp safechecks,\n            i.e. when closing the trade on previous EOD from today's first bar.\n        '''\n        point = self._current_point\n        timestamp = timestamp or point.timestamp\n        slip = self.slippage\n        old_position = self.position\n        volume = position - old_position\n        if not ignore_timecheck:\n            if timestamp != point.timestamp:\n                self.log.warning('order timestamp %s is not current '\\\n                                 'timestamp %s' ,timestamp, point.timestamp)\n            if self._first_timestamp == timestamp:\n                self.log.warning('position change on the openning of a day')\n        ## calculating price\n        if price == 'close':\n            limit_price = point.C\n        elif type(price) in (float, int): # calc limit price from stop price\n            # price present in current bar? everything's ok then\n            if price >= point.L - slip and price <= point.H + slip:\n                limit_price = price\n            # price is not in current bar (i.e., gap)? defaulting\n            else:\n                self._price_overrides += 1\n                if defaulting == 'close':\n                    limit_price = point.C\n                elif defaulting == 'open':\n                    limit_price = point.O\n                elif defaulting == 'override':\n                    pass\n                else:\n                    raise Exception('requested defaulting mode '\\\n                                    ' is not supported')\n                self.log.debug('requested price %s (%s) is not present in '\\\n                                'current bar (%s)' % (price, volume, timestamp))\n                self.log.debug('defaulting to `%s` price %s', defaulting,\n                                 limit_price)\n        else:\n            raise Exception('requested price %s cannot be accepted' % price)\n        ## executing\n        self.positions.append((timestamp, limit_price, position))\n        if volume > 0:\n            limit_price += slip\n        elif volume < 0:\n            limit_price -= slip\n        self.log.debug('position change from %s to %s' % (old_position,\n          position))\n        self.order(timestamp, limit_price, volume)\n\n    def finalize(self):\n        self.log.debug('finalization requested')\n        if self.position != 0:\n            self.change_position(0)\n        self._current_point = None\n        self._first_timestamp = None\n        self.log.debug('finalized')\n\n    def exit(self, **kwargs):\n        self.change_position(0, **kwargs)\n\n    def long(self, **kwargs):\n        self.change_position(1, **kwargs)\n\n    def short(self, **kwargs):\n        self.change_position(-1, **kwargs)\n","sub_path":"backtest/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"191001824","text":"# Test only upper values are included\nUPPER_VALUE = 'foo'\nlower_value = 'bar'\nmixed_VALUE = 'eek'\n\n# Helpful test placeholders.\nSETTING_1 = 1\nSETTING_2 = 2\nSETTING_3 = 3\nSETTING_4 = 4\nSETTING_5 = 5\n\n# Factory sample values\nTEST_NAMED_FACTORY = {\n    'default': (\n        'tests.factory.Bar', {\n            'length': 42\n        },\n    ),\n    'iron': (\n        'tests.factory.IronBar', {\n            'length': 24\n        },\n    ),\n    'steel': ('tests.factory.SteelBeam', {})\n}\n\n# Factory sample values\nTEST_NAMED_FACTORY_NO_DEFAULT = {\n    'iron': (\n        'tests.factory.IronBar', {\n            'length': 24\n        },\n    ),\n    'steel': ('tests.factory.SteelBeam', {})\n}\n\n# Config sample values\nTEST_NAMED_CONFIG = {\n    'default': {\n        'length': 42,\n        'foo': 'bar'\n    },\n    'eek': {\n        'length': 24,\n        'foo': 'bar'\n    }\n}\n\n# Providers\nTEST_PROVIDERS = ['tests.test_conf_helpers_providers.ProviderBaseTest']\n","sub_path":"tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"289383683","text":"import tkinter as tk\n \nmaster = tk.Tk()\ndef callback():\n    print(\"我被调用了!\")\n \nlongtext = \"\"\"\n我明明只是一个按钮,\n作为按钮并不需要太多\n的文字用于告诉用户当\n我被按下的时候会发生\n什么事情,但我为什么\n这么长?\n\"\"\"\nb = tk.Button(master, text=longtext, anchor=\"w\", justify=\"left\", padx=2, command=callback)\nb.pack()\n \nmaster.mainloop()","sub_path":"Tkinter/2-Button/2-3.py","file_name":"2-3.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"77268405","text":"\"\"\" Bank account module \"\"\"\nimport datetime\nimport pytz\n\n\nclass Account:\n    \"\"\" Simple account class with balance \"\"\"\n\n    # Static method, shared by all instances of class\n    # a method that belongs to the class, but doesn't use or manipulate the object\n    @staticmethod\n    def _current_time():\n        utc_time = datetime.datetime.utcnow()\n        return pytz.utc.localize(utc_time)\n\n    def __init__(self, name, balance):\n        \"\"\" Account initialize \"\"\"\n        self._name = name\n        self.__balance = balance\n        self._transaction_list = [(Account._current_time(), balance)]\n        print(\"Account created for \" + self._name)\n\n    def deposit(self, amount):\n        \"\"\" Deposit into account \"\"\"\n        if amount > 0:\n            self.__balance += amount\n            self._transaction_list.append((Account._current_time(), amount))\n        else:\n            print(\"Amount to deposit must be greater than zero.\")\n        self.show_balance()\n\n    def withdraw(self, amount):\n        \"\"\" Withdraw from account \"\"\"\n        if 0 < amount <= self.__balance:\n            self.__balance -= amount\n            self._transaction_list.append((Account._current_time(), -amount))\n        else:\n            print(\"The amount must be between zero and your account balance\")\n        self.show_balance()\n\n    def show_balance(self):\n        \"\"\" Print account balance \"\"\"\n        print(\"Balance is {}\".format(self.__balance))\n\n    def show_transactions(self):\n        \"\"\" Print transaction history \"\"\"\n        for date, amount in self._transaction_list:\n            if amount > 0:\n                tran_type = \"deposited\"\n            else:\n                tran_type = \"withdrawn\"\n                amount *= -1\n            print(\"{:>6} {} on {} (local time was {})\"\n                  .format(amount, tran_type, date, date.astimezone()))\n\n\nif __name__ == '__main__':\n    scott_acct = Account(\"Scott\", 0)\n    scott_acct.show_balance()\n\n    scott_acct.deposit(1000)\n    scott_acct.deposit(0)\n\n    scott_acct.withdraw(500)\n    scott_acct.withdraw(1500)\n\n    scott_acct.show_transactions()\n\n    tim = Account(\"Tim\", 800)\n    tim.__balance = 15000   ## has no effect, python mangles double underscore attributes\n    tim.deposit(100)\n    tim.withdraw(200)\n    tim.show_transactions()\n\n","sub_path":"12-oop/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"552735604","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom youtubedownloader import youtubewindowclass\nfrom converertorgui import convertorwindowclass\n\n\n# error in pytube so do this before proceding https://github.com/pytube/pytube/issues/1105#issuecomment-907033591\n# i have fixed this in this program by cloning the module from github and correcting inside it\n\n\nclass Ui_Dialog(object):\n    def setupUi(self, Dialog):\n        Dialog.setObjectName(\"Dialog\")\n        Dialog.resize(472, 334)\n        self.Heading = QtWidgets.QLabel(Dialog)\n        self.Heading.setGeometry(QtCore.QRect(125, 0, 241, 31))\n        font = QtGui.QFont()\n        font.setPointSize(20)\n        font.setBold(True)\n        font.setUnderline(True)\n        font.setWeight(75)\n        self.Heading.setFont(font)\n        self.Heading.setAutoFillBackground(False)\n        self.Heading.setObjectName(\"Heading\")\n        self.youtubevidedownloadbutton = QtWidgets.QPushButton(Dialog)\n        self.youtubevidedownloadbutton.setGeometry(QtCore.QRect(30, 60, 151, 41))\n        font = QtGui.QFont()\n        font.setBold(True)\n        font.setWeight(75)\n        self.youtubevidedownloadbutton.setFont(font)\n        self.youtubevidedownloadbutton.setObjectName(\"youtubevidedownloadbutton\")\n        self.youtubevidedownloadbutton.clicked.connect(\n            self.on_click_youtubebutton\n        )  # connecting\n        self.converterbutton = QtWidgets.QPushButton(Dialog)\n        self.converterbutton.setGeometry(QtCore.QRect(250, 60, 151, 41))\n        font = QtGui.QFont()\n        font.setBold(True)\n        font.setWeight(75)\n        self.converterbutton.setFont(font)\n        self.converterbutton.setObjectName(\"converterbutton\")\n        self.converterbutton.clicked.connect(\n            self.on_click_converterbutton\n        )  # connecting\n\n        self.retranslateUi(Dialog)\n        QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n    def retranslateUi(self, Dialog):\n        _translate = QtCore.QCoreApplication.translate\n        Dialog.setWindowTitle(_translate(\"Dialog\", \"Productivity Tools\"))\n        self.Heading.setText(_translate(\"Dialog\", \"Productivity Tools\"))\n        self.youtubevidedownloadbutton.setText(_translate(\"Dialog\", \"▶️Youtube video \"))\n        self.converterbutton.setText(_translate(\"Dialog\", \"🔄Video 2 Audio\"))\n\n    def on_click_youtubebutton(self):\n        self.window = QtWidgets.QMainWindow()\n        self.ui = youtubewindowclass()\n        self.ui.youtubewindow(self.window)\n        self.window.show()\n\n    def on_click_converterbutton(self):\n        self.window1 = QtWidgets.QMainWindow()\n        self.ui = convertorwindowclass()\n        self.ui.covertorwindow(self.window1)\n        self.window1.show()\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    app = QtWidgets.QApplication(sys.argv)\n    Dialog = QtWidgets.QDialog()\n    ui = Ui_Dialog()\n    ui.setupUi(Dialog)\n    Dialog.show()\n    sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"420005745","text":"import sys\nfrom PyQt5 import QtGui, QtCore, QtWidgets\n\nimport airsortUI as design\nimport qdarkstyle\n\nimport supportFile\nimport mainFunctions\n\nimport numpy\nimport csv\nimport pickle\nimport datetime\nimport locale\n# this reads the environment and inits the right locale\nlocale.setlocale(locale.LC_ALL, \"\")\n\n\nclass example(QtWidgets.QMainWindow, design.Ui_MainWindow):\n    def __init__(self):\n\n        super(self.__class__, self).__init__()\n        self.setupUi(self)\n\n\nclass MainWIndow(QtWidgets.QMainWindow, design.Ui_MainWindow):\n\n    def __init__(self, parent=None):\n        QtWidgets.QMainWindow.__init__(self, parent)\n        self.setupUi(self)\n\n        self.setWindowTitle(\"Airsort\")\n        self.setWindowIcon(QtGui.QIcon('icon.png'))\n\n        self.textRegAero = [self.tae0CodOco, self.tae1Matricula, self.tae2CategOperador,\n                            self.tae3TipoAero, self.tae4Fabricante, self.tae5Modelo, self.tae6TipoICAO,\n                            self.tae7TipoMotor, self.tae8QtdMotores, self.tae9PesoMax, self.tae11NumAssentos,\n                            self.tae13PaisFabric, self.tae14PaisRegistro, self.tae15RegCategoria, self.tae16RegSegmento,\n                            self.tae17VooOrigem, self.tae18VooDestino, self.tae19FaseOperacao, self.tae20TipoOperacao,\n                            self.tae22Fatalidades]\n        self.textRegOco = [self.toc0CodOco, self.toc2TipoOco, self.toc3LatitudeOco, self.toc4LongitudeOco,\n                           self.toc5CidadeOco, self.toc8AerodromeOco, self.toc13NumRelatOco, self.toc16Recomend]\n\n\n\n        self.initializeInsereRemoveTab()\n\n        lll = ['classification.bin', 'type.bin', 'city.bin', 'UF.bin', 'aerodrome.bin', 'dayShift.bin', 'invStatus.bin',\n         'veicType.bin', 'manufacturer.bin', 'model.bin', 'qtyEngine.bin', 'class.bin', 'harm.bin',\n         'fatalities.bin']\n\n        self.menuVariablesOco = [self.dropEstado, self.dropCidade, self.dropAerodromo, self.dropTurno, self.dropTipoOcorrencia, self.dropClassificacao]\n        self.menuVariablesOcoBin = ['UF.bin', 'city.bin', 'aerodrome.bin', 'dayShift.bin', 'type.bin', 'classification.bin']\n        self.menuVariablesOcoDictBin = ['dicUF.bin', 'dicCity.bin', 'dicAerodrome.bin', 'dicDayShift.bin', 'dicType.bin', 'dicClassification.bin']\n\n        self.menuVariablesAero = [self.dropTipoAeronave, self.dropFabricante, self.dropModelo, self.dropQtdMotores, self.dropCategoriaPeso, self.dropDano]\n        self.menuVariablesAeroBin = ['veicType.bin', 'manufacturer.bin', 'model.bin', 'qtyEngine.bin', 'class.bin', 'harm.bin','fatalities.bin']\n        self.menuVariablesAeroDictBin = ['dicVeicType.bin', 'dicManufacturer.bin', 'dicModel.bin', 'dicQtyEngine.bin','dicClass.bin', 'dicHarm.bin', 'dicFatalities.bin']\n\n\n        listaTipoOco = supportFile.returnSorted('dicType.bin')\n        self.dropTipoOcorrencia.addItems(listaTipoOco)\n\n        self.dropClassificacao.addItems(supportFile.returnSorted('dicClassification.bin'))\n\n        listaTurnoDia = supportFile.returnSorted('dicDayShift.bin')\n        turnos = {\"MADRUGADA\":0, \"MANHÃ\":1, \"TARDE\":2, \"NOITE\":3} #garante a ordem intuitiva dos turnos (caso nao tenha todos)\n        listaTurnoDia = sorted(listaTurnoDia, key=lambda x: (x not in turnos, turnos.get(x), None))\n        self.dropTurno.addItems(listaTurnoDia)\n\n        listaCatPesos = supportFile.returnSorted('dicClass.bin')\n        pesos = {\"***\":0, \"LEVE\":1, \"MÉDIA\":2, \"MÉDIO\":3, \"PESADA\":4, \"PESADO\":5}  # garante a ordem intuitiva\n        listaCatPesos = sorted(listaCatPesos, key=lambda x: (x not in pesos, pesos.get(x), None))\n        self.dropCategoriaPeso.addItems(listaCatPesos)\n\n        listaTipoAero = supportFile.returnSorted('dicVeicType.bin')\n        self.dropTipoAeronave.addItems(listaTipoAero)\n\n        listaDano = supportFile.returnSorted('dicHarm.bin')\n        damages = {\"***\":0, \"NENHUM\":1, \"LEVE\":2, \"SUBSTANCIAL\":3, \"DESTRUÍDA\":4, \"DESTRUÍDO\":5}\n        listaDano = sorted(listaDano, key=lambda x: (x not in damages, damages.get(x), None))\n        self.dropDano.addItems(listaDano)\n\n\n\n        #listaAerodromo = supportFile.returnSorted('dicAerodrome.bin')\n        #self.dropAerodromo.addItems(listaAerodromo)\n\n        listaQtdMotores = supportFile.returnSorted('dicQtyEngine.bin')\n        motors = {\"***\":0, \"SEM TRAÇÃO\":1, \"MONOMOTOR\":2, \"BIMOTOR\":3, \"TRIMOTOR\":4, \"QUADRIMOTOR\":5}  # garante a ordem intuitiva\n        listaQtdMotores = sorted(listaQtdMotores, key=lambda x: (x not in motors, motors.get(x), None))\n        self.dropQtdMotores.addItems(listaQtdMotores)\n\n\n        listaUF = supportFile.returnSorted('dicUF.bin')\n        self.dropEstado.clear()\n        self.dropEstado.addItem('Qualquer')\n        self.dropEstado.addItems(listaUF)\n\n        # se trocar estado, troca a selecao de cidades e aerodromos\n        self.dropCidade.setEnabled(False)  # Não pode selecionar, só Qualquer\n        self.dropAerodromo.setEnabled(False)  # Não pode selecionar, só Qualquer\n        self.dropEstado.currentIndexChanged['QString'].connect(self.onUFSelected)\n\n\n        listaFabricantes = supportFile.returnSorted('dicManufacturer.bin')\n        self.dropFabricante.clear()\n        self.dropFabricante.addItem('Qualquer')\n        self.dropFabricante.addItems(listaFabricantes)\n\n        # se trocar Fabricante, troca a selecao de modelos\n        self.dropModelo.setEnabled(False)  # Não pode selecionar, só Qualquer\n        self.dropFabricante.currentIndexChanged['QString'].connect(self.onFabricanteSelected)\n\n\n\n        # usa regex para validar entradas ao linebox de codigo ID\n        # para até 35 digitos numericos (embora tenham 15 - pois podem ser inseridas novas IDs mais longas mais tarde)\n        self.regexNum35 = QtCore.QRegExp(\"[0-9]\\\\d{0,34}\")\n        self.onlyDigits = QtGui.QRegExpValidator(self.regexNum35)\n        self.textCodigo.setValidator(self.onlyDigits)\n\n        # Bind ações de menu (Sair/Exit e Sobre/About)\n        self.actionSair.triggered.connect(self.shutDown)\n        self.actionSobre.triggered.connect(self.aboutWindow)\n        self.actionSalvarResultados.triggered.connect(self.saveCurrentResults)\n\n        # Bind os botoes de Limpar dados de busca e Buscar com dados atuais\n        self.limparButton.clicked.connect(self.onLimparButtonClicked)\n        self.buscarButton.clicked.connect(self.onBuscarButtonClicked)\n\n\n        # Bind as duas tabelas ao doubleclick para abrir raw data\n        self.tableResultadosOco.itemDoubleClicked.connect(self.onResultDoubleClick)\n        self.tableResultadosAero.itemDoubleClicked.connect(self.onResultDoubleClick)\n\n        # Bind a troca de data e hora de começo do período (From) à data e hora mínimas\n        # que poderão ser escolhidas no calendário de fim do período (To)\n        self.dateTimeFrom.dateTimeChanged.connect(self.onDTFromChanged)\n\n\n    def saveCurrentResults(self):\n\n        now = (str(QtCore.QDate.currentDate().toPyDate())).replace(\" \",\"_\").replace(\"-\",\"\")\n\n        now += \"-\"+str(QtCore.QDateTime.currentDateTime().secsTo(QtCore.QDateTime(\n                        QtCore.QDate.currentDate().addDays(1), QtCore.QTime(0,0))))\n\n        nameOco = \"resultadosOcorrencias_\" + now + \".csv\"\n        nameAero = \"resultadosAeronaves_\" + now+ \".csv\"\n        nameRank = \"resultadosAnalise_\" + now+ \".txt\"\n\n\n        model = self.tableResultadosOco.model()\n        data = []\n        headers = []\n\n        if model.rowCount() == 0:\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"Tabela de resultados vazia\")\n            msg.setText(\"Não há resultados para salvar. Faça outra busca.\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n            return\n\n        for column in range(model.columnCount()):\n            headers.append(str(model.headerData(column,QtCore.Qt.Horizontal)))\n        for row in range(model.rowCount()):\n            data.append([])\n            for column in range(model.columnCount()):\n                index = model.index(row, column)\n                data[row].append(str(model.data(index)))\n\n        data.insert(0,headers)\n        with open(nameOco, \"w\", newline=\"\") as f:\n            writer = csv.writer(f)\n            writer.writerows(data)\n\n        model = self.tableResultadosAero.model()\n        data = []\n        headers = []\n        for column in range(model.columnCount()):\n            headers.append(str(model.headerData(column,QtCore.Qt.Horizontal)))\n        for row in range(model.rowCount()):\n            data.append([])\n            for column in range(model.columnCount()):\n                index = model.index(row, column)\n                data[row].append(str(model.data(index)))\n\n        data.insert(0,headers)\n        with open(nameAero, \"w\", newline=\"\") as f:\n            writer = csv.writer(f)\n            writer.writerows(data)\n\n        data = self.rankingBox.toPlainText()\n\n        with open(nameRank, \"w\") as f:\n            f.write(data)\n\n        msg = QtWidgets.QMessageBox()\n        msg.setIcon(QtWidgets.QMessageBox.Information)\n\n        msg.setWindowTitle(\"Resultados salvos\")\n        msg.setText(\"Resultados de ocorrência, aeronave e análise\\n\"\n                    \"salvos com sucesso nos arquivos:\\n\"\n                    \"{}\\n{}\\n{}\".format(nameOco, nameAero, nameRank))\n        msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n        msg.exec()\n        return\n\n\n\n\n    def onDTFromChanged(self, dt):\n        self.dateTimeTo.setMinimumDateTime(dt)\n\n    def onResultDoubleClick(self, item):\n\n        table = self.sender()\n\n        row = item.row()\n        id = table.item(row, 0)\n        id = id.text()\n\n        #Ocorrencia\n        dados = mainFunctions.getInfoID(id, 'Trie.bin')\n        textOco = 'Ocorrência\\n\\n'\n        with open('infoOco.bin', 'rb') as f:\n            info = pickle.load(f)\n            for i in range(len(info)):\n                textOco += '{} = {}\\n'.format(info[i], dados[0][i])\n        #Aeros\n        textAero = \"\\nAeronaves Envolvidas\\n\"\n        with open('infoAnv.bin', 'rb') as f:\n            info = pickle.load(f)\n            for i in range(1, len(dados)):\n                textAero += '\\nAeronave {}:\\n'.format(i)\n                for j in range(len(info)):\n                    textAero += '{} = {}\\n'.format(info[j], dados[i][j])\n\n        self.rawWindow = QtWidgets.QTextEdit()\n        self.rawWindow.setReadOnly(True)\n        self.rawWindow.setFont(QtGui.QFont(\"Consolas\", 10))\n        self.rawWindow.setPlainText(textOco+textAero)\n        self.rawWindow.setWindowTitle('\\nOcorrência ID {} (raw data)\\n'.format(id))\n        self.rawWindow.setFixedWidth(500)\n        self.rawWindow.setFixedHeight(600)\n        self.rawWindow.show()\n\n\n    def onFabricanteSelected(self):\n        # Troca de fabricante implica troca na selecao de modelos\n\n        maker = self.dropFabricante.currentText()\n\n        if (maker != \"Qualquer\"):\n            self.dropModelo.clear()\n            self.dropModelo.addItem('Qualquer')\n            listaModels = supportFile.getIDs('dicModelsByManufacturer.bin', 'modelsByManufacturer.bin', maker)\n            print(maker, listaModels)\n            listaModels = sorted(listaModels, key=locale.strxfrm)  # Sort baseado na lingua local (because acentos)\n            print(maker, listaModels)\n            self.dropModelo.addItems(listaModels)\n            self.dropModelo.setEnabled(True)  # Pode selecionar agora\n\n        else: # Se for Qualquer ou ***, presume-se modelo Qualquer\n            self.dropModelo.clear()\n            self.dropModelo.addItem('Qualquer')\n            self.dropModelo.setEnabled(False) # Não pode selecionar, só Qualquer\n\n\n    # Troca de Estado\n    def onUFSelected(self):\n\n        uf = self.dropEstado.currentText() # Novo dado escolhido em Estado\n\n        if (uf != \"***\") and (uf != \"Qualquer\"): # Se for UF válido\n            self.dropCidade.clear()\n            self.dropCidade.addItem('Qualquer')\n            listaCidades = supportFile.getIDs('dicCitiesByUF.bin', 'citiesByUF.bin', uf)\n            listaCidades = sorted(listaCidades, key=locale.strxfrm) # Sort baseado na lingua local (because acentos)\n            self.dropCidade.addItems(listaCidades)\n            self.dropCidade.setEnabled(True) # Pode selecionar\n\n            self.dropAerodromo.clear()\n            self.dropAerodromo.addItem(\"Qualquer\")\n            listaAerodromos = supportFile.getIDs('dicAerodromesByUF.bin', 'aerodromesByUF.bin', uf)\n            listaAerodromos = sorted(listaAerodromos, key=locale.strxfrm)\n            self.dropAerodromo.addItems(listaAerodromos)\n            self.dropAerodromo.setEnabled(True)  # Pode selecionar\n\n        else: # Se for Qualquer ou ***, presume-se cidade Qualquer\n            self.dropCidade.clear()\n            self.dropCidade.addItem('Qualquer')\n            self.dropCidade.setEnabled(False) # Não pode selecionar, só Qualquer\n\n            self.dropAerodromo.clear()\n            self.dropAerodromo.addItem('Qualquer')\n            self.dropAerodromo.setEnabled(False)  # Não pode selecionar, só Qualquer\n\n    def onLimparButtonClicked(self):\n\n        # Reseta todos os drop down menus para o índice 0, com a opção \"Qualquer\"\n        for v in self.menuVariablesOco:\n            v.setCurrentIndex(0)\n        for v in self.menuVariablesAero:\n            v.setCurrentIndex(0)\n\n        # Limpa a entrada do ID\n        self.textCodigo.setText(\"\")\n\n        # Limpa button groups:\n        self.butInvQqr.setChecked(True)\n        self.butFatalQqr.setChecked(True)\n\n        # Reseta calendário FROM para seu mínimo e o TO para a data atual no sistema do usuário\n        self.dateTimeFrom.setDateTime(self.dateTimeFrom.minimumDateTime())\n        self.dateTimeTo.setDateTime(self.dateTimeTo.dateTime().currentDateTime())\n\n\n\n    def onBuscarButtonClicked(self):\n\n        categorias = ['Classificação:', 'Tipo:', 'Cidade:', 'Estado:', 'Aeródromo:', 'Turno do Dia:', 'Status Investigativo:',\n             'Tipo de Veículo:', 'Fabricante:', 'Modelo:', 'Quantidade de Motores:', 'Classe:', 'Dano:',\n             'Presença de Fatalidades:']\n        l1 = ['classification.bin', 'type.bin', 'city.bin', 'UF.bin', 'aerodrome.bin', 'dayShift.bin', 'invStatus.bin',\n              'veicType.bin', 'manufacturer.bin', 'model.bin', 'qtyEngine.bin', 'class.bin', 'harm.bin',\n              'fatalities.bin']\n        dictionaryFiles = ['dicClassification.bin', 'dicType.bin', 'dicCity.bin', 'dicUF.bin', 'dicAerodrome.bin', 'dicDayShift.bin',\n              'dicInvStatus.bin', 'dicVeicType.bin', 'dicManufacturer.bin', 'dicModel.bin', 'dicQtyEngine.bin',\n              'dicClass.bin', 'dicHarm.bin', 'dicFatalities.bin']\n\n\n        IDs = set()\n\n        strIDParcial = self.textCodigo.displayText()\n        #if strIDParcial != \"\":  #tem ID numerico\n\n        IDs = IDs.union(mainFunctions.filterIDTrie(strIDParcial, 'Trie.bin'))\n\n        for i,v in enumerate(self.menuVariablesOco):\n            if v.currentText() != \"Qualquer\":\n                IDs = IDs.intersection(supportFile.getIDs(self.menuVariablesOcoDictBin[i], self.menuVariablesOcoBin[i], v.currentText()))\n\n        textinvest = self.butgroupInvestigacao.checkedButton().text().upper()\n        if textinvest != 'QUALQUER':\n            IDs = IDs.intersection(supportFile.getIDs('dicInvStatus.bin', 'invStatus.bin', textinvest))\n\n        for i,v in enumerate(self.menuVariablesAero):\n            if v.currentText() != \"Qualquer\":\n                IDs = IDs.intersection(supportFile.getIDs(self.menuVariablesAeroDictBin[i], self.menuVariablesAeroBin[i], v.currentText()))\n\n        textfatal = self.butgroupFatalidades.checkedButton().text().upper()\n        if textfatal == \"FATAL\":\n            IDs = IDs.intersection(supportFile.getIDs('dicFatalities.bin', 'fatalities.bin', \"SIM\"))\n        elif textfatal == \"NÃO FATAL\":\n            IDs = IDs.intersection(supportFile.getIDs('dicFatalities.bin', 'fatalities.bin', \"NÃO\"))\n\n        startdate = datetime.datetime.combine(self.dateTimeFrom.date().toPyDate(), self.dateTimeFrom.time().toPyTime())\n        enddate = datetime.datetime.combine(self.dateTimeTo.date().toPyDate(), self.dateTimeTo.time().toPyTime())\n\n        # ID, Classificacao, TipoOco, Cidade, UF, Aerodromo, Dia e Hora, Turno do Dia, Invest Status, # Aeronaves\n        listaIndicesOco = [0, 1, 2, 5, 6, 8, \"dh\", \"turno\", 12, 17]\n\n        dictionaryFiles = ['dicClassification.bin', 'dicType.bin', 'dicCity.bin', 'dicUF.bin', 'dicAerodrome.bin',\n                           'dicDayShift.bin',\n                           'dicInvStatus.bin', 'dicVeicType.bin', 'dicManufacturer.bin', 'dicModel.bin',\n                           'dicQtyEngine.bin',\n                           'dicClass.bin', 'dicHarm.bin', 'dicFatalities.bin']\n        listaIndicesRankOco = [1,2,5,6,8]\n\n\n        #da um clear na table anterior\n        self.tableResultadosOco.setSortingEnabled(False)  # evita bug esquisito que mantem row vazias se estiver sorted\n        for x in reversed(range(self.tableResultadosOco.rowCount())):\n            self.tableResultadosOco.removeRow(x)\n        #self.tableResultadosOco.setRowCount(0)\n        IDkeepers = []\n        ranksOco = []\n        sortedOptionsOco = []\n        for dicfile in dictionaryFiles[0:7]:\n            sortedOptionsOco.append(supportFile.returnSorted(dicfile))\n            ranksOco.append([0]*len(sortedOptionsOco[-1]))\n\n        for id in IDs:\n\n            dados = mainFunctions.getInfoID(id, 'Trie.bin')\n\n            date = dados[0][9]\n            time = dados[0][10]\n\n            #print(date)\n            #print(time)\n\n            datatempo = datetime.datetime.combine(datetime.date(int(date.split(\"-\")[0]), int(date.split(\"-\")[1]), int(date.split(\"-\")[2]) ),\n                                                  datetime.time(int(time.split(\":\")[0]), int(time.split(\":\")[1]), int(time.split(\":\")[2]) ))\n            if startdate <= datatempo <= enddate:\n                IDkeepers.append(id)\n\n                dh = date + \" \" + time\n                horahora = int(time.split(\":\")[0])\n                if horahora >= 18:\n                    turno = \"NOITE\"\n                elif horahora >= 12:\n                    turno = \"TARDE\"\n                elif horahora >= 6:\n                    turno = \"MANHÃ\"\n                else:\n                    turno = \"MADRUGADA\"\n\n                # ID, Classificacao, TipoOco, Cidade, UF, Aerodromo, Dia e Hora, Turno do Dia, Invest Status, # Aeronaves\n                #listaIndicesOco = [0, 1, 2, 5, 6, 8, \"dh\", \"turno\", 12, 17]\n                #Rankings Oco\n\n                for i in range(5):\n                    for k,item in enumerate(sortedOptionsOco[i]):\n                        if dados[0][ listaIndicesRankOco[i]] == item:\n                            ranksOco[i][k] += 1\n                            break\n\n                for k,item in enumerate(sortedOptionsOco[5]):\n                    if turno == item:\n                        ranksOco[5][k] +=1\n                        break\n\n                for k, item in enumerate(sortedOptionsOco[6]):\n                    if dados[0][ 12 ] == item: # indice Status investig\n                        ranksOco[6][k] += 1\n                        break\n\n\n\n                #rankOcoClassif = [0]*self.dropClassificacao.count()\n                #for i in range()\n                #    if dados[0][1] ==\n\n                #Tabela Oco\n                rowPosition = self.tableResultadosOco.rowCount()\n                self.tableResultadosOco.insertRow(rowPosition)\n                for i, j in enumerate(listaIndicesOco):\n                    if j != \"dh\" and j != \"turno\":\n                        self.tableResultadosOco.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(dados[0][j]))\n                    elif j == \"dh\":\n\n                        self.tableResultadosOco.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(dh))\n                        i += 1\n                        self.tableResultadosOco.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(turno))\n\n\n        self.tableResultadosOco.setSortingEnabled(True)\n        self.tableResultadosOco.sortItems(0, QtCore.Qt.AscendingOrder)\n\n        textao = \"\"\n        textao += \"Dados de Ocorrência:\\n\"\n\n        total = len(IDkeepers)\n\n        if total == 0:\n            textao = \"Sem resultados de ocorrência\"\n        else:\n\n            for i, catigoria in enumerate(categorias[0:7]):\n                textao += '\\n{}\\n'.format(catigoria)\n\n                argindices = numpy.argsort(ranksOco[i])[::-1]\n                if len(argindices) <= 10:\n                    for indice in argindices:\n                        textao += '  {} {} ({:.2f}%)\\n'.format((sortedOptionsOco[i][indice]+':').ljust(60), ranksOco[i][indice], ranksOco[i][indice]*100/total)\n                else:\n                    for indice in argindices[:10]:\n                        textao += '  {} {} ({:.2f}%)\\n'.format((sortedOptionsOco[i][indice]+':').ljust(60), ranksOco[i][indice], ranksOco[i][indice]*100/total)\n\n\n\n        IDs = IDkeepers\n        ranksAero = []\n        sortedOptionsAero = []\n        for dicfile in dictionaryFiles[7:]:\n            sortedOptionsAero.append(supportFile.returnSorted(dicfile))\n            ranksAero.append([0] * len(sortedOptionsAero[-1]))\n\n\n        ## TABLE AERONAVES\n        # ID, TipoAero, Fabricante, Modelo, Qtd Motores, Classe, Dano, Fatalidades\n        listaIndicesAero = [0, 1,3,4,5,8, 10, 21,22]\n\n        # clearzera\n        self.tableResultadosAero.setSortingEnabled(False)  # evita bug esquisito que mantem row vazias se estiver sorted\n        for x in reversed(range(self.tableResultadosAero.rowCount())):\n            self.tableResultadosAero.removeRow(x)\n\n        totalAero = 0\n\n        # self.menuVariablesAero = [self.dropTipoAeronave, self.dropFabricante, self.dropModelo, self.dropQtdMotores, self.dropCategoriaPeso, self.dropDano]\n        #\n\n        for id in IDs:\n            dados = mainFunctions.getInfoID(id, 'Trie.bin')\n            if len(dados) == 2:\n\n                # continua insercao e catalogo\n                totalAero += 1\n\n                # ID, Matricula, TipoAero, Fabricante, Modelo, Qtd Motores, Classe, Dano, Fatalidades\n                #listaIndicesAero = [0, 1, 3, 4, 5, 8, 10, 21, 22]\n\n                # Rank aero\n\n                for i in range(6):\n                    for j, item in enumerate(sortedOptionsAero[i]):\n                        if dados[1][listaIndicesAero[i + 2]] == item:\n                            ranksAero[i][j] += 1\n                            break\n\n                # fatalidade sim ou nao\n                for j, item in enumerate(sortedOptionsAero[6]):\n                    if (dados[1][22] not in ['***', '0']) and item == \"SIM\":\n                        ranksAero[6][j] += 1\n                        break\n                    elif (dados[1][22] in ['***', '0']) and item == \"NÃO\":\n                        ranksAero[6][j] += 1\n                        break\n\n                rowPosition = self.tableResultadosAero.rowCount()\n                self.tableResultadosAero.insertRow(rowPosition)\n                for i, j in enumerate(listaIndicesAero[:8]):\n                    self.tableResultadosAero.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(dados[1][j]))\n\n                if len(dados[1][22]) == 1:\n                    self.tableResultadosAero.setItem(rowPosition, i+1, QtWidgets.QTableWidgetItem((\"00\"+dados[1][22])))\n                elif len(dados[1][22]) == 2:\n                    self.tableResultadosAero.setItem(rowPosition, i+1, QtWidgets.QTableWidgetItem((\"0\"+ dados[1][22])))\n                else:\n                    self.tableResultadosAero.setItem(rowPosition, i+1, QtWidgets.QTableWidgetItem((dados[1][22])))\n\n\n            elif len(dados) > 2:\n                for k in range(1,len(dados)):\n\n                    itemOk = True\n                    for i, v in enumerate(self.menuVariablesAero):\n\n                        if v.currentText().upper() not in [\"QUALQUER\"]:\n                            if dados[k][listaIndicesAero[i+2]] != v.currentText().upper():\n                                itemOk = False\n                                break\n\n                    if self.butgroupFatalidades.checkedButton().text().upper() != \"QUALQUER\":\n                        if dados[k][22] != self.butgroupFatalidades.checkedButton().text().upper():\n                            itemOk = False\n\n                    if itemOk:\n\n                        #continua insercao e catalogo\n                        totalAero += 1\n\n                        # ID, Matricula, TipoAero, Fabricante, Modelo, Qtd Motores, Classe, Dano, Fatalidades\n                        # listaIndicesAero = [0, 1, 3, 4, 5, 8, 10, 21, 22]\n\n                        #Rank aero\n\n                        for i in range(6):\n                            for j, item in enumerate(sortedOptionsAero[i]):\n                                if dados[k][listaIndicesAero[i+2]] == item:\n                                    ranksAero[i][j] += 1\n                                    break\n\n                        # fatalidade sim ou nao\n                        for j, item in enumerate(sortedOptionsAero[6]):\n                            if (dados[k][22] not in ['***', '0']) and item == \"SIM\":\n                                ranksAero[6][j] += 1\n                                break\n                            elif (dados[k][22] in ['***', '0']) and item == \"NÃO\":\n                                ranksAero[6][j] += 1\n                                break\n\n\n                        rowPosition = self.tableResultadosAero.rowCount()\n                        self.tableResultadosAero.insertRow(rowPosition)\n                        for i, j in enumerate(listaIndicesAero[:8]):\n                            self.tableResultadosAero.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(dados[k][j]))\n\n                        if len(dados[k][22]) == 1:\n                            self.tableResultadosAero.setItem(rowPosition, i+1,\n                                                             QtWidgets.QTableWidgetItem((\"00\" + dados[k][22])))\n                        elif len(dados[k][22]) == 2:\n                            self.tableResultadosAero.setItem(rowPosition, i+1,\n                                                             QtWidgets.QTableWidgetItem((\"0\" + dados[k][22])))\n                        else:\n                            self.tableResultadosAero.setItem(rowPosition, i+1, QtWidgets.QTableWidgetItem((dados[k][22])))\n            # ignora se nao tem aeronave inscrita\n\n\n        self.tableResultadosAero.setSortingEnabled(True)\n        self.tableResultadosAero.sortItems(0, QtCore.Qt.AscendingOrder)\n\n        if totalAero > 0:\n\n            textao += \"\\n\\nDados de Aeronaves:\\n\"\n            for i, catigoria in enumerate(categorias[7:]):\n                textao += '\\n{}\\n'.format(catigoria)\n\n                argindices = numpy.argsort(ranksAero[i])[::-1]\n\n                if len(argindices) <= 10:\n                    for indice in argindices:\n                        textao += '  {} {} ({:.2f}%)\\n'.format((sortedOptionsAero[i][indice]+':').ljust(60), ranksAero[i][indice], ranksAero[i][indice]*100/totalAero)\n                else:\n                    for indice in argindices[:10]:\n                        textao += '  {} {} ({:.2f}%)\\n'.format((sortedOptionsAero[i][indice]+':').ljust(60), ranksAero[i][indice], ranksAero[i][indice]*100/totalAero)\n\n        else:\n            textao += \"\\nSem resultados de aeronave.\\n\"\n\n\n        self.rankingBox.setPlainText(textao)\n\n\n\n    def initializeInsereRemoveTab(self):\n\n        self.regexNum35 = QtCore.QRegExp(\"[0-9]\\\\d{0,34}\")\n        self.only35Digits = QtGui.QRegExpValidator(self.regexNum35)\n        self.toc0CodOco.setValidator(self.only35Digits)\n        self.tae0CodOco.setValidator(self.only35Digits)\n\n\n        self.regexNum6 = QtCore.QRegExp(\"[0-9]\\\\d{0,5}\")\n        self.only6Digits = QtGui.QRegExpValidator(self.regexNum6)\n        self.tae9PesoMax.setValidator(self.only6Digits)\n        self.tae11NumAssentos.setValidator(self.only6Digits)\n        self.tae22Fatalidades.setValidator(self.only6Digits)\n        self.toc16Recomend.setValidator(self.only6Digits)\n\n\n\n        self.regexAlpha35 = QtCore.QRegExp(\"[^\\W\\d_]\\\\{0,34}\")\n        self.only35Alpha = QtGui.QRegExpValidator(self.regexAlpha35)\n        #self.toc5CidadeOco.setValidator(self.only35Alpha)\n        #self.tae8QtdMotores.setValidator(self.only35Alpha)\n        #self.tae13PaisFabric.setValidator(self.only35Alpha)\n        #self.tae14PaisRegistro.setValidator(self.only35Alpha)\n\n        #self.textRegAero = [self.tae0CodOco, self.tae1Matricula, self.tae2CategOperador,\n        #                    self.tae3TipoAero, self.tae4Fabricante, self.tae5Modelo, self.tae6TipoICAO,\n        #                    self.tae7TipoMotor, self.tae8QtdMotores, self.tae9PesoMax, self.tae11NumAssentos,\n        #                    self.tae13PaisFabric, self.tae14PaisRegistro, self.tae15RegCategoria, self.tae16RegSegmento,\n        #                    self.tae17VooOrigem, self.tae18VooDestino, self.tae19FaseOperacao, self.tae20TipoOperacao,\n        #                    self.tae22Fatalidades]\n\n        for v in self.textRegOco:\n            v.setClearButtonEnabled(True)\n\n\n        #self.textRegOco = [self.toc0CodOco, self.toc2TipoOco, self.toc3LatitudeOco, self.toc4LongitudeOco,\n        #                   self.toc5CidadeOco, self.toc8AerodromeOco, self.toc13NumRelatOco, self.toc16Recomend]\n\n        for v in self.textRegAero:\n            v.setClearButtonEnabled(True)\n\n\n        self.coc14RelatPublOco.stateChanged.connect(self.onRelatorioPublicadoChanged)\n        self.coc15TemDataRelat.stateChanged.connect(self.onTemDataRelatorioChanged)\n\n        self.limparRegOco.clicked.connect(self.onLimparRegOcoClicked)\n        self.limparRegAero.clicked.connect(self.onLimparRegAeroClicked)\n        self.registrarRegOco.clicked.connect(self.onRegistrarRegOcoClicked)\n        self.registrarRegAero.clicked.connect(self.onRegistrarRegAeroClicked)\n        self.removerRegOco.clicked.connect(self.onRemoverRegOcoClicked)\n\n        self.toc13NumRelatOco.setText(\"\")\n        self.toc13NumRelatOco.setEnabled(False)\n        self.dtoc15DataPublicRelat.setDateTime(QtCore.QDateTime.currentDateTime())\n        self.dtoc15DataPublicRelat.setEnabled(False)\n        self.coc15TemDataRelat.setChecked(False)\n        self.groupBoxPublicacao.setEnabled(False)\n\n        self.coc15TemDataRelat.setChecked(False)\n        self.coc14RelatPublOco.setChecked(False)\n\n\n    def onRemoverRegOcoClicked(self):\n\n        # Checar se ID ja existe\n        id = self.toc0CodOco.displayText()\n        dados = mainFunctions.getInfoID(id, 'Trie.bin')\n\n        if id == \"\":\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"Campo Obrigatório Vazio\")\n            msg.setText(\"Preencha o código identificador da ocorrência.\\n\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n            return\n\n        if dados != -1:  # se não retornou -1, então já existe.\n\n            yn = QtWidgets.QMessageBox.question(self, 'Deletar ocorrência?',\n\n                                                \"Deseja deletar os dados de ocorrência e de aeronaves associados ao código ID informado?\\n\"\n                                                \"(NOTA: Esta ação é irreversível! Os dados correntes serão permanentemente descartados)\",\n                                                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n            if yn == QtWidgets.QMessageBox.No:\n                pass\n            else:\n                retornoRem = mainFunctions.removeData(id, 'Trie.bin')\n                if retornoRem == -1:\n                    msg = QtWidgets.QMessageBox()\n                    msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                    msg.setWindowTitle(\"Erro de remoção\")\n                    msg.setText(\"Não foi possível deletar o registro da ocorrência especificada no banco de dados.\\n\")\n                    msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                    msg.exec()\n                    return\n                else:\n                    msg = QtWidgets.QMessageBox()\n                    msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                    msg.setWindowTitle(\"Remoção bem sucedida\")\n                    msg.setText(\"Registro de ocorrência deletado com sucesso.\\n\")\n                    msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                    msg.exec()\n                    return\n\n\n        else:  # nao existe essa ID;\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"Ocorrência não encontrada\")\n            msg.setText(\"Não existe ocorrência com o código ID informado no banco de dados.\\n\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n            return\n\n\n\n\n    def onTemDataRelatorioChanged(self):\n\n        if self.coc15TemDataRelat.isChecked():\n\n            self.dtoc15DataPublicRelat.setEnabled(True)\n        else:\n            self.dtoc15DataPublicRelat.setDateTime(QtCore.QDateTime.currentDateTime())\n            self.dtoc15DataPublicRelat.setEnabled(False)\n\n    def onRelatorioPublicadoChanged(self):\n\n        if self.coc14RelatPublOco.isChecked():\n\n            self.toc13NumRelatOco.setEnabled(True)\n            self.groupBoxPublicacao.setEnabled(True)\n\n        else:\n            self.toc13NumRelatOco.setText(\"\")\n            self.toc13NumRelatOco.setEnabled(False)\n            self.coc15TemDataRelat.setChecked(False)\n            self.groupBoxPublicacao.setEnabled(False)\n\n\n    def onRegistrarRegOcoClicked(self):\n\n        # Mandou registrar os dados em Ocorrencia\n        # Checar se ID ja existe\n        id = self.toc0CodOco.displayText()\n        dados = mainFunctions.getInfoID(id, 'Trie.bin')\n\n        if id == \"\":\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"Campo Obrigatório Vazio\")\n            msg.setText(\"Preencha o código identificador da ocorrência.\\n\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n            return\n\n        if dados != -1:  # se não retornou -1, então já existe.\n\n            yn = QtWidgets.QMessageBox.question(self, 'Atualizar dados?',\n                                                \"Já existe registro para o código identificador especificado.\\n\"\n                                                \"Deseja sobrescrevê-lo com os novos dados informados?\\n\"\n                                                \"(NOTA: Esta ação é irreversível! Os dados correntes serão permanentemente descartados)\",\n                                                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n            if yn == QtWidgets.QMessageBox.No:\n                pass\n            else:\n                self.dadosOcoLista, self.dadosOcoStringFinal = self.novaStringOcorrencia()\n\n                ret = mainFunctions.updateOcoWithDataString(id,'Trie.bin', self.dadosOcoLista)\n                if ret == -1:\n                    msg = QtWidgets.QMessageBox()\n                    msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                    msg.setWindowTitle(\"Erro de atualização\")\n                    msg.setText(\"Não foi possível atualizar o registro da ocorrência especificada no banco de dados.\\n\")\n                    msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                    msg.exec()\n                    return\n                else:\n                    msg = QtWidgets.QMessageBox()\n                    msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                    msg.setWindowTitle(\"Atualização bem sucedida\")\n                    msg.setText(\"Registro de ocorrência atualizado com sucesso.\\n\")\n                    msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                    msg.exec()\n                    return\n\n        else: # nao existe essa ID; fazer uma nova sem perguntas\n            self.dadosOcoLista, self.dadosOcoStringFinal = self.novaStringOcorrencia()\n            ret = mainFunctions.addOcoData(self.dadosOcoLista,'Trie.bin')\n\n            if ret == -1:\n\n                msg = QtWidgets.QMessageBox()\n                msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                msg.setWindowTitle(\"Erro de inserção\")\n                msg.setText(\"Não foi possível inserir a nova ocorrência no banco de dados.\\n\")\n                msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                msg.exec()\n                return\n\n            else:\n                msg = QtWidgets.QMessageBox()\n                msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                msg.setWindowTitle(\"Inserção bem-sucedida\")\n                msg.setText(\"Nova ocorrência registrada com sucesso.\\n\")\n                msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                msg.exec()\n\n\n    def onRegistrarRegAeroClicked(self):\n\n        # Mandou registrar os dados em Aeronave\n        # Checar se ID e Matricula de Aeronave ja existem nos registros\n        id = self.tae0CodOco.displayText()\n        matr = self.tae1Matricula.displayText().upper()\n        dados = mainFunctions.getInfoID(id, 'Trie.bin')\n\n        if id == \"\":\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"Campo Obrigatório Vazio\")\n            msg.setText(\"Preencha o código identificador da ocorrência associada à aeronave.\\n\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n            return\n        elif matr == \"\":\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"Campo Obrigatório Vazio\")\n            msg.setText(\"Preencha a matrícula de identificação da aeronave.\\n\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n            return\n\n        if dados != -1:  # se não retornou -1, então já existe ocorrencia. Checar se existe matricula\n            achouIndex = -1\n            for i in range(1,len(dados)):\n                if dados[i][1] == matr:\n                    achouIndex = i\n\n            if achouIndex != -1: # achou aeronave com mesmo ID de ocorrencia e mesma matricula. Alterar?\n                yn = QtWidgets.QMessageBox.question(self, 'Atualizar dados?',\n                                                    \"Já existe registro para a ocorrência e aeronave com o código e matrícula especificados.\\n\"\n                                                    \"Deseja sobrescrevê-lo com os novos dados informados?\\n\"\n                                                    \"(NOTA: Esta ação é irreversível! Os dados correntes serão permanentemente descartados)\",\n                                                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n                if yn == QtWidgets.QMessageBox.No:\n                    pass\n                else:\n                    self.dadosAeroLista, self.dadosAeroStringFinal = self.novaStringAeronave()\n                    ret = mainFunctions.updateAnvWithDataString(id, matr, 'Trie.bin', self.dadosAeroLista)\n                    if ret == -1:\n                        msg = QtWidgets.QMessageBox()\n                        msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                        msg.setWindowTitle(\"Erro de atualização\")\n                        msg.setText(\"Não foi possível atualizar os dados da aeronave especificada no banco de dados.\\n\")\n                        msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                        msg.exec()\n                        return\n                    else:\n                        msg = QtWidgets.QMessageBox()\n                        msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                        msg.setWindowTitle(\"Atualização bem sucedida\")\n                        msg.setText(\"Registro de aeronave atualizado com sucesso.\\n\")\n                        msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                        msg.exec()\n                        return\n\n\n            else: #nao achou esta aeronave registrada para este ID. Inserir sem perguntas\n                self.dadosAeroLista, self.dadosAeroStringFinal = self.novaStringAeronave()\n                ret = mainFunctions.addAeroData([self.dadosAeroLista], 'Trie.bin')\n\n                if ret == -1:\n                    msg = QtWidgets.QMessageBox()\n                    msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                    msg.setWindowTitle(\"Erro de inserção\")\n                    msg.setText(\"Não foi possível inserir o novo registro de aeronave no banco de dados.\\n\")\n                    msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                    msg.exec()\n                    return\n                else:\n                    msg = QtWidgets.QMessageBox()\n                    msg.setIcon(QtWidgets.QMessageBox.Information)\n\n                    msg.setWindowTitle(\"Inserção bem sucedida\")\n                    msg.setText(\"Novo registro de aeronave inserido com sucesso.\\n\")\n                    msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n                    msg.exec()\n                    return\n\n        else:  # nao existe essa ID; não pode registrar aeronave ainda\n            msg = QtWidgets.QMessageBox()\n            msg.setIcon(QtWidgets.QMessageBox.Information)\n\n            msg.setWindowTitle(\"404 - ID not found\")\n            msg.setText(\"ID não encontrado.\\n\\nÉ necessário registrar a ocorrência antes de acrescentar dados de aeronaves envolvidas ao banco de dados.\")\n            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n            msg.exec()\n\n\n    def novaStringOcorrencia(self):\n\n        #self.textRegOco = [self.toc0CodOco, self.toc2TipoOco, self.toc3LatitudeOco, self.toc4LongitudeOco,\n        #                   self.toc5CidadeOco, self.toc8AerodromeOco, self.toc13NumRelatOco, self.toc16Recomend]\n\n        sep = '\"~\"'\n        empty = '***'\n        stringElements = []\n\n        stringElements.append(self.toc0CodOco.displayText())   #0\n\n        stringElements.append(self.doc1Classif.currentText().upper())\n\n        for i in range(1,5): #2,3,4,5\n            input = self.textRegOco[i].displayText()\n            if input == \"\":\n                stringElements.append(empty)\n            else:\n                stringElements.append(self.textRegOco[i].displayText().upper())\n\n        stringElements.append(self.doc6EstadoOco.currentText()) #6\n        stringElements.append('BRASIL') #7\n\n        if self.toc8AerodromeOco.displayText() == \"\":  #8\n            stringElements.append(empty)\n        else:\n            stringElements.append(self.toc8AerodromeOco.displayText().upper())\n\n        dia = self.dtoc910DataHoraOco.date().toPyDate()\n        hora = self.dtoc910DataHoraOco.time().toPyTime()\n        stringElements.append(str(dia)) # 9\n        stringElements.append(str(hora)) #10\n        stringElements.append('NULL') #11\n\n        if self.coc12StatusInvestOco.isChecked(): #12\n            stringElements.append('ATIVA')\n        else:\n            stringElements.append('FINALIZADA')\n\n        if self.coc14RelatPublOco.isChecked():\n            #SIM para relatorio. Checa se tem codigo de relatorio:\n            if self.toc13NumRelatOco == \"\":\n                stringElements.append('A DEFINIR') #13\n            else:\n                stringElements.append(self.toc13NumRelatOco.displayText().upper()) #13\n\n            stringElements.append('SIM') #14\n\n        else:\n            stringElements.append(empty)#13\n            stringElements.append('NÃO')#14\n\n        if self.coc15TemDataRelat.isChecked():\n            stringElements.append(str(self.dtoc15DataPublicRelat.date().toPyDate())) #15\n        else:\n            stringElements.append('NULL') #15\n\n        stringElements.append(self.toc16Recomend.displayText())\n        stringElements.append(str(self.soc17NumAeronavesEnv.value()))\n\n        if self.coc18SaidaPistaOco.isChecked():\n            stringElements.append('SIM')\n        else:\n            stringElements.append('NÃO')\n\n        stringElements.append(str(QtCore.QDate.currentDate().toPyDate()))\n        stringFinal = sep.join(stringElements)\n\n        return( stringElements, stringFinal)\n\n        # codigo_ocorrencia\"~\"ocorrencia_classificacao\"~\"ocorrencia_tipo\"~\"ocorrencia_latitude\"~\"ocorrencia_longitude\"~\n        # \"ocorrencia_cidade\"~\"ocorrencia_uf\"~\"ocorrencia_pais\"~\"ocorrencia_aerodromo\"~\"ocorrencia_dia\"~\"ocorrencia_horario\"~\n        # \"investigacao_aeronave_liberada\"~\"investigacao_status\"~\"divulgacao_relatorio_numero\"~\"divulgacao_relatorio_publicado\"~\n        # \"divulgacao_dia_publicacao\"~\"total_recomendacoes\"~\"total_aeronaves_envolvidas\"~\"ocorrencia_saida_pista\"~\n        # \"ocorrencia_dia_extracao\n\n    def novaStringAeronave(self):\n\n        # self.textRegAero = [self.tae0CodOco, self.tae1Matricula, self.tae2CategOperador,\n        #                    self.tae3TipoAero, self.tae4Fabricante, self.tae5Modelo, self.tae6TipoICAO,\n        #                    self.tae7TipoMotor, self.tae8QtdMotores, self.tae9PesoMax, self.tae11NumAssentos,\n        #                    self.tae13PaisFabric, self.tae14PaisRegistro, self.tae15RegCategoria, self.tae16RegSegmento,\n        #                    self.tae17VooOrigem, self.tae18VooDestino, self.tae19FaseOperacao, self.tae20TipoOperacao,\n        #                    self.tae22Fatalidades]\n\n        sep = '\"~\"'\n        empty = '***'\n        stringElements = []\n\n        for i in range(10):\n            textinput = self.textRegAero[i].displayText().upper()\n            if textinput == \"\":\n                stringElements.append(empty)\n            else:\n                stringElements.append(textinput)\n\n        #10, 11, 12\n        stringElements.append(self.dae10CategPesoMax.currentText().upper())\n        stringElements.append(self.tae11NumAssentos.displayText())\n        stringElements.append(str(self.dt12AnoFabric.date().year()))\n\n        for i in range(11,19):\n            textinput = self.textRegAero[i].displayText().upper()\n            if textinput == \"\":\n                stringElements.append(empty)\n            else:\n                stringElements.append(textinput)\n\n        stringElements.append(self.dae21DanoAeronave.currentText().upper())\n        stringElements.append(self.tae22Fatalidades.displayText())\n        stringElements.append(str(QtCore.QDate.currentDate().toPyDate()))\n\n        stringFinal = sep.join(stringElements)\n        return (stringElements, stringFinal)\n\n        #codigo_ocorrencia\"~\"aeronave_matricula\"~\"aeronave_operador_categoria\"~\"aeronave_tipo_veiculo\"~\n        # \"aeronave_fabricante\"~\"aeronave_modelo\"~\"aeronave_tipo_icao\"~\"aeronave_motor_tipo\"~\n        # \"aeronave_motor_quantidade\"~\"aeronave_pmd\"~\"aeronave_pmd_categoria\"~\"aeronave_assentos\"~\n        # \"aeronave_ano_fabricacao\"~\"aeronave_pais_fabricante\"~\"aeronave_pais_registro\"~\"aeronave_registro_categoria\"~\n        # \"aeronave_registro_segmento\"~\"aeronave_voo_origem\"~\"aeronave_voo_destino\"~\n        # \"aeronave_fase_operacao\"~\"aeronave_tipo_operacao\"~\"aeronave_nivel_dano\"~\n        # \"total_fatalidades\"~\"aeronave_dia_extracao\n\n    def onLimparRegOcoClicked(self):\n\n        for v in self.textRegOco:\n            v.setText(\"\")\n\n        self.doc6EstadoOco.setCurrentIndex(0)\n        self.soc17NumAeronavesEnv.setValue(1)\n\n        self.coc12StatusInvestOco.setChecked(False)\n        self.coc14RelatPublOco.setChecked(False)\n        self.coc15TemDataRelat.setChecked(False)\n        self.coc18SaidaPistaOco.setChecked(False)\n\n        self.doc1Classif.setCurrentIndex(0)\n\n        self.dtoc15DataPublicRelat.setDateTime(self.dtoc15DataPublicRelat.dateTime().currentDateTime())\n        self.dtoc910DataHoraOco.setDateTime(self.dtoc910DataHoraOco.dateTime().currentDateTime())\n\n\n    def onLimparRegAeroClicked(self):\n        for v in self.textRegAero:\n            v.setText(\"\")\n\n        self.dt12AnoFabric.setDate(QtCore.QDate(2000,1,1))\n        self.dae10CategPesoMax.setCurrentIndex(0)\n        self.dae21DanoAeronave.setCurrentIndex(0)\n\n\n\n    def shutDown(self):\n\n        yn = QtWidgets.QMessageBox.question(self, 'Sair',\n        \"Deseja mesmo sair do airsort?\", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)\n        if yn == QtWidgets.QMessageBox.Yes:\n            print(\"Shutting down :<\")\n            sys.exit()\n        else:\n            pass\n\n    def aboutWindow(self):\n        msg = QtWidgets.QMessageBox()\n        msg.setIcon(QtWidgets.QMessageBox.Information)\n\n        msg.setWindowTitle(\"Sobre airsort\")\n        msg.setText(\"airsort, Inc. 2017-2018\\nInstituto de Informatica, UFRGS\\n\")\n        msg.setInformativeText(\"Developed by Arthur Endres Balbao, Giovane Alves Fonseca & Giovanna Lazzari Miotto.\")\n\n        msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n\n        msg.exec()\n\n\n\n\ndef main():\n    app = QtWidgets.QApplication(sys.argv)  # nova app\n\n    # traducao de standard messages para a lingua local\n    translator = QtCore.QTranslator(app)\n    localeQT = QtCore.QLocale.system().name()\n    path = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)\n    translator.load('qtbase_%s' % localeQT, path)\n    app.installTranslator(translator)\n\n    # dark~~~ stylesheet\n    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n\n\n    form = MainWIndow()\n\n    #override the overrides ^^\n    view = QtWidgets.QListView()  # create a ListView\n    view.setFixedWidth(450)  # set the ListView with fixed Width\n    #form.dropTipoOcorrencia.setView(view)  # provide the list view to Combobox object\n    form.dropFabricante.setView(view)\n    #form.dropTipoOcorrencia.setFixedHeight(24)\n    #form.dropTipoOcorrencia.setFixedWidth(271)\n    form.doc1Classif.setFixedHeight(24)\n    form.doc1Classif.setFixedWidth(133)\n    form.dae21DanoAeronave.setFixedHeight(24)\n    form.dae21DanoAeronave.setFixedWidth(113)\n    form.dae10CategPesoMax.setFixedHeight(24)\n    form.dae10CategPesoMax.setFixedWidth(113)\n    form.dropCidade.setFixedHeight(24)\n    form.dropCidade.setFixedWidth(211)\n\n\n    form.show() # mostra a janelera\n    sys.exit(app.exec_())  # executa o app\n\n\nif __name__ == '__main__':  # if we're running file directly and not importing it\n    main()\n","sub_path":"airtest.py","file_name":"airtest.py","file_ext":"py","file_size_in_byte":50349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"434294087","text":"import can\nimport pickle\nimport codecs\nimport time\nimport sys\nfrom Crypto.Cipher import DES3\n\nbus = can.interface.Bus(channel='can0', bustype='socketcan_native')\nfirstmsg = b'start'\nlastmsg = b'end'\ntext = sys.argv[1]\n\nkey = \"sixteen byte key\"\nprint(\"The Triple DES key value :\",key )\ncipher = DES3.new(key, DES3.MODE_ECB) # or 24-byte key\nprint(\"The plain text entered is    :\",text)\n\n\nstart = time.time()\n\nplain = bytearray(sys.argv[1],'utf-8');\nencrypted = cipher.encrypt(plain)\nencrypt = codecs.encode(encrypted,'hex')\nprint(\"The encrypted text in hex is :\",encrypt)\n\nmsg1 = can.Message(arbitration_id=0x231,data= firstmsg)\nbus.send(msg1)\n\n\nmsg = can.Message(arbitration_id=0x123,data= encrypted)\nbus.send(msg)\n    \nend = time.time()\nmsg2 = can.Message(arbitration_id=0x231,data = lastmsg)\nbus.send(msg2)\nTimeTaken = end - start\nprint(\"The time elapsed to encrypt & send '{0}' message : {1} \".format(sys.argv[1],TimeTaken))\n","sub_path":"DES3_Encrypt_Send_single.py","file_name":"DES3_Encrypt_Send_single.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"633969262","text":"from fastapi import Depends, Security, APIRouter\nimport sqlalchemy as sa\nfrom ..dependencies import authenticated, get_session, AsyncSession\nfrom .. import models, schemas, constants\n\nrouter = APIRouter(prefix='/2/movies/{movie_id}/watched')\n\n@router.get('', response_model=schemas.Movie_watched)\nasync def get_watched(\n    movie_id: int,\n    session: AsyncSession = Depends(get_session),\n    user: schemas.User_authenticated = Security(authenticated, scopes=[str(constants.LEVEL_PROGRESS)]),\n):\n    w = await session.scalar(sa.select(models.Movie_watched).where(\n        models.Movie_watched.user_id == user.id,\n        models.Movie_watched.movie_id == movie_id,\n    ))\n    return schemas.Movie_watched.from_orm(w) if w else schemas.Movie_watched()\n\n\n@router.post('', response_model=schemas.Movie_watched)\nasync def watched_increment(\n    movie_id: int,\n    request: dict | None = None,\n    user: schemas.User_authenticated = Security(authenticated, scopes=[str(constants.LEVEL_PROGRESS)]),\n):  \n    data = schemas.Movie_watched_increment.parse_obj(request) if request else schemas.Movie_watched_increment()\n    w = await models.Movie_watched.increment(\n        user_id=user.id,\n        movie_id=movie_id,\n        data=data,\n    )\n    return w if w else schemas.Movie_watched()\n\n\n@router.delete('', response_model=schemas.Movie_watched)\nasync def watched_decrement(\n    movie_id: int,\n    user: schemas.User_authenticated = Security(authenticated, scopes=[str(constants.LEVEL_USER)]),    \n):\n    w = await models.Movie_watched.decrement(\n        user_id=user.id,\n        movie_id=movie_id,\n    )\n    return w if w else schemas.Movie_watched()","sub_path":"seplis/api/routes/movie_watched.py","file_name":"movie_watched.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"625496310","text":"import sys\nimport csv\nimport numpy as np\nData = []\nlabel = []\nwith open(sys.argv[1], 'r') as f:\n\tfcsv = csv.reader(f)\n\tnext(fcsv)\n\tfor row in fcsv:\n\t\tData.append(row)\nData = np.array(Data, dtype=float)\nwith open(sys.argv[2], 'r') as f:\n\tfcsv = csv.reader(f)\n\tfor row in fcsv:\n\t\tlabel.append(row[0])\nlabel = np.array(label, dtype=float)\n\nclass1 = []\nclass2 = []\nn1 = 0\nn2 = 0\n\nfor i in range(Data.shape[0]):\n\tif label[i] == 1:\n\t\tclass1.append(list(Data[i]))\n\t\tn1 += 1\n\tif label[i] == 0:\n\t\tclass2.append(list(Data[i]))\n\t\tn2 += 1\n\nclass1 = np.array(class1, dtype=float).T\nclass2 = np.array(class2, dtype=float).T\n\nu1 = np.zeros(106)\nfor i in range(106):\n\tu1[i] = class1[i].mean()\nu2 = np.zeros(106)\nfor i in range(106):\n\tu2[i] = class2[i].mean()\n\nsigma1 = np.zeros((106, 106))\nsigma2 = np.zeros((106, 106))\n\nclass1 = class1.T\nclass2 = class2.T\n\nfor i in range((class1.shape)[0]):\n\ttmp = class1[i] - u1\n\tsigma1 = sigma1 + tmp.reshape(106,1).dot(tmp.reshape(1,106))\n\nfor i in range((class2.shape)[0]):\n\ttmp = class2[i] - u2\n\tsigma2 = sigma2 + tmp.reshape(106,1).dot(tmp.reshape(1,106))\n\nsigma = (n1 * sigma1 + n2 * sigma2) / (n1 + n2)\n\nw = (u1 - u2).dot(np.linalg.inv(sigma))\nb = 0.5*(((u2.reshape(1,106)).dot(np.linalg.inv(sigma)))).dot(u2.reshape(106,1)) - 0.5*(((u1.reshape(1,106)).dot(np.linalg.inv(sigma)))).dot(u1.reshape(106,1))\nb = b[0,0] + np.log(n1/n2)\n\ncnt = 0\nfor i in range(32561):\n\tk = Data[i].dot(w) + b\n\tk = 1 / (1 + np.exp(-k))\n\tif(k > 0.5 and label[i] == 1):\n\t\tcnt = cnt + 1\n\telif(k <= 0.5 and label[i] == 0):\n\t\tcnt = cnt + 1\n\nfile = open(sys.argv[4], 'w')\nfile.write(\"id,label\\n\")\n\ncnt = 1\n\nwith open(sys.argv[3], 'r') as f:\n\tfcsv = csv.reader(f)\n\tnext(fcsv)\n\tfor row in fcsv:\n\t\ttmp = np.array(row, dtype=float)\n\t\tif( 1/(1+np.exp(-(tmp.T.dot(w) + b))) > 0.5 ):\n\t\t\tfile.write('%d,1\\n' % cnt)\n\t\telse:\n\t\t\tfile.write('%d,0\\n' % cnt)\n\t\tcnt = cnt + 1\n\nfile.close()\n","sub_path":"hw2/generative.py","file_name":"generative.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"234569501","text":"#!/usr/bin/env python3\n### input './print list' to show the numbers and names of all parameters\n\nimport os,re,sys,copy\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# functions===============================================\ndef input(data):\n    d=[]\n    for line in open(data,'r').readlines():\n        c=[]\n        for i in (line.rstrip('\\n').rstrip('\\t')).split('\\t'):\n            c.extend(i.split(':'))\n        d.append(c)\n    return np.asarray(d)\n\nclass GetData:\n    def __init__(self,data):\n        a=input(data)\n        self.name=a[0,1::2].tolist()\n        self.par=a[:,2::2].astype(float)\n        self.number=a[:,0].astype(int)\n    def Add(self,data):\n        a=input(data)\n        if len(self.number)==len(a[:,0].astype(int)):\n            self.name.extend(a[0,1::2].tolist())\n            self.par=np.hstack((self.par,a[:,2::2].astype(float)))\n        else:\n            print('check the line number')\n            exit()\n#=========================================================\n\n#------------------ read data file  --------------------\npar=GetData('AllParameters.txt')\npar.Add('Ft.txt')\nparlist=[par]   # add all parameter arrays here\nif len(sys.argv)>1:\n    if sys.argv[1]=='list':\n        for p in parlist:\n            print('*'*20)\n            for i in range(len(p.name)):\n                print(i,p.name[i])\n        exit()\n\n#print(par.name)\n#print(par.par)\n#print(par.number)\n# Reduce ============================================\n","sub_path":"ScanCraft/Script/plot/plot_np.py","file_name":"plot_np.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"420704623","text":"from django.db import models\nfrom django.urls import reverse\nfrom django.contrib.auth.models import AbstractUser, UserManager\n\n\nclass User(AbstractUser):\n    \"\"\"\n    Default user cmpirque.\n    \"\"\"\n\n    class Meta:\n        verbose_name = \"user\"\n        verbose_name_plural = \"users\"\n\n    objects = UserManager()\n\n    def __str__(self):\n        is_admin = \" (admin)\" if self.is_superuser else \"\"\n        return f\"{self.username}{is_admin}\"\n\n    def get_absolute_url(self):\n        return reverse(\"users:detail\", kwargs={\"username\": self.username})\n","sub_path":"cmpirque/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"52347050","text":"import logging\nimport re\nfrom decimal import Decimal\n\nfrom celery.exceptions import MaxRetriesExceededError\nfrom django.conf import settings\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.utils.translation import gettext, gettext_noop\nfrom django_scopes import scope, scopes_disabled\n\nfrom pretix.base.email import get_email_context\nfrom pretix.base.i18n import language\nfrom pretix.base.models import Event, Order, OrderPayment, Organizer, Quota\nfrom pretix.base.payment import PaymentException\nfrom pretix.base.services.locking import LockTimeoutException\nfrom pretix.base.services.mail import SendMailException\nfrom pretix.base.services.orders import change_payment_provider\nfrom pretix.base.services.tasks import TransactionAwareTask\nfrom pretix.celery_app import app\n\nfrom .models import BankImportJob, BankTransaction\n\nlogger = logging.getLogger(__name__)\n\n\ndef notify_incomplete_payment(o: Order):\n    with language(o.locale):\n        email_template = o.event.settings.mail_text_order_expire_warning\n        email_context = get_email_context(event=o.event, order=o)\n        email_subject = gettext('Your order received an incomplete payment: %(code)s') % {'code': o.code}\n\n        try:\n            o.send_mail(\n                email_subject, email_template, email_context,\n                'pretix.event.order.email.expire_warning_sent'\n            )\n        except SendMailException:\n            logger.exception('Reminder email could not be sent')\n\n\ndef cancel_old_payments(order):\n    for p in order.payments.filter(\n            state__in=(OrderPayment.PAYMENT_STATE_PENDING,\n                       OrderPayment.PAYMENT_STATE_CREATED),\n            provider='banktransfer',\n    ):\n        try:\n            with transaction.atomic():\n                p.payment_provider.cancel_payment(p)\n                order.log_action('pretix.event.order.payment.canceled', {\n                    'local_id': p.local_id,\n                    'provider': p.provider,\n                })\n        except PaymentException as e:\n            order.log_action(\n                'pretix.event.order.payment.canceled.failed',\n                {\n                    'local_id': p.local_id,\n                    'provider': p.provider,\n                    'error': str(e)\n                },\n            )\n\n\n@transaction.atomic\ndef _handle_transaction(trans: BankTransaction, code: str, event: Event=None, organizer: Organizer=None,\n                        slug: str=None):\n    if event:\n        try:\n            trans.order = event.orders.get(code=code)\n        except Order.DoesNotExist:\n            normalized_code = Order.normalize_code(code)\n            try:\n                trans.order = event.orders.get(code=normalized_code)\n            except Order.DoesNotExist:\n                trans.state = BankTransaction.STATE_NOMATCH\n                trans.save()\n                return\n    else:\n        qs = Order.objects.filter(event__organizer=organizer)\n        if slug:\n            qs = qs.filter(event__slug__iexact=slug)\n        try:\n            trans.order = qs.get(code=code)\n        except Order.DoesNotExist:\n            normalized_code = Order.normalize_code(code)\n            try:\n                trans.order = qs.get(code=normalized_code)\n            except Order.DoesNotExist:\n                trans.state = BankTransaction.STATE_NOMATCH\n                trans.save()\n                return\n\n    if trans.order.status == Order.STATUS_PAID and trans.order.pending_sum <= Decimal('0.00'):\n        trans.state = BankTransaction.STATE_DUPLICATE\n    elif trans.order.status == Order.STATUS_CANCELED:\n        trans.state = BankTransaction.STATE_ERROR\n        trans.message = gettext_noop('The order has already been canceled.')\n    else:\n        try:\n            p, created = trans.order.payments.get_or_create(\n                amount=trans.amount,\n                provider='banktransfer',\n                state__in=(OrderPayment.PAYMENT_STATE_CREATED, OrderPayment.PAYMENT_STATE_PENDING),\n                defaults={\n                    'state': OrderPayment.PAYMENT_STATE_CREATED,\n                }\n            )\n        except OrderPayment.MultipleObjectsReturned:\n            created = False\n            p = trans.order.payments.filter(\n                amount=trans.amount,\n                provider='banktransfer',\n                state__in=(OrderPayment.PAYMENT_STATE_CREATED, OrderPayment.PAYMENT_STATE_PENDING),\n            ).last()\n\n        p.info_data = {\n            'reference': trans.reference,\n            'date': trans.date,\n            'payer': trans.payer,\n            'trans_id': trans.pk\n        }\n\n        if created:\n            # We're perform a payment method switching on-demand here\n            old_fee, new_fee, fee, p = change_payment_provider(trans.order, p.payment_provider, p.amount,\n                                                               new_payment=p, create_log=False)  # noqa\n            if fee:\n                p.fee = fee\n                p.save(update_fields=['fee'])\n\n        try:\n            p.confirm()\n        except Quota.QuotaExceededException:\n            trans.state = BankTransaction.STATE_VALID\n            cancel_old_payments(trans.order)\n        except SendMailException:\n            trans.state = BankTransaction.STATE_VALID\n            cancel_old_payments(trans.order)\n        else:\n            trans.state = BankTransaction.STATE_VALID\n            cancel_old_payments(trans.order)\n\n            o = trans.order\n            o.refresh_from_db()\n            if o.pending_sum > Decimal('0.00') and o.status == Order.STATUS_PENDING:\n                notify_incomplete_payment(o)\n\n    trans.save()\n\n\ndef _get_unknown_transactions(job: BankImportJob, data: list, event: Event=None, organizer: Organizer=None):\n    amount_pattern = re.compile(\"[^0-9.-]\")\n    known_checksums = set(t['checksum'] for t in BankTransaction.objects.filter(\n        Q(event=event) if event else Q(organizer=organizer)\n    ).values('checksum'))\n\n    transactions = []\n    for row in data:\n        amount = row['amount']\n        if not isinstance(amount, Decimal):\n            if ',' in amount and '.' in amount:\n                # Handle thousand-seperator , or .\n                if amount.find(',') < amount.find('.'):\n                    amount = amount.replace(',', '')\n                else:\n                    amount = amount.replace('.', '')\n            amount = amount_pattern.sub(\"\", amount.replace(',', '.'))\n            try:\n                amount = Decimal(amount)\n            except:\n                logger.exception('Could not parse amount of transaction: {}'.format(amount))\n                amount = Decimal(\"0.00\")\n\n        trans = BankTransaction(event=event, organizer=organizer, import_job=job,\n                                payer=row.get('payer', ''),\n                                reference=row['reference'],\n                                amount=amount,\n                                date=row['date'])\n        trans.checksum = trans.calculate_checksum()\n        if trans.checksum not in known_checksums:\n            trans.state = BankTransaction.STATE_UNCHECKED\n            trans.save()\n            transactions.append(trans)\n            known_checksums.add(trans.checksum)\n\n    return transactions\n\n\n@app.task(base=TransactionAwareTask, bind=True, max_retries=5, default_retry_delay=1)\ndef process_banktransfers(self, job: int, data: list) -> None:\n    with language(\"en\"):  # We'll translate error messages at display time\n        with scopes_disabled():\n            job = BankImportJob.objects.get(pk=job)\n        with scope(organizer=job.organizer or job.event.organizer):\n            job.state = BankImportJob.STATE_RUNNING\n            job.save()\n            prefixes = []\n\n            try:\n                # Delete left-over transactions from a failed run before so they can reimported\n                BankTransaction.objects.filter(state=BankTransaction.STATE_UNCHECKED, **job.owner_kwargs).delete()\n\n                transactions = _get_unknown_transactions(job, data, **job.owner_kwargs)\n\n                code_len = settings.ENTROPY['order_code']\n                if job.event:\n                    pattern = re.compile(job.event.slug.upper() + r\"[ \\-_]*([A-Z0-9]{%s})\" % code_len)\n                else:\n                    if not prefixes:\n                        prefixes = [e.slug.upper().replace(\".\", r\"\\.\").replace(\"-\", r\"[\\- ]*\")\n                                    for e in job.organizer.events.all()]\n                    pattern = re.compile(\"(%s)[ \\\\-_]*([A-Z0-9]{%s})\" % (\"|\".join(prefixes), code_len))\n\n                for trans in transactions:\n                    match = pattern.search(trans.reference.replace(\" \", \"\").replace(\"\\n\", \"\").upper())\n\n                    if match:\n                        if job.event:\n                            code = match.group(1)\n                            _handle_transaction(trans, code, event=job.event)\n                        else:\n                            slug = match.group(1)\n                            code = match.group(2)\n                            _handle_transaction(trans, code, organizer=job.organizer, slug=slug)\n                    else:\n                        trans.state = BankTransaction.STATE_NOMATCH\n                        trans.save()\n            except LockTimeoutException:\n                try:\n                    self.retry()\n                except MaxRetriesExceededError:\n                    logger.exception('Maximum number of retries exceeded for task.')\n                    job.state = BankImportJob.STATE_ERROR\n                    job.save()\n            except Exception as e:\n                job.state = BankImportJob.STATE_ERROR\n                job.save()\n                raise e\n            else:\n                job.state = BankImportJob.STATE_COMPLETED\n                job.save()\n","sub_path":"src/pretix/plugins/banktransfer/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":9841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"535348192","text":"import os\nimport sys\nfrom androguard.misc import AnalyzeAPK\nfrom androguard.core.bytecodes.dvm import DalvikVMFormat\nfrom androguard.core.analysis.analysis import Analysis\nfrom androguard.core.analysis.analysis import is_ascii_obfuscation\nfrom androguard.core.bytecodes.apk import APK\nfrom androguard.core.analysis import analysis\nfrom androguard.core.bytecodes import dvm\nfrom androguard.core.analysis.analysis import ExternalMethod\nimport csv\nimport time\nfrom const import API_CALLS, PERMISSIONS, RESULT_PARAMS, DB_REGEX , API_ClASS \nfrom const2 import API_SYSTEM_COMMANDS \nfrom GroupAPI import GroupAPIChecker, APIGROUPS\n\n#инициализации определения групп API\nGroupAPI_Checker=GroupAPIChecker()\nresult_folder= \"testResult\"+\"/\"\nAPKpath = \"testAPK\" + '/'\nif not os.path.exists(result_folder):\n    os.mkdir(result_folder)\n\ndef load_file(filename):\n    with open(filename, 'rb') as text_file:\n        lines = text_file.readlines()\n    return lines\n\ndef read_system_commands(list_smali_strings, api_system_commands):\n    # System commands\n    list_system_commands = []\n    for elem in filter(None, list_smali_strings):\n        command_to_check_list = elem.split(' ')\n        for i in command_to_check_list:\n            if  i in api_system_commands:\n                list_system_commands.append(i)\n\n    return list_system_commands\n\n\ndef api_check(folder,APKname):\n    if os.path.exists(result_folder + folder + APKname + 'data/'):\n        print(APKname+\" Already scanned\")\n        return\n\n    print(\"Starting apk:\"+APKname)\n\n    apk_start_time=time.time()\n   \n\n    RESULTdict = dict.fromkeys(RESULT_PARAMS,0) \n\n##отдельные словари для фич\n    OtherDict=dict.fromkeys(('obfuscation','database'),0)\n\n    APIdict = dict.fromkeys((API_CALLS+API_ClASS),0) \n\n    permission_dict=  dict.fromkeys(PERMISSIONS,0)\n\n    strings_dict = dict.fromkeys(API_SYSTEM_COMMANDS,0)\n\n    groupAPI_dict=dict.fromkeys(APIGROUPS,0)\n##№№№\n\n\n    #a-APK d[0]-DalvikVMFormat dx-Analysis\n    try: \n        a,d,dx = AnalyzeAPK(folder+APKname)\n    except:\n        print(\" ERROR: Androguard parse error, skipping file\")\n        return\n\n###\n    temp= a.get_details_permissions()\n    temp2= a.get_declared_permissions_details()\n    temp3 = a.get_uses_implied_permission_list()\n\n# ########TODO почитать про использование пермишинсов без запросов\n\n            \n\n####\n\n    RESULTdict[\"APP_Name\"]=APKname\n    RESULTdict['folder']=folder\n    #methods = []\n\n    \n    #подозрительные строки\n    RESULTdict[\"warn_strings\"] =[]\n    strings=dx.get_strings_analysis()\n    #w=d[0].get_strings()\n    list_system_commands = read_system_commands(strings, API_SYSTEM_COMMANDS)\n    for i in list_system_commands:\n        #print(i)\n        RESULTdict[\"warn_strings\"].append(i)\n\n    for i in list_system_commands:\n        strings_dict[i]+=1\n\n\n    ### общая информация \n    RESULTdict['permissions'] = a.get_permissions()\n    RESULTdict['activities'] = a.get_activities()\n    RESULTdict['providers'] = a.get_providers()\n    RESULTdict['services'] = a.get_services()\n    RESULTdict['libraries'] = a.get_libraries()\n    RESULTdict['is_obfuscation'] = 1 if is_ascii_obfuscation(d[0]) else 0\n    RESULTdict['is_database'] = 1 if d[0].get_regex_strings(DB_REGEX) else 0\n    #TODO intents_analysis from new.py\n\n    OtherDict['obfuscation']=RESULTdict['is_obfuscation']\n    OtherDict['database']=RESULTdict['is_database']\n\n    #permissions\n    RESULTdict['warn_permissions'] =[]\n\n   #RESULTdict['feature_vectors']['permissions'] = []\n    for permission in PERMISSIONS:\n\n        if permission in RESULTdict['permissions']:\n            RESULTdict['warn_permissions'].append(permission) \n            permission_dict[permission]=1\n\n\n###########################################################################\n#TODO подсчет групп АПИ и системных команд для вектора фич\n###########################################################################\n\n    #API \n    RESULTdict['API_groups']=[]\n    external_classes = dx.get_external_classes()\n    for i in external_classes:\n        class_name = i.get_vm_class()\n        methods_list = class_name.get_methods()\n        for method in methods_list:\n            a = '%s' % method.get_class_name().replace(';','')\n            b = '%s' % method.get_name()\n            c = '%s' % method.get_descriptor()\n            #TODO permission_api_name https://androguard.readthedocs.io/en/latest/api/androguard.core.analysis.html?highlight=permission#androguard.core.analysis.analysis.ExternalMethod.permission_api_name \n            if b in API_CALLS:\n                APIdict[b]+=1\n                ###TODO !!!нужна нормализация данных\n            if a in API_ClASS:\n                APIdict[a]+=1\n\n            temp=GroupAPI_Checker.checkAPIGroup(a.replace('/','.')[1:] ,b)\n            if(temp!=None):\n                groupAPI_dict[temp]+=1\n                RESULTdict['API_groups'].append(temp)\n\n##запись общих параметров\n    with open(result_folder + 'API_CALLS.csv', 'a', encoding='utf8') as csvfile:\n        fieldnames=(('APP_Name','folder')+API_CALLS+API_ClASS)\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n        #writer.writeheader()\n        tempDict=APIdict.copy()\n        tempDict['APP_Name']=APKname\n        tempDict['folder']=folder\n        writer.writerow(tempDict)\n\n    with open(result_folder + 'OtherDict.csv', 'a', encoding='utf8') as csvfile:\n        fieldnames='APP_Name','folder','obfuscation','database'\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n        #writer.writeheader()\n        tempDict=OtherDict.copy()\n        tempDict['APP_Name']=APKname\n        tempDict['folder']=folder\n        writer.writerow(tempDict)\n\n    with open(result_folder + 'permission_dict.csv', 'a', encoding='utf8') as csvfile:\n        fieldnames=('APP_Name','folder')+PERMISSIONS\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n        #writer.writeheader()\n        tempDict=permission_dict.copy()\n        tempDict['APP_Name']=APKname\n        tempDict['folder']=folder\n        writer.writerow(tempDict)\n\n    with open(result_folder + 'strings_dict.csv', 'a', encoding='utf8') as csvfile:\n        fieldnames=('APP_Name','folder')+API_SYSTEM_COMMANDS\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n        #writer.writeheader()\n        tempDict=strings_dict.copy()\n        tempDict['APP_Name']=APKname\n        tempDict['folder']=folder\n        writer.writerow(tempDict)\n\n    with open(result_folder + 'groupAPI_dict.csv', 'a', encoding='utf8') as csvfile:\n        fieldnames=('APP_Name','folder')+APIGROUPS\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n        #writer.writeheader()\n        tempDict=groupAPI_dict.copy()\n        tempDict['APP_Name']=APKname\n        tempDict['folder']=folder\n        writer.writerow(tempDict)\n  \n\n    with open(result_folder + 'RESULTdict.csv', 'a', encoding='utf8') as csvfile:\n        fieldnames=RESULT_PARAMS\n        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n        #writer.writeheader()\n        writer.writerow(RESULTdict)\n    \n##запись параметров данного приложения\n    try:\n        if os.path.exists(result_folder + folder):\n            os.mkdir(result_folder+folder+APKname+'data')\n        else:\n            os.mkdir(result_folder+folder)\n            os.mkdir(result_folder+folder+APKname+'data')\n    except OSError:\n        print (\"Создать директорию %s не удалось\" % (result_folder+folder+APKname+'data'))\n    else:\n        with open(result_folder + folder + APKname + 'data/RESULT.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=RESULT_PARAMS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n            writer.writerow(RESULTdict)\n        \n        with open(result_folder + folder + APKname + 'data/OtherDict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames='obfuscation','database'\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n            writer.writerow(OtherDict)\n\n        with open(result_folder + folder + APKname + 'data/APIdict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=API_CALLS+API_ClASS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n            writer.writerow(APIdict)\n\n        with open(result_folder + folder + APKname + 'data/permission_dict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=PERMISSIONS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n            writer.writerow(permission_dict)\n\n        with open(result_folder + folder + APKname + 'data/strings_dict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=API_SYSTEM_COMMANDS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n            writer.writerow(strings_dict)      \n\n        with open(result_folder + folder + APKname + 'data/groupAPI_dict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=APIGROUPS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n            writer.writerow(groupAPI_dict)   \n\n    print(\"APK done:{} \".format(time.time() - apk_start_time))\n\n\n\ndef main():\n    #################### main\n    start_time = time.time()\n\n        ## подготовка общих файлов\n    if not os.path.exists(result_folder + 'RESULTdict.csv'):\n        with open(result_folder + 'RESULTdict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=RESULT_PARAMS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n\n    if not os.path.exists(result_folder + 'API_CALLS.csv'):\n        with open(result_folder + 'API_CALLS.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=(('APP_Name','folder')+API_CALLS+API_ClASS)\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n\n    if not os.path.exists(result_folder + 'OtherDict.csv'):\n        with open(result_folder + 'OtherDict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames='APP_Name','folder','obfuscation','database'\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n\n    if not os.path.exists(result_folder + 'permission_dict.csv'):\n        with open(result_folder + 'permission_dict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=('APP_Name','folder')+PERMISSIONS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n\n    if not os.path.exists(result_folder + 'strings_dict.csv'):\n        with open(result_folder + 'strings_dict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=('APP_Name','folder')+API_SYSTEM_COMMANDS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n\n    if not os.path.exists(result_folder + 'groupAPI_dict.csv'):\n        with open(result_folder + 'groupAPI_dict.csv', 'w', encoding='utf8') as csvfile:\n            fieldnames=('APP_Name','folder')+APIGROUPS\n            writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter=\";\",lineterminator=\"\\n\")\n            writer.writeheader()\n\n\n\n    #проход папок с файлами\n\n    files = os.listdir(APKpath)\n\n    APKs = filter(lambda x: x.endswith(('.apk','.apkk')), files)\n    for apk in APKs:\n            api_check(APKpath,apk)\n    print(\"All DONE:{} \".format(time.time() - start_time))\n\nmain()","sub_path":"test_data_collect.py","file_name":"test_data_collect.py","file_ext":"py","file_size_in_byte":12408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"413586845","text":"from os.path import join\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom wofs.util.news_e_plotting_cbook_v2 import cb_colors as wofs\nimport sys\n\nsys.path.append(\"/home/monte.flora/machine_learning/build_model\")\nfrom ModelClarifier.class_ModelClarify import ModelClarify\nfrom ModelClarifier.plotting_routines import plot_first_order_ale\nimport waterfall_chart\nfrom MachLearn import MachLearn\nfrom wofs.util.feature_names import to_only_varname\n\n\"\"\"\nfold_to_load=None\nfname_params = {\n    \"model_name\": \"RandomForest\",\n    \"target_var\": \"matched_to_tornado_0km\",\n    \"fcst_time_idx\": \"first_hour\",\n}\n\nprint(\"Loading the data...\")\nml = MachLearn(\n    fname_params,\n    load_model=True,\n    drop_correlated_features=True,\n    fold_to_load=fold_to_load,\n)\ndata_dict = ml.data_dict\n\nresults_list = [ ]\nfor fold in range(15):\n    fold = f\"fold_{fold}\"\n    model = data_dict[fold][\"model\"]\n    data = data_dict[fold][\"data\"]\n    examples = data['training'][\"examples\"]\n    targets = data['training'][\"targets\"]\n    model_clarifier = ModelClarify(model=model, examples_in=examples, targets_in=targets)\n    result = model_clarifier.get_top_contributors()\n    results_list.append(result)\n\nfor mode in ['hits', 'misses', 'false_alarms', 'corr_negs']:\n    for var in list(results_list[0][mode].keys()):\n        result[mode][var] = {'Mean Contribution': np.mean([adict[mode][var]['Mean Contribution'] for adict in results_list])}\n\nprint(result)\n\"\"\"\n\ndef combine_like_features(contrib, varnames):\n    \"\"\"\n    \"\"\"\n    duplicate_vars = {}\n    for var in varnames:\n        duplicate_vars[var] = [idx for idx, v in enumerate(varnames) if v == var]\n\n    new_contrib = []\n    new_varnames = []\n    for var in list(duplicate_vars.keys()):\n        idxs = duplicate_vars[var]\n        new_varnames.append(var)\n        new_contrib.append(np.array(contrib)[idxs].sum())\n\n    return new_contrib, new_varnames\n\n\ndef plot_treeinterpret(result, save_name):\n    \"\"\"\n    Plot the results of tree interpret\n    \"\"\"\n    contrib = [50.0]\n    varnames = [\"bias\"]\n    for i, var in enumerate(list(result.keys())):\n        contrib.append(result[var][\"Mean Contribution\"])\n        varnames.append(to_only_varname(var))\n\n    contrib, varnames = combine_like_features(contrib, varnames)\n\n    plt = waterfall_chart.plot(\n        varnames,\n        contrib,\n        rotation_value=90,\n        sorted_value=True,\n        threshold=0.02,\n        net_label=\"Final prediction\",\n        other_label=\"Others\",\n        y_lab=\"Probability\",\n    )\n    plt.savefig(save_name, bbox_inches=\"tight\", dpi=300)\n\n\n#for mode in [\"hits\", \"misses\", \"false_alarms\", \"corr_negs\"]:\n#    plot_treeinterpret(result[mode], save_name=\"tree_interpreter_{}.png\".format(mode))\n","sub_path":"plotting/plot_tree_interpreter.py","file_name":"plot_tree_interpreter.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"91298143","text":"# Copyright 2017 Google Inc.\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\"\"\"Wrapper classes for document, token, and mention frames\"\"\"\n\nimport sling\nimport sling.pysling as api\n\n# Token break types.\nNO_BREAK = 0\nSPACE_BREAK = 1\nLINE_BREAK = 2\nSENTENCE_BREAK = 3\nPARAGRAPH_BREAK = 4\nSECTION_BREAK = 5\nCHAPTER_BREAK = 6\n\nclass DocumentSchema:\n  def __init__(self, store):\n    self.isa = store['isa']\n    self.document = store['/s/document']\n    self.document_text = store['/s/document/text']\n    self.document_tokens = store['/s/document/tokens']\n    self.document_mention = store['/s/document/mention']\n    self.document_theme = store['/s/document/theme']\n\n    self.token = store['/s/token']\n    self.token_index = store['/s/token/index']\n    self.token_text = store['/s/token/text']\n    self.token_start = store['/s/token/start']\n    self.token_length = store['/s/token/length']\n    self.token_break = store['/s/token/break']\n\n    self.phrase = store['/s/phrase']\n    self.phrase_begin = store['/s/phrase/begin']\n    self.phrase_length = store['/s/phrase/length']\n    self.phrase_evokes = store['/s/phrase/evokes']\n\n\nclass Token(object):\n  def __init__(self, schema, frame):\n    self.schema = schema\n    self.frame = frame\n\n  @property\n  def index(self):\n    return self.frame[self.schema.token_index]\n\n  @index.setter\n  def index(self, value):\n    self.frame[self.schema.token_index] = value\n\n  @property\n  def text(self):\n    return self.frame[self.schema.token_text]\n\n  @text.setter\n  def text(self, value):\n    self.frame[self.schema.token_text] = value\n\n  @property\n  def start(self):\n    return self.frame[self.schema.token_start]\n\n  @start.setter\n  def start(self, value):\n    self.frame[self.schema.token_start] = value\n\n  @property\n  def length(self):\n    l = self.frame[self.schema.token_length]\n    if l == None: l = 1\n    return l\n\n  @length.setter\n  def length(self, value):\n    self.frame[self.schema.token_length] = value\n\n  @property\n  def end(self):\n    return self.start + self.length\n\n  @property\n  def brk(self):\n    b = self.frame[self.schema.token_break]\n    if b == None: b = SPACE_BREAK\n    return b\n\n  @brk.setter\n  def brk(self, value):\n    self.frame[self.schema.token_break] = value\n\n\nclass Mention(object):\n  def __init__(self, schema, frame):\n    self.schema = schema\n    self.frame = frame\n\n  @property\n  def begin(self):\n    return self.frame[self.schema.phrase_begin]\n\n  @begin.setter\n  def begin(self, value):\n    self.frame[self.schema.phrase_begin] = value\n\n  @property\n  def length(self):\n    l = self.frame[self.schema.phrase_length]\n    if l == None: l = 1\n    return l\n\n  @length.setter\n  def length(self, value):\n    self.frame[self.schema.phrase_length] = value\n\n  @property\n  def end(self):\n    return self.begin + self.length\n\n  def evokes(self):\n    return self.frame(self.schema.phrase_evokes)\n\n  def evoke(self, evoked):\n    return self.frame.append(self.schema.phrase_evokes, evoked)\n\n\nclass Document(object):\n  def __init__(self, frame=None, store=None, schema=None):\n    # Create store, frame, and schema if missing.\n    if frame != None:\n      store = frame.store()\n    if store == None:\n      store = sling.Store()\n    if schema == None:\n      schema = DocumentSchema(store)\n    if frame == None:\n      frame = store.frame([(schema.isa, schema.document)])\n\n    # Initialize document from frame.\n    self.frame = frame\n    self.schema = schema\n    self.tokens = []\n    self.mentions = []\n    self.themes = []\n    self.tokens_dirty = False\n    self.mentions_dirty = False\n    self.themes_dirty = False\n\n    # Get tokens.\n    tokens = frame[schema.document_tokens]\n    if tokens != None:\n      for t in tokens:\n        token = Token(schema, t)\n        self.tokens.append(token)\n\n    # Get mentions.\n    for m in frame(schema.document_mention):\n      mention = Mention(schema, m)\n      self.mentions.append(mention)\n\n    # Get themes.\n    for theme in frame(schema.document_theme):\n      self.themes.append(theme)\n\n  def add_token(self, text=None, start=None, length=None, brk=SPACE_BREAK):\n    slots = [\n      (self.schema.isa, self.schema.token),\n      (self.schema.token_index, len(self.tokens)),\n    ]\n    if text != None: slots.append((self.schema.token_text, text))\n    if start != None: slots.append((self.schema.token_start, start))\n    if length != None: slots.append((self.schema.token_length, length))\n    if brk != SPACE_BREAK: slots.append((self.schema.token_break, brk))\n    token = Token(self.schema, self.frame.store().frame(slots))\n    self.tokens.append(token)\n    self.tokens_dirty = True\n    return token\n\n  def add_mention(self, begin, end):\n    length = end - begin\n    slots = [\n      (self.schema.isa, self.schema.phrase),\n      (self.schema.phrase_begin, begin),\n    ]\n    if length != 1: slots.append((self.schema.phrase_length, length))\n    mention = Mention(self.schema, self.frame.store().frame(slots))\n    self.mentions.append(mention)\n    self.mentions_dirty = True\n    return mention\n\n  def add_theme(self, theme):\n    self.themes.append(theme)\n    self.themes_dirty = True\n\n  def update(self):\n    # Update tokens in document frame.\n    if self.tokens_dirty:\n      array = []\n      for token in self.tokens: array.append(token.frame)\n      self.frame[self.schema.document_tokens] = array\n      self.tokens_dirty = False\n\n    # Update mentions in document frame.\n    if self.mentions_dirty:\n      slots = []\n      for mention in self.mentions:\n        slots.append((self.schema.document_mention, mention.frame))\n      del self.frame[self.schema.document_mention]\n      self.frame.extend(slots)\n      self.mentions_dirty = False\n\n    # Update themes in document frame.\n    if self.themes_dirty:\n      slots = []\n      for theme in self.themes:\n        slots.append((self.schema.document_theme, theme))\n      del self.frame[self.schema.document_theme]\n      self.frame.extend(slots)\n      self.themes_dirty = False\n\n  @property\n  def text(self):\n    return self.frame[self.schema.document_text]\n\n  @text.setter\n  def text(self, value):\n    self.frame[self.schema.document_text] = value\n\n  def phrase(self, begin, end):\n    parts = []\n    for token in self.tokens[begin:end]:\n      if len(parts) > 0 and token.brk != NO_BREAK: parts.append(' ')\n      parts.append(token.text)\n    return ''.join(parts)\n\n  def remove_annotations(self):\n    if len(self.mentions) > 0:\n      self.mentions = []\n      self.mentions_dirty = True\n    if len(self.themes) > 0:\n      self.themes = []\n      self.themes_dirty = True\n    self.update()\n\n  def refresh_annotations(self):\n    self.mentions = []\n    for m in self.frame(self.schema.document_mention):\n      mention = Mention(self.schema, m)\n      self.mentions.append(mention)\n    self.mentions_dirty = False\n\n    self.themes = []\n    for theme in self.frame(self.schema.document_theme):\n      self.themes.append(theme)\n    self.themes_dirty = False\n\n","sub_path":"python/nlp/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":7366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"391474025","text":"\"\"\"\nProvides routes for verifying base templates and exception handling.\n\nThe blueprint instantiated here is **not** for use in a production application;\nit is not attached by :class:`arxiv.base.Base`.\n\"\"\"\n\nfrom typing import Any, Tuple, Callable, Dict\nfrom flask import Blueprint, render_template, current_app, make_response, \\\n    Response, flash, url_for\n\nfrom arxiv import status\nfrom arxiv.base.exceptions import NotFound, Forbidden, Unauthorized, \\\n    MethodNotAllowed, RequestEntityTooLarge, BadRequest, InternalServerError\n\nfrom . import messages\n\nblueprint = Blueprint('ui', __name__, url_prefix='')\n\n\n@blueprint.route('/styleguide', methods=['GET'])\ndef test_page() -> Response:\n    \"\"\"Render the test page.\"\"\"\n    rendered = render_template(\"base/styleguide.html\", pagetitle='Home')\n    response = make_response(rendered, status.HTTP_200_OK)\n\n    # Demonstrate flash messages. To see these messages, reload the page.\n    help_url = url_for('help')\n    messages.flash_warning(f'This is a warning, see the'\n                           f' docs for more information',\n                           title='Warning title', safe=True)\n    messages.flash_info('This is some info', title='Info title')\n    messages.flash_failure('This is a failure', title='Failure title')\n    messages.flash_success('This is a success', title='Success title')\n    messages.flash_warning('This is a warning that cannot be dismissed',\n                           dismissable=False)\n    return response\n\n\n@blueprint.route('/404', methods=['GET'])\ndef test_404() -> Response:\n    \"\"\"Test the 404 error page.\"\"\"\n    raise NotFound()\n\n\n@blueprint.route('/403', methods=['GET'])\ndef test_403() -> Response:\n    \"\"\"Test the 403 error page.\"\"\"\n    raise Forbidden()\n\n\n@blueprint.route('/401', methods=['GET'])\ndef test_401() -> Response:\n    \"\"\"Test the 401 error page.\"\"\"\n    raise Unauthorized()\n\n\n@blueprint.route('/405', methods=['GET'])\ndef test_405() -> Response:\n    \"\"\"Test the 405 error page.\"\"\"\n    raise MethodNotAllowed()\n\n\n@blueprint.route('/413', methods=['GET'])\ndef test_413() -> Response:\n    \"\"\"Test the 413 error page.\"\"\"\n    raise RequestEntityTooLarge()\n\n\n@blueprint.route('/400', methods=['GET'])\ndef test_400() -> Response:\n    \"\"\"Test the 400 error page.\"\"\"\n    raise BadRequest()\n\n\n@blueprint.route('/500', methods=['GET'])\ndef test_500() -> Response:\n    \"\"\"Test the 500 error page.\"\"\"\n    raise InternalServerError()\n","sub_path":"arxiv/base/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"314860996","text":"import  socket\n\ns = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\ns.sendto('早上好'.encode('utf8'),('127.0.0.1',9090))\n\n#data 的数据类型是一个元组\n#元组的第0个元素是接收到的元组\n#元组里第1个元素是发送方的ip地址和端口号\ndata = s.recvfrom(1024)\nprint(data)\n\ns.close()","sub_path":"17.多进程多线程/02.多线程聊天.py","file_name":"02.多线程聊天.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"287636629","text":"#!/usr/bin/python\n\n# Copyright (c) 2009 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n# action_makenames.py is a harness script to connect actions sections of\n# gyp-based builds to make_names.pl.\n#\n# usage: action_makenames.py OUTPUTS -- INPUTS [-- OPTIONS]\n#\n# Multiple OUTPUTS, INPUTS, and OPTIONS may be listed.  The sections are\n# separated by -- arguments.\n#\n# The directory name of the first output is chosen as the directory in which\n# make_names will run.  If the directory name for any subsequent output is\n# different, those files will be moved to the desired directory.\n#\n# Multiple INPUTS may be listed.  An input with a basename matching\n# \"make_names.pl\" is taken as the path to that script.  Inputs with names\n# ending in TagNames.in or tags.in are taken as tag inputs.  Inputs with names\n# ending in AttributeNames.in or attrs.in are taken as attribute inputs.  There\n# may be at most one tag input and one attribute input.  A make_names.pl input\n# is required and at least one tag or attribute input must be present.\n#\n# OPTIONS is a list of additional options to pass to make_names.pl.  This\n# section need not be present.\n\n\nimport os\nimport posixpath\nimport shutil\nimport subprocess\nimport sys\n\n\ndef SplitArgsIntoSections(args):\n  sections = []\n  while len(args) > 0:\n    if not '--' in args:\n      # If there is no '--' left, everything remaining is an entire section.\n      dashes = len(args)\n    else:\n      dashes = args.index('--')\n\n    sections.append(args[:dashes])\n\n    # Next time through the loop, look at everything after this '--'.\n    if dashes + 1 == len(args):\n      # If the '--' is at the end of the list, we won't come back through the\n      # loop again.  Add an empty section now corresponding to the nothingness\n      # following the final '--'.\n      args = []\n      sections.append(args)\n    else:\n      args = args[dashes + 1:]\n\n  return sections\n\n\ndef main(args):\n  sections = SplitArgsIntoSections(args[1:])\n  assert len(sections) == 2 or len(sections) == 3\n  (outputs, inputs) = sections[:2]\n  if len(sections) == 3:\n    options = sections[2]\n  else:\n    options = []\n\n  # Make all output pathnames absolute so that they can be accessed after\n  # changing directory.\n  for index in xrange(0, len(outputs)):\n    outputs[index] = os.path.abspath(outputs[index])\n\n  output_dir = os.path.dirname(outputs[0])\n\n  # Look at the inputs and figure out which ones are make_names.pl, tags, and\n  # attributes.  There can be at most one of each, and those are the only\n  # input types supported.  make_names.pl is required and at least one of tags\n  # and attributes is required.\n  make_names_input = None\n  tag_input = None\n  attr_input = None\n  for input in inputs:\n    # Make input pathnames absolute so they can be accessed after changing\n    # directory.  On Windows, convert \\ to / for inputs to the perl script to\n    # work around the intermix of activepython + cygwin perl.\n    input_abs = os.path.abspath(input)\n    input_abs_posix = input_abs.replace(os.path.sep, posixpath.sep)\n    input_basename = os.path.basename(input)\n    if input_basename == 'make_names.pl':\n      assert make_names_input == None\n      make_names_input = input_abs\n    elif input_basename.endswith('TagNames.in') or \\\n         input_basename.endswith('tags.in'):\n      assert tag_input == None\n      tag_input = input_abs_posix\n    elif input_basename.endswith('AttributeNames.in') or \\\n         input_basename.endswith('attrs.in'):\n      assert attr_input == None\n      attr_input = input_abs_posix\n    else:\n      assert False\n\n  assert make_names_input != None\n  assert tag_input != None or attr_input != None\n\n  # scripts_path is a Perl include directory, located relative to\n  # make_names_input.\n  scripts_path = os.path.normpath(\n      os.path.join(os.path.dirname(make_names_input), os.pardir,\n                   'bindings', 'scripts'))\n\n  # Change to the output directory because make_names.pl puts output in its\n  # working directory.\n  os.chdir(output_dir)\n\n  # Build up the command.\n  command = ['perl', '-I', scripts_path, make_names_input]\n  if tag_input != None:\n    command.extend(['--tags', tag_input])\n  if attr_input != None:\n    command.extend(['--attrs', attr_input])\n  command.extend(options)\n\n  # Do it.  check_call is new in 2.5, so simulate its behavior with call and\n  # assert.\n  return_code = subprocess.call(command)\n  assert return_code == 0\n\n  # Go through the outputs.  Any output that belongs in a different directory\n  # is moved.  Do a copy and delete instead of rename for maximum portability.\n  # Note that all paths used in this section are still absolute.\n  for output in outputs:\n    this_output_dir = os.path.dirname(output)\n    if this_output_dir != output_dir:\n      output_basename = os.path.basename(output)\n      src = os.path.join(output_dir, output_basename)\n      dst = os.path.join(this_output_dir, output_basename)\n      shutil.copyfile(src, dst)\n      os.unlink(src)\n\n  return return_code\n\n\nif __name__ == '__main__':\n  sys.exit(main(sys.argv))\n","sub_path":"webkit/build/action_makenames.py","file_name":"action_makenames.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"640378946","text":"\"\"\"Tests pawn piece for legal/illegal moves and captures\"\"\"\nimport pytest\nfrom helper import *\n\n\nclass Test_Pawn:\n    \"\"\"Test cases\"\"\"\n    @pytest.mark.parametrize(\"player, old_loc, piece, move, next\",\n                             [('w', 'f2', 'P', 'f3', 'b'),\n                              ('w', 'g2', 'P', 'g4', 'b'),\n                              ('b', 'e7', 'p', 'e5', 'w'),\n                              ('b', 'h7', 'p', 'h6', 'w')])\n    def test_pawn_legal_move(self, empty_board, player, old_loc, piece, move,\n                             next, result):\n        \"\"\"\n        Test all legal pawn moves from a single position for both black and\n        white players.\n        Args:\n            empty_board: MakeMove object with an empty board\n            player: Player making move\n            old_loc: Starting location of pawn piece making move\n            piece: Type of pawn to be moved\n            move: Legal move being made\n            next: Next player's turn\n            result: Response object with expected response\n\n        \"\"\"\n        # Setup API request\n        empty_board.set_player(player)\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece(old_loc, piece)\n        empty_board.set_move(move)\n\n        # Setup expected response\n        result.set_board(list(empty_board.get_board()))\n        result.set_player(next)\n        result.remove_piece(old_loc)\n        result.add_piece(move, piece)\n\n        # Print API response and compare with expected response\n        send_assert(empty_board.get_request(), result.get_response())\n\n    @pytest.mark.parametrize(\"player, move\", [('w', 'b4'),\n                                              ('w', 'c4'),\n                                              ('w', 'd4'),\n                                              ('w', 'd3'),\n                                              ('w', 'd2'),\n                                              ('w', 'c2'),\n                                              ('w', 'b2'),\n                                              ('w', 'b3'),\n                                              ('b', 'g5'),\n                                              ('b', 'f5'),\n                                              ('b', 'e5'),\n                                              ('b', 'e6'),\n                                              ('b', 'e7'),\n                                              ('b', 'f7'),\n                                              ('b', 'g7'),\n                                              ('b', 'g6')])\n    def test_pawn_illegal_move(self, empty_board, player, move,\n                               error_cant_move):\n        \"\"\"\n        Test various illegal pawn moves from a single position for both black\n        and white players.\n        Args:\n            empty_board: MakeMove objext with an empty board\n            player: Player making move\n            move: Illegal move being made\n            error_cant_move: Response objext with expected error\n\n        \"\"\"\n        empty_board.set_player(player)\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('c3', 'P')\n        empty_board.add_piece('f5', 'P')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece('f6', 'p')\n        empty_board.add_piece('c4', 'p')\n        empty_board.set_move(move)\n\n        error_cant_move.set_data(move)\n\n        send_assert(empty_board.get_request(), error_cant_move.get_response())\n\n    @pytest.mark.parametrize(\"player, old_loc, cap, move, piece, next\",\n                             [('w', 'c3', 'P', 'cxb4', 'p', 'b'),\n                              ('w', 'c3', 'P', 'cxd4', 'r', 'b'),\n                              ('w', 'c3', 'P', 'cxb4', 'n', 'b'),\n                              ('w', 'c3', 'P', 'cxd4', 'b', 'b'),\n                              ('w', 'c3', 'P', 'cxb4', 'r', 'b'),\n                              ('b', 'f6', 'p', 'fxe5', 'P', 'w'),\n                              ('b', 'f6', 'p', 'fxg5', 'R', 'w'),\n                              ('b', 'f6', 'p', 'fxe5', 'N', 'w'),\n                              ('b', 'f6', 'p', 'fxg5', 'B', 'w'),\n                              ('b', 'f6', 'p', 'fxg5', 'Q', 'w')])\n    def test_pawn_legal_capture(self, empty_board, player, old_loc, cap, move,\n                                piece, next, result):\n        \"\"\"\n        Test legal pawn captures of every type from a single position for both\n        black and white players.\n        Args:\n            empty_board: MakeMove object with an empty board\n            player: Player making move\n            old_loc: Starting location of pawn making move\n            cap: Type of pawn capturing\n            move: Legal capture being made\n            piece: Type of piece being captured\n            next: Next player's turn\n            result: Response objext with expected response\n\n        \"\"\"\n        # Setup API request\n        empty_board.set_player(player)\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('c3', 'P')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece('f6', 'p')\n        empty_board.add_piece(move[2:], piece)\n        empty_board.set_move(move)\n\n        # Setup expected response\n        result.set_board(list(empty_board.get_board()))\n        result.set_player(next)\n        result.remove_piece(move[2:])\n        result.remove_piece(old_loc)\n        result.add_piece(move[2:], cap)\n\n        # Print API response and compare with expected response\n        send_assert(empty_board.get_request(), result.get_response())\n\n    @pytest.mark.parametrize(\"player, cap, move, piece\",\n                             [('w', 'P', 'dxd5', 'p'),\n                              ('w', 'P', 'dxc4', 'p'),\n                              ('w', 'P', 'dxe4', 'p'),\n                              ('w', 'P', 'dxd4', 'p'),\n                              ('b', 'p', 'dxd3', 'P'),\n                              ('b', 'p', 'dxc4', 'P'),\n                              ('b', 'p', 'dxe4', 'P'),\n                              ('b', 'p', 'dxd5', 'P')])\n    def test_pawn_illegal_capture(self, empty_board, player, cap, move,\n                                  piece, error_cant_move):\n        \"\"\"\n        Test various illegal pawn captures of every\n        Args:\n            empty_board: MakeMove object with starting board that contains\n            no pawns\n            player: Player making the capture\n            cap: Type of pawn making the capture\n            move: Illegal capture being made\n            piece: Type of piece being captured\n            error_cant_move: Response object with expected response\n\n        \"\"\"\n        empty_board.set_player(player)\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece('d4', cap)\n        empty_board.add_piece(move[2:], piece)\n        empty_board.set_move(move)\n\n        error_cant_move.set_data(move)\n\n        send_assert(empty_board.get_request(),\n                    error_cant_move.get_response())\n\n    @pytest.mark.parametrize(\"loc, piece\", [('a1', 'P'),\n                                            ('g1', 'P'),\n                                            ('b8', 'P'),\n                                            ('f8', 'P'),\n                                            ('c8', 'p'),\n                                            ('h8', 'p'),\n                                            ('b1', 'p'),\n                                            ('f1', 'p')])\n    def test_pawn_illegal_location(self, empty_board, loc, piece,\n                                   error_invalid_coord):\n        \"\"\"\n        Test illegal pawn locations which is the backrows of the board.\n        Args:\n            empty_board: MakeMove object with an empty board\n            loc: Location of pawn to be placed\n            piece: Type of pawn being placed\n            error_invalid_coord: Response object with expected error\n\n        \"\"\"\n        empty_board.set_player('b')\n        empty_board.add_piece('d1', 'Q')\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('d8', 'q')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece(piece, loc)\n        empty_board.set_move('Q8d7')\n\n        error_invalid_coord.set_data(piece)\n\n        send_assert(empty_board.get_request(),\n                    error_invalid_coord.get_response())\n\n    @pytest.mark.parametrize(\"player, loc, piece, move\",\n                             [('w', 'f4', 'P', 'fxe6'),\n                              ('b', 'c4', 'p', 'fxd3')])\n    def test_en_passant(self, empty_board, player, loc, piece, move,\n                        error_cant_move):\n        \"\"\"\n        Test en passant capture.\n        Args:\n            empty_board: MakeMove object with an empty board\n            player: Playing making the en passant capture\n            loc: Location of piece attempting to en passant\n            piece: Type of pawn performing capture\n            move: En passant move being made\n            error_cant_move: Response object with expected response\n\n        \"\"\"\n        empty_board.set_player(player)\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('c4', 'P')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece('e5', 'p')\n        empty_board.add_piece(loc, piece)\n        empty_board.set_move(move)\n\n        error_cant_move.set_data(move)\n\n        send_assert(empty_board.get_request(), error_cant_move.get_response())\n\n    @pytest.mark.parametrize(\"player, move, next\", [('w', 'c8Q', 'b'),\n                                                    ('w', 'c8=N', 'b'),\n                                                    ('w', 'c8(R)', 'b'),\n                                                    ('w', 'c8=B', 'b'),\n                                                    ('b', 'b1(q)', 'w'),\n                                                    ('b', 'b1n', 'w'),\n                                                    ('b', 'b1=r', 'w'),\n                                                    ('b', 'b1(b)', 'w')])\n    def test_promotion(self, empty_board, player, move, next, result):\n        \"\"\"\n        Test if pawn can get promoted when reaching the other side\n        Args:\n            empty_board: MakeMove object with an empty board\n            player: Player making the move\n            move: Promotion move being made\n            next: Next player's turn\n            result: Response object with expected response\n\n        \"\"\"\n        empty_board.set_player(player)\n        empty_board.add_piece('e1', 'K')\n        empty_board.add_piece('d8', 'Q')\n        empty_board.add_piece('c7', 'P')\n        empty_board.add_piece('e8', 'k')\n        empty_board.add_piece('d1', 'Q')\n        empty_board.add_piece('b2', 'p')\n        empty_board.set_move(move)\n\n        result.set_board(list(empty_board.get_board()))\n        result.set_player(next)\n        result.add_piece(move[0:2], move[3])\n\n        send_assert(empty_board.get_request(), result.get_response())\n","sub_path":"test_pawn.py","file_name":"test_pawn.py","file_ext":"py","file_size_in_byte":10968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"634367933","text":"from tkinter import *\n#import tkinter as tk\nimport pymysql\nfrom datetime import datetime, timedelta\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport pandas as pd\n\n\ndef Menu_window():\n    screen.destroy()\n    import kh\n\ndef moduleg1():\n    #screen.destroy()\n    global screen27\n    screen27 = Toplevel(screen)\n    screen27.title(\"Time series for orders in database\")\n    Label(screen27, text=\"\", bg='#dddddd',width='500', height='50').place(x=0, y=70)\n    Label(screen27, text=\"Time series for orders in database\", width=\"500\", height=\"2\",font=(\"Calibri\", 22, 'bold'), fg='black', bg='#77d8d8').pack()\n    #adjustWindow(screen27)\n    \n    connection = pymysql.connect(host=\"localhost\",user=\"root\",passwd=\"\", database=\"sales\") # database connection\n    cursor = connection.cursor()\n    select_query =  \"SELECT ORD_DATE FROM orders ;\" # queries for retrieving values \n    cursor.execute(select_query) # executing the queries \n    date = cursor.fetchall()\n    date_list = []\n    \n    for i in range(len(date)):       \n        date_list.append(date[i][0])\n        date_list.sort(key = lambda date: datetime.strptime(str(date), '%Y-%m-%d')) \n        fdate = {}\n        \n        for i in range(len(date_list)):\n            if date_list[i] in fdate:\n                fdate[date_list[i]] = fdate[date_list[i]] + 1\n            else:\n                fdate[date_list[i]] = 1\n     \n\n    df = pd.DataFrame.from_dict(fdate,orient='index')\n    \n    figure = plt.Figure(figsize=(10,6.1), dpi=100)\n    ax = figure.add_subplot(111)\n    chart_type = FigureCanvasTkAgg(figure, screen27)\n    chart_type.get_tk_widget().pack()\n    df.plot(rot=90,ax=ax)\n    ax.set_ylabel(\"Number of orders\")\n    ax.set_title('Time series for orders in database')\n    \n    \ndef moduleg2():\n    global screen28\n    screen28 = Toplevel(screen)\n    screen28.title(\"Time series for Area leased or owned\")\n    Label(screen28, text=\"\", bg='#dddddd',width='500', height='50').place(x=0, y=70)\n    Label(screen28, text=\"Time series for Area leased or owned\", width=\"500\", height=\"2\",font=(\"Calibri\", 22, 'bold'), fg='white', bg='#77d8d8').pack()\n    #adjustWindow(screen28)\n    data = pd.read_excel(\"A_new.xlsx\",header = 8)\n    data = data[:-1]\n    data.loc[data.UoM == \"HA\", \"Area\"] = data.Area*10000\n    data=data.replace('HA','SQ-M')\n    q7a = dict(data.groupby('Year').count()['Prov'])\n    q7ad = pd.DataFrame({'Year':list(q7a.keys()),'Number of orders':list(q7a.values())})\n    figure = plt.Figure(figsize=(10,6.1), dpi=100)\n    ax = figure.add_subplot(111)\n    chart_type = FigureCanvasTkAgg(figure, screen28)\n    chart_type.get_tk_widget().pack()\n    q7ad.plot(ax=ax,x='Year')\n    ax.set_ylabel(\"Number of orders\")\n    ax.set_title('Time series for Area leased or owned')\n\n    \ndef main_screen():\n    global screen\n    screen=Tk()\n    screen.title(\"Time Series Analysis\")\n    screen.geometry(\"1030x600+100+50\")\n    screen.configure(background=\"sky blue\")\n    lbl=Label(screen,text=\"Time Series Analysis For Order Date VS Order Amount\",font=(\"times new roman\",20,\"bold\"),fg=\"green\")\n    lbl.place(x=250,y=120)\n    \n    lbl=Label(screen,text=\"Time Series Analysis For Order Date VS Advance Amount\",font=(\"times new roman\",20,\"bold\"),fg=\"green\")\n    lbl.place(x=250,y=300)\n\n    but = Button(screen, text=\"VIEW GRAPH\", bg = \"#747437\", fg=\"white\",font=(\"times new roman\",20,\"bold\"),cursor=\"hand2\",command=moduleg1)\n        \n    but.place(x=440,y=180)\n    menubtn=Button(screen,text=\"= s and d <= t:\n            apples_count += 1\n    for orange in oranges:\n        d = b + orange\n        if d >= s and d <= t:\n            oranges_count += 1\n    print(apples_count)\n    print(oranges_count)\n\n\nprint(countApplesAndOranges(7, 11, 5, 15, [-2, 2, 1], [5, -6]))\n","sub_path":"apple-orange.py","file_name":"apple-orange.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"166097308","text":"from NanoCore import *\n\n# modeling tool\natoms = io.read_xsf('model.xsf')\n\n# simulation object\nsim = s2.Siesta(atoms)\n\n# set simulation options\nsim.set_option('kgrid', [1,7,1])         # set #k-point\nsim.set_option('kshift', [0.0,0.0,0.0])  # set k-center from gamma\nsim.set_option('MixingWt', 0.05)         # adjust mixing weight (density)\nsim.set_option('PDOS', 1)                # enable PDOS block\nsim.set_option('PDOSE', (-5,5,0.1,1001)) # emin, emax, dE, NE\n\n# run siesta\nsim.run(mpi=1, nproc=2)\n\n# get PDOS --> LDOS\nz_coords, Z, E = s2.get_pldos(sim, -5, 5, broad=0.05, npoints=1001, label='siesta')\n\n# convert to log10 values + minimum correction to avoid -INF\ncorrect = 10**-5\nZ = np.log10(Z+correct)\n\n# generate meshgrid\nX, Y = np.meshgrid(np.array(z_coords), E)\n\n# customized figure \nimport matplotlib.pyplot as plt\nfig1 = plt.figure(figsize=(10,12))\nfig11 = fig1.add_subplot(212)\nlevels = np.linspace(1.01*Z.min(), 0.99*Z.max(), 100)\n\nimport pylab as plb\ncset = plb.contourf(X,Y,Z, levels)\nplb.colorbar(cset)\nfig11.axis([0, 20, -5, 5])\n\n# atoms \nfig12 = fig1.add_subplot(311)\nY, Z = atoms.get_2dscatter(plane='yz')\nfig12.scatter(Z, Y)\nfig12.axis([0, 20, 0, 6])\n\nplt.show()\nfig1.savefig('1.png')\n","sub_path":"Examples/2.pdos/RUN.py","file_name":"RUN.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"483271379","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/ryan/anaconda3/envs/wsl2/lib/python3.8/site-packages/pyEQL/tests/test_dielectric.py\n# Compiled at: 2020-04-22 00:39:48\n# Size of source mod 2**32: 4373 bytes\n\"\"\"\npyEQL dielectric constant test suite\n============================================\n\nThis file contains tests that check the dielectric constant\ncomputations of pyEQL\n\n\"\"\"\nimport pyEQL, unittest\n\nclass Test_dielectric(unittest.TestCase, pyEQL.CustomAssertions):\n    __doc__ = '\\n    test the Dielectric Constant calculations of various solutions\\n    ------------------------------------------------\\n\\n    Reference: A. Zuber, L. Cardozo-Filho, V.F. Cabral, R.F. Checoni, M. Castier, An empirical equation for the \\n    dielectric constant in aqueous and nonaqueous electrolyte mixtures, Fluid Phase Equilib. 376 (2014) 116–123.\\n    doi:10.1016/j.fluid.2014.05.037.\\n\\n    '\n\n    def setUp(self):\n        self.tol = 0.01\n\n    def test_dielectric_constant(self):\n        \"\"\"\n        4.4 mol/kg NaCl = 46\n        \"\"\"\n        s1 = pyEQL.Solution([['Na+', '4.4 mol/kg'], ['Cl-', '4.4 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 46\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant2(self):\n        \"\"\"\n        2 mol/kg NaCl = 58\n        \"\"\"\n        s1 = pyEQL.Solution([['Na+', '2 mol/kg'], ['Cl-', '2 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 58\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant3(self):\n        \"\"\"\n        1 mol/kg NaCl = 66\n        \"\"\"\n        s1 = pyEQL.Solution([['Na+', '1 mol/kg'], ['Cl-', '1 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 66\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant4(self):\n        \"\"\"\n        1 mol/kg KBr = 67\n        \"\"\"\n        s1 = pyEQL.Solution([['K+', '1 mol/kg'], ['Br-', '1 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 67\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant5(self):\n        \"\"\"\n        3.4 mol/kg KBr = 51\n        \"\"\"\n        s1 = pyEQL.Solution([['K+', '3.4 mol/kg'], ['Br-', '3.4 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 51\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant6(self):\n        \"\"\"\n        5 mol/kg LiCl = 39\n        \"\"\"\n        s1 = pyEQL.Solution([['Li+', '5 mol/kg'], ['Cl-', '5 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 39\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant7(self):\n        \"\"\"\n        1 mol/kg LiCl = 64\n        \"\"\"\n        s1 = pyEQL.Solution([['Li+', '1 mol/kg'], ['Cl-', '1 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 64\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    @unittest.expectedFailure\n    def test_dielectric_constant8(self):\n        \"\"\"\n        12 mol/kg LiCl = 24\n        \"\"\"\n        s1 = pyEQL.Solution([['Li+', '12 mol/kg'], ['Cl-', '12 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 24\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant9(self):\n        \"\"\"\n        6.5 mol/kg RbCl = 43\n        \"\"\"\n        s1 = pyEQL.Solution([['Rb+', '6.5 mol/kg'], ['Cl-', '6.5 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 43\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant9(self):\n        \"\"\"\n        2.1 mol/kg RbCl = 59\n        \"\"\"\n        s1 = pyEQL.Solution([['Rb+', '2.1 mol/kg'], ['Cl-', '2.1 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 59\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n    def test_dielectric_constant9(self):\n        \"\"\"\n        0.5 mol/kg RbCl = 73\n        \"\"\"\n        s1 = pyEQL.Solution([['Rb+', '0.5 mol/kg'], ['Cl-', '0.5 mol/kg']])\n        result = s1.get_dielectric_constant().magnitude\n        expected = 73\n        self.assertWithinExperimentalError(result, expected, self.tol)\n\n\nif __name__ == '__main__':\n    unittest.main()","sub_path":"pycfiles/pyEQL-0.5.2.linux-x86_64.tar/test_dielectric.cpython-38.py","file_name":"test_dielectric.cpython-38.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"502275008","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom saveas import save_output_txt\n\n# ---------------------------- Get Hanning Window Coeffs ------------------------------\ndef get_win(nFFT, show_plots=False, save_output='both', out_folder='output'):\n    \n    # hanning window according to IDL func (asymmetric)\n\n    win_out = [((2**16)-1)*(0.5 - (0.5)*np.cos(2* np.pi * k/ nFFT)) for k in range(nFFT)]\n    win = [round(w) for w in win_out] # make int window\n    win = np.array(win)\n\n    if show_plots:\n        plt.plot(np.arange(0, len(win)), win)\n        plt.title('Input Window')\n        plt.show()\n        plt.close()\n    \n    if save_output:\n        out_path = out_folder+'/window'\n        save_output_txt(win, out_path, save_output, 'u-16')\n\n    return win\n# ------------------------------------------------------------------------------------","sub_path":"win.py","file_name":"win.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"369187592","text":"# -*- coding: utf-8 -*-\r\nimport csv     \r\nimport requests\r\nimport json\r\nfrom datetime import datetime\r\nfrom bs4 import BeautifulSoup \r\nimport sys\r\nreload(sys)\r\nsys.setdefaultencoding('utf8')\r\n\r\n\r\n\r\ncsv.register_dialect('myDialect1',\r\n\t  quoting=csv.QUOTE_ALL,\r\n\t  skipinitialspace=True)\r\n\r\nwrite_file = open('gwdocs.csv', 'a')\r\ncsv_writer = csv.writer(write_file, dialect='myDialect1')\r\n\r\ncsv_writer.writerow(['Name', 'Title', 'Specialties', 'Phone', 'Address'])\r\n\r\nsession = requests.Session()\r\nsession.headers.update({\r\n        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',\r\n    })\r\nurl = 'https://www.gwdocs.com/find-a-doctor/'\r\nbaseurl = 'https://www.gwdocs.com'\r\nfor page in range(1, 13):\r\n    r = session.post(url, data={\r\n        '_m_': 'PhysicianSearchResultsPanel',\r\n        'PhysicianSearch$HDR0$SpecialtyIDs': '',\r\n        'PhysicianSearch$HDR0$Gender': '',\r\n        'PhysicianSearch$HDR0$PhysicianName': '',\r\n        'PhysicianSearch$HDR0$City': '',\r\n        'PhysicianSearch$HDR0$AffiliationIDs': '',\r\n        'PhysicianSearch$HDR0$Position': '',\r\n        'PhysicianSearch$HDR0$InterestIDs': '',\r\n        'PhysicianSearch$HDR0$LastName': '',\r\n        'PhysicianSearch$HDR0$Keywords': '',\r\n        'PhysicianSearch$HDR0$ResultsPerPage': 50,\r\n        'PhysicianSearch$HDR0$PagingID': page,\r\n        'PhysicianSearch$FTR01$PagingID': page\r\n    })\r\n    soup = BeautifulSoup(r.text, features=\"html.parser\")\r\n    for doctor in soup.findAll('li', class_='phys-item'):\r\n        name = doctor.find('div', class_='top').text.strip().split(',')[0]\r\n        title = ''\r\n        if len(doctor.find('div', class_='top').text.strip().split(',')) > 1:\r\n            title = doctor.find('div', class_='top').text.strip().split(',')[1]\r\n        detail = doctor.find('div', class_='top').find('a').attrs['href']\r\n        speciality = ''\r\n        for spec in doctor.find('ul', class_='specialty-list').findAll('li'):\r\n            speciality = speciality + spec.text.strip() + ', '\r\n        r = session.get(baseurl + detail)\r\n        soup = BeautifulSoup(r.text, features=\"html.parser\")\r\n        phone = ''\r\n        if soup.find('div', class_='book-phone') and soup.find('div', class_='book-phone').find('a'):\r\n            phone = soup.find('div', class_='book-phone').find('a').text\r\n            address = ''\r\n        if soup.find('ul', class_='location-list'):\r\n            address = \" \".join(soup.find('ul', class_='location-list').find('p').text.strip().split())\r\n        print(name, title, speciality[0:-2], phone, address)\r\n        csv_writer.writerow([name, title, speciality[0:-2], phone, address])","sub_path":"gwdocs.py","file_name":"gwdocs.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"132740342","text":"import copy\nimport random\n\nimport numpy as np\n\n\nclass Environment:\n\n    def __init__(self, goal_state_reward, pit_reward, move_reward, give_up_reward):\n\n        # randomize the seed to current system time\n        random.seed(None)\n\n        # 0 is empty area, 1 is goal, 2 is pit\n        # self._grid[y][x]\n        self._grid = np.matrix([[0, 0, 0, 0, 0, 0, 0],\n                                [0, 0, 0, 0, 0, 0, 0],\n                                [0, 0, 2, 2, 0, 0, 0],\n                                [0, 2, 1, 0, 0, 2, 0],\n                                [0, 0, 2, 2, 2, 0, 0],\n                                [0, 0, 0, 0, 0, 0, 0]])\n        print(np.shape(self._grid))\n        self.goal_reward = goal_state_reward\n        self.pit_reward = pit_reward\n        self.move_reward = move_reward\n        self.give_up_reward = give_up_reward\n\n        self.running_reward = 0\n\n        self._x_size = self._grid.shape[1]\n        self._y_size = self._grid.shape[0]\n\n        self.state_size = self._x_size * self._y_size\n        self.state_space = np.reshape(copy.deepcopy(self._grid), (1, self.state_size))\n\n        self.action_space = np.array([0, 1, 2, 3, 5])\n        self.action_size = self.action_space.size\n\n        self._x = None\n        self._y = None\n\n        self.start_x = self._x\n        self.start_y = self._y\n\n        self.random_start()\n\n    '''\n    takes in an action and determines the effect that action has on the environment\n    '''\n\n    def step(self, action, q_init=False):\n\n        if action == 5:\n            self.running_reward += self.give_up_reward\n            return (self._x, self._y), self.give_up_reward, True\n\n        if q_init:\n            next_x, next_y = self.get_final_location(self._x, self._y, action, False)\n            reward, is_done = self.get_step_reward(next_x, next_y, False)\n            return (next_x, next_y), reward, is_done\n\n        new_action, is_double = self.get_actual_movement(action)\n\n        # special check for double movements to make sure it didn't hit an ending location 1 move away\n        if is_double:\n            step_x, step_y = self.get_skipped_location(self._x, self._y, new_action)\n            reward, is_done = self.get_step_reward(step_x, step_y, False)\n            # if we finished (hit goal or pit, either or), set the variables, and return that were finished\n            if is_done:\n                self._x = step_x\n                self._y = step_y\n\n                self.running_reward += reward\n\n                return (self._x, self._y), reward, is_done\n            else:\n                self._x, self._y = self.get_final_location(self._x, self._y, new_action, is_double)\n                reward, is_done = self.get_step_reward(self._x, self._y, is_double)\n\n                self.running_reward += reward\n\n                return (self._x, self._y), reward, is_done\n        else:\n            self._x, self._y = self.get_final_location(self._x, self._y, new_action, is_double)\n            reward, is_done = self.get_step_reward(self._x, self._y, is_double)\n\n            self.running_reward += reward\n\n            return (self._x, self._y), reward, is_done\n\n    '''\n    mirror of step method that instead takes in the starting location instead of changing the objects values\n    '''\n\n    def future_step(self, action, future_x, future_y):\n        direction, double = self.get_actual_movement(action)\n\n        if action == 5:\n            return (future_x, future_y), self.give_up_reward, True\n\n        # special check for double movements to make sure it didn't hit an ending location 1 move away\n        if double:\n            step_x, step_y = self.get_skipped_location(future_x, future_y, direction)\n            reward, is_done = self.get_step_reward(step_x, step_y, False)\n            # if we finished (hit goal or pit, either or), set the variables, and return that were finished\n            if is_done:\n                return (future_x, future_y), reward, is_done\n\n        # if we get here, the movement was only one step, or the movement was double but we didn't hit an end goal\n        x, y = self.get_final_location(future_x, future_y, direction, double)\n        reward, is_done = self.get_step_reward(x, y, double)\n\n        return (x, y), reward, is_done\n\n    '''\n    generates a random location. Checks to make sure that location is not a pit, otherwise it trys again\n    '''\n\n    def random_start(self):\n\n        self._x = None\n        self._y = None\n\n        while self._x is None and self._y is None:\n            self._x = random.randint(0, self._x_size - 1)\n            self._y = random.randint(0, self._y_size - 1)\n\n            if self._grid[self._y, self._x] != 0:\n                self._x = None\n                self._y = None\n\n        self.start_x = self._x\n        self.start_y = self._y\n\n    '''\n    resets the environment \n    sets the running reward to 0, then chooses a random start location\n    '''\n\n    def reset(self):\n\n        self.running_reward = 0\n        self.random_start()\n\n    '''\n    requested move = [0, 1, 2, 3] for [up, right, down, left]\n    returns (move, is_double) where 'move' is the same mapping as the input, and 'is_double' is a bool flag\n    '''\n\n    @staticmethod\n    def get_actual_movement(requested_move):\n\n        def rotate_right(wanted_move):\n            wanted_move += 1\n            if wanted_move == 4:\n                wanted_move = 0\n            return wanted_move\n\n        def rotate_left(wanted_move):\n            wanted_move -= 1\n            if wanted_move == -1:\n                wanted_move = 3\n            return wanted_move\n\n        val = random.randint(0, 9)\n\n        if val <= 6:\n            return requested_move, False\n        elif 6 < val <= 7:\n            return rotate_right(requested_move), False\n        elif 7 < val <= 8:\n            return rotate_left(requested_move), False\n        else:\n            return requested_move, True\n\n    '''\n    finds the final location of the movement\n    '''\n\n    def get_final_location(self, start_x, start_y, direction, is_double):\n\n        def clamp(val, minn, maxn):\n            return min(max(val, minn), maxn)\n\n        current_x = start_x\n        current_y = start_y\n\n        if direction == 0:\n            if is_double:\n                current_y -= 2\n            else:\n                current_y -= 1\n        elif direction == 1:\n            if is_double:\n                current_x += 2\n            else:\n                current_x += 1\n        elif direction == 2:\n            if is_double:\n                current_y += 2\n            else:\n                current_y += 1\n        elif direction == 3:\n            if is_double:\n                current_x -= 2\n            else:\n                current_x -= 1\n\n        current_x = clamp(current_x, 0, self._x_size - 1)\n        current_y = clamp(current_y, 0, self._y_size - 1)\n\n        return current_x, current_y\n\n    '''\n    finds the stepped over location for use with pit/goals checks\n    '''\n\n    def get_skipped_location(self, start_x, start_y, direction):\n        def clamp(val, minn, maxn):\n            return min(max(val, minn), maxn)\n\n        current_x = start_x\n        current_y = start_y\n\n        if direction == 0:\n            current_y -= 1\n        elif direction == 1:\n            current_x += 1\n        elif direction == 2:\n            current_y += 1\n        elif direction == 3:\n            current_x -= 1\n\n        current_x = clamp(current_x, 0, self._x_size - 1)\n        current_y = clamp(current_y, 0, self._y_size - 1)\n\n        return current_x, current_y\n\n    '''\n    computes the step reward result and whether or not its done\n    '''\n\n    def get_step_reward(self, x, y, is_double):\n        reward = 0\n        is_done = False\n\n        current_grid = self._grid[y, x]\n        r = lambda is_double: 2 if is_double else 1\n\n        if current_grid == 0:\n            reward += self.move_reward * r(is_double)\n        elif current_grid == 1:\n            reward += self.goal_reward\n            is_done = True\n        elif current_grid == 2:\n            reward += self.pit_reward\n            is_done = True\n\n        return reward, is_done\n\n    def set_start_location(self, x, y):\n        self._x = x\n        self._y = y\n","sub_path":"src/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":8157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"327674233","text":"\"\"\"\n@file tests/python/smoke_test.py\n@date 12/16/15\n@author user\n\"\"\"\nimport py.test\nimport os.path\nimport glob\nimport extSim.utils\nimport extSim.extsim\nfrom astropy.io import fits\nimport shutil\nfrom string import uppercase as amptags\nfrom fixtures.PyDataSyncFixture import *\nimport ElementsKernel.Logging as logging\n\nlog = logging.getLogger('image')\n\ndata_dir = os.path.join(os.environ[\"PHOTROOT\"],\"tests\", \"data\")\n\ndef symlinks(datafiles,workspace):\n    for dst,src in datafiles.items():\n        os.symlink(os.path.join(data_dir,src), os.path.join(workspace,dst))\n\ndef simulate():\n    datafiles={\"catalog.txt\":\"myEXTrandomcat-sersics.txt\", \"target.json\":\"des_target.json\", \"instrument.json\":\"des_test_instrument.json\", \"flat.fits\":\"des_testflat.fits\", \"bias.fits\":\"des_testbias.fits\"}\n    with extSim.utils.mock_workspace('test_smoke_sersics_ws_',del_tmp=False) as workspace:\n       symlinks(datafiles,workspace)\n       args = extSim.extsim.parseOptions(['--workspace',workspace],defaultconfig='smoke_test.conf')\n       extSim.extsim.mainMethod(args)\n    return args\n\nclass Testsersic(object):\n    \"\"\"\n    @class Testsmoke\n    @brief Unit Test class\n    \"\"\"\n    \n    def setup_class(self): \n        PyDataSyncFixture(\"../../config/sync.conf\", \"../../config/test_file_list.txt\")\n        self.del_tmp = True\n        self.silent = True\n        self.args = simulate()\n        self.instrument = extSim.utils.read_instrument(os.path.join(self.args.workspace,self.args.instrument))\n        try :\n            self.im = fits.open(os.path.join(self.args.output_path, 'output.fits'))\n        except :\n            self.im = None\n        \n    def test_outfile(self):\n        \"\"\"\n        Check that an output image have been generated in the output directory.\n        \"\"\"\n        assert glob.glob(os.path.join(self.args.output_path, 'output.fits'))\n        \n    def test_amp_positions(self):\n        \"\"\"\n        Check that the amps sections header keywords have the expected values.\n        \"\"\"\n        for iext,ccdinfos in self.instrument[\"CCDS_LAYOUT\"].items():\n            for key in [k for k in ccdinfos if k.endswith(\"SEC\")]:\n                for iamp in range(self.instrument[\"AMPS_X_CCD\"]):\n                    amptag = amptags[iamp]\n                    log.info(\"extension : {} amp : {} key : {}\".format(iext,amptag,key))\n                    assert self.im[iext].header[key+amptag]==ccdinfos[key][iamp]\n    \n    def test_ccd_order(self):\n        \"\"\"\n        Check that the fits extensions are ordered as expected.\n        \"\"\"\n        for iext,ccdinfos in self.instrument[\"CCDS_LAYOUT\"].items():\n            assert self.im[iext].header[\"CCDNUM\"]==iext and  self.im[iext].header[\"EXTNAME\"]==ccdinfos[\"EXTNAME\"]\n            \n    def test_pixel_headkeys(self):\n        \"\"\"\n        Check that the pixel related headkeys are coherent with the input values.\n        \"\"\"\n        headkeys={\"GAIN\":\"GAIN\",\"SATURAT\":\"SATUR_LEVEL\",\"RDNOISE\":\"READOUT_NOISE\"}\n        for iext,ccdinfos in self.instrument[\"CCDS_LAYOUT\"].items():\n            for hkey,pkey in headkeys.items():\n                for iamp in range(self.instrument[\"AMPS_X_CCD\"]):\n                    amptag = amptags[iamp]\n                    assert self.im[iext].header[hkey+amptag]==ccdinfos[pkey][iamp]\n                    \n    def test_extend_keyword(self):\n        \"\"\"\n        Check that the pixel related headkeys are coherent with the input values.\n        \"\"\"\n        assert self.im[0].header[\"EXTEND\"]==True\n    \n    def test_obstype_keyword(self):\n        \"\"\"\n        Check that OBSTYPE keyword complies with DES convention\n        \"\"\"\n        assert self.im[0].header[\"OBSTYPE\"]==\"object\"\n        \n    def teardown_class(self):\n        \"\"\"\n        Removes workspace\n        \"\"\"\n        shutil.rmtree(self.args.workspace, ignore_errors=True)\n        \n                    \n","sub_path":"Phot/tests/python/smoke_test_sersic_des.py","file_name":"smoke_test_sersic_des.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"374172985","text":"import re\nfrom . import commands\nfrom .selectors import selectpattern, select_local_pattern, intervalselector\nfrom .document import Document\nfrom .prompt import prompt\nfrom .commandtools import Compose\nfrom functools import partial\n\nDocument.search_pattern = ''\n\n\ndef local_find(document):\n    key = document.ui.getkey()\n    selector = intervalselector(partial(select_local_pattern, re.escape(key)))\n    selector(document)\ncommands.local_find = local_find\n\n\ndef local_find_backward(document):\n    key = document.ui.getkey()\n    selector = intervalselector(partial(select_local_pattern, re.escape(key),\n                                        reverse=True))\n    selector(document)\ncommands.local_find_backward = local_find_backward\n\n\ndef _search(document):\n    document.search_pattern = document.promptinput\n    if document.search_pattern:\n        try:\n            command = selectpattern(document.search_pattern, document, document.selection,\n                                    document.selectmode)\n            command(document)\n        except re.error as e:\n            document.ui.notify(str(e))\ncommands.search = Compose(prompt('/'), _search)\n\n\ndef search_current_content(document):\n    document.search_pattern = re.escape(document.selection.content(document)[-1])\n    selectpattern(document.search_pattern, document, document.selection,\n                  document.selectmode)(document)\ncommands.search_current_content = search_current_content\n\n\ndef search_next(document):\n    if document.search_pattern:\n        try:\n            command = selectpattern(document.search_pattern, document, document.selection,\n                                    document.selectmode)\n            command(document)\n        except re.error as e:\n            document.ui.notify(str(e))\ncommands.search_next = search_next\n\n\ndef search_previous(document):\n    if document.search_pattern:\n        try:\n            command = selectpattern(document.search_pattern, document, document.selection,\n                                    document.selectmode, reverse=True)\n            command(document)\n        except re.error as e:\n            document.ui.notify(str(e))\ncommands.search_previous = search_previous\n","sub_path":"fate/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"244765145","text":"'''\nCreated on Nov 25, 2012\n\n@author: jamesd\n'''\nimport BDmaya.main_lib.BD_Utils as BD_Utils\nimport BDmaya.main_lib.BD_CONST as BD_CONST\nimport BDmaya.main_customToolsByCompany.tools_AL.BD_SurfGeoCheck as BD_SurfGeoCheck\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nimport maya.cmds as cmds\n\n                                           \nclass BD_SurfGeoCheckUI(QWidget):\n    '''\n    Standalone window for surfGeo checking\n    '''\n    def __init__(self, parent = None):\n        QWidget.__init__(self, parent)\n        self.setObjectName('SurfGeo Checker')\n        self.setWindowTitle('SurfGeo Checker')\n\n        self.splitter = QGridLayout(self)\n        \n        self.mainLayout = QVBoxLayout(self)\n        self.freezeXformsCB = QCheckBox('FreezeTransforms', self)\n        self.freezeXformsCB.setChecked(True)\n\n        self.deleteHistoryCB = QCheckBox('Delete History', self)\n        self.deleteHistoryCB.setChecked(True)\n                    \n        self.fixShapeNamesCB = QCheckBox('Fix Shape Names', self)\n        self.fixShapeNamesCB.setChecked(True)            \n\n        self.removeBobjectsCB = QCheckBox('Remove Bobtags', self)\n        self.removeBobjectsCB.setChecked(True)     \n\n        self.removeIntermediateCB = QCheckBox('Remove Intermediate Objs', self)\n        self.removeIntermediateCB.setChecked(True)     \n\n        self.zeroPivotsCB = QCheckBox('ZeroPivots', self)\n        self.zeroPivotsCB.setChecked(True)\n        \n        self.checkSuffixCB = QCheckBox('Check Suffix _geo', self)\n        self.checkSuffixCB.setChecked(True)\n        \n        self.goButton = QPushButton('Clean', self)\n        self.goButton.released.connect(self.processSurfGeo)\n        \n        self.listBoxLayout = QVBoxLayout(self)\n        \n        self.listBox = QListWidget(self)\n        self.listBox.setMinimumWidth(300)\n        self.listBoxLayout.addWidget(self.listBox)\n        self.listBox.hide()\n        \n        self.mainLayout.addWidget(self.freezeXformsCB)\n        self.mainLayout.addWidget(self.deleteHistoryCB)\n        self.mainLayout.addWidget(self.removeIntermediateCB)\n        self.mainLayout.addWidget(self.fixShapeNamesCB)\n        self.mainLayout.addWidget(self.removeBobjectsCB)\n        self.mainLayout.addWidget(self.zeroPivotsCB)\n        self.mainLayout.addWidget(self.checkSuffixCB)\n        self.mainLayout.addWidget(self.goButton)\n\n        self.splitter.addLayout(self.mainLayout, 0,0)\n        self.splitter.addLayout(self.listBoxLayout, 0,1)\n            \n    def processSurfGeo(self):\n        self.listBox.clear()\n        self.listBox.show()\n        curSel = cmds.ls(sl = True)\n        if BD_SurfGeoCheck.duplicateNameCheck():\n            self.listBox.addItem('Duplicate transform names found. Please fix.')\n            \n        elif curSel:\n            ##Unlock unhide all attrs and set vis to 1\n            for eachSel in curSel:\n                try:\n                    BD_Utils.lockAndHide(eachSel, BD_CONST.ALLCHANS, lock = False, keyable = True)\n                    cmds.setAttr('%s.visibility' % eachSel, 1)                   \n                except TypeError:\n                    pass\n            self.listBox.addItem('Unlocked/hid all attrs')\n            self.listBox.addItem('Vis turned on')\n            ### Process Freeze Transforms\n            if self.freezeXformsCB.isChecked():\n                for eachSel in curSel:\n                    BD_SurfGeoCheck.freezeXForms(eachSel)\n                self.listBox.addItem('All Transforms Frozen')\n            else:\n                self.listBox.addItem('Freeze Transforms Skipped.')\n                \n            ### Process History\n            if self.deleteHistoryCB.isChecked():\n                for eachSel in curSel:\n                    BD_SurfGeoCheck.delHistory(eachSel)\n                self.listBox.addItem('All History Deleted')\n            else:\n                self.listBox.addItem('Del History Skipped.')\n\n            ### Process Intermediate Removal    \n            if self.removeIntermediateCB.isChecked():\n                for eachSel in curSel:\n                    BD_SurfGeoCheck.deleteIntermediate(eachSel)\n                self.listBox.addItem('All Intermediates Removed')\n            else:\n                self.listBox.addItem('Intermediates Skipped.')\n    \n            ### Process fixShapeNamesCB\n            if self.fixShapeNamesCB.isChecked():\n                for eachSel in curSel:\n                    BD_SurfGeoCheck.checkShapeNames(eachSel)\n                self.listBox.addItem('All Shape Names cleaned')\n            else:\n                self.listBox.addItem('Shape Names Skipped.')\n                \n            ### Process Bobject Removal\n            if self.removeBobjectsCB.isChecked():\n                BD_SurfGeoCheck.remBobjects()\n                self.listBox.addItem('All Bobjects Removed')\n            else:\n                self.listBox.addItem('Bobject Removal Skipped.')\n            \n            ### Process ZeroPivots               \n            if self.zeroPivotsCB.isChecked():\n                for eachSel in curSel:\n                    BD_SurfGeoCheck.checkPivots(eachSel)\n                self.listBox.addItem('All Pivots Zeroed')\n            else:\n                self.listBox.addItem('Pivots Skipped.')\n                \n            ### Process Suffix               \n            if self.checkSuffixCB.isChecked():\n                badSuffix = []\n                for eachSel in curSel:\n                    if BD_SurfGeoCheck.checkSuffix(eachSel):\n                        badSuffix.append(eachSel)\n                \n                if badSuffix != []:\n                    self.listBox.addItem('All Suffix Checked - Incorrect Suffix Found. Check Outliner')\n                    cmds.select(badSuffix, r=True)\n                    cmds.sets(name = 'badSuffix')\n                    cmds.select(clear = True)\n                else:\n                    self.listBox.addItem('All Suffix Checked - No issues found.')\n            else:\n                self.listBox.addItem('Suffix Skipped.')\n        else:\n            self.listBox.addItem('Nothing Selected')","sub_path":"BDmaya/main_customToolsByCompany/tools_AL/BD_SurfGeoCheckUI.py","file_name":"BD_SurfGeoCheckUI.py","file_ext":"py","file_size_in_byte":6050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"115828076","text":"import torch.nn as nn\nfrom bayesian_layer import FlattenLayer, Bayesian_conv2D, Bayesian_fullyconnected\n\nclass Small_conv_net(nn.Module):\n    def __init__(self, outputs, inputs):\n        super(Small_conv_net, self).__init__()\n\n        self.conv1 = Bayesian_conv2D(inputs, 6, 5, stride=1)\n        self.conv1_bn = nn.BatchNorm2d(6)\n        self.soft1 = nn.Softplus()\n        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.conv2 = Bayesian_conv2D(6, 16, 5, stride=1)\n        self.conv2_bn = nn.BatchNorm2d(16)\n        self.soft2 = nn.Softplus()\n        self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.flatten = FlattenLayer(5 * 5 * 16)\n        self.fc1 = Bayesian_fullyconnected(5 * 5 * 16, 120)\n        self.fc1_bn = nn.BatchNorm1d(120)\n        self.soft3 = nn.Softplus()\n\n        self.fc2 = Bayesian_fullyconnected(120, outputs)\n\n        layers = [self.conv1, self.conv1_bn, self.soft1, self.pool1, self.conv2, self.conv2_bn, self.soft2, self.pool2,\n                  self.flatten, self.fc1, self.fc1_bn, self.soft3, self.fc2]\n\n        self.layers = nn.ModuleList(layers)\n\n\n        # self.conv1 = Bayesian_conv2D(inputs, 32, 5, stride=1, padding=2, bias=True)\n        # self.conv1_bn = nn.BatchNorm2d(32)\n        # self.soft1 = nn.Softplus()\n        # self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)\n        #\n        # self.conv2 = Bayesian_conv2D(32, 64, 5, stride=1, padding=2, bias=True)\n        # self.conv2_bn = nn.BatchNorm2d(64)\n        # self.soft2 = nn.Softplus()\n        # self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)\n        #\n        # self.conv3 = Bayesian_conv2D(64, 128, 5, stride=1, padding=1, bias=True)\n        # self.conv3_bn = nn.BatchNorm2d(128)\n        # self.soft3 = nn.Softplus()\n        # self.pool3 = nn.MaxPool2d(kernel_size=3, stride=2)\n        #\n        # self.flatten = FlattenLayer(2 * 2 * 128,)\n        # self.fc1 = Bayesian_fullyconnected(2 * 2 * 128, 100, bias=True)\n        # self.fc1_bn = nn.BatchNorm1d(100)\n        # self.soft5 = nn.Softplus()\n        #\n        # self.fc3 = Bayesian_fullyconnected(100, outputs, bias=True)\n        #\n        # self.layers = [self.conv1, self.conv1_bn, self.soft1, self.pool1, self.conv2,self.conv2_bn, self.soft2, self.pool2,\n        #           self.conv3, self.conv3_bn, self.soft3, self.pool3, self.flatten, self.fc1, self.fc1_bn, self.soft5,\n        #           self.fc3]\n\n\n\n    def probforward(self, x):\n        'Forward pass with Bayesian weights'\n        kl = 0\n        for layer in self.layers:\n            if hasattr(layer, 'conv_forward_bayes') and callable(layer.conv_forward_bayes):\n                x, _kl, = layer.conv_forward_bayes(x)\n                kl += _kl\n\n            elif hasattr(layer, 'fc_forward_bayes') and callable(layer.fc_forward_bayes):\n                x, _kl, = layer.fc_forward_bayes(x)\n                kl += _kl\n            else:\n                x = layer(x)\n        logits = x\n        return logits, kl\n\nclass FC_Net(nn.Module):\n    def __init__(self, outputs, inputs):\n        super(FC_Net, self).__init__()\n\n        self.flatten = FlattenLayer(28*28)\n        self.fc1 = Bayesian_fullyconnected(28*28, 120)\n        self.soft3 = nn.Softplus()\n\n        self.fc2 = Bayesian_fullyconnected(120, 84)\n        self.soft4 = nn.Softplus()\n\n        self.fc3 = Bayesian_fullyconnected(84, outputs)\n\n        layers = [self.flatten, self.fc1, self.soft3, self.fc2, self.soft4, self.fc3]\n\n        self.layers = nn.ModuleList(layers)\n\n    def probforward(self, x):\n        'Forward pass with Bayesian weights'\n        kl = 0\n        for layer in self.layers:\n            if hasattr(layer, 'conv_forward_bayes') and callable(layer.conv_forward_bayes):\n                x, _kl, = layer.conv_forward_bayes(x)\n                kl += _kl\n\n            elif hasattr(layer, 'fc_forward_bayes') and callable(layer.fc_forward_bayes):\n                x, _kl, = layer.fc_forward_bayes(x)\n                kl += _kl\n            else:\n                x = layer(x)\n        logits = x\n        return logits, kl","sub_path":"model_BNN.py","file_name":"model_BNN.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"197113005","text":"#coding=utf-8\n\nimport tornado.web\nfrom handler.basehandler import BaseHandler\nfrom bin import base\n\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nclass TrashHeadImgHandler(BaseHandler):\n    @tornado.web.authenticated\n    def post(self):\n        img_id = self.get_argument(\"img_id\", \"\")\n        if img_id:\n            from optsql.searchMySQL import search_one_imgurl\n            img_url = search_one_imgurl(img_id=img_id)     #先查询图片id对应的url\n            if img_url:\n                import os\n                os.remove(img_url)                         #删除存储在文件中的图\n                from optsql.deleteMySQL import delete_one_imgurl\n                delete_one_imgurl(img_id=img_id)           #删除数据库的url\n                result = {\"status\": 0, \"rt_info\": \"删除成功!\"}\n            else:\n                result = {\"status\": 1, \"rt_info\": \"不存在改图~\"}\n        else:\n            result = {\"status\": 2, \"rt_info\": \"网络连接错误~\"}\n        self.write(base.get_json(result))\n","sub_path":"handler/headimg/trashheadimg.py","file_name":"trashheadimg.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"613111184","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 13 14:43:47 2019\r\n\r\n@author: imbroscb\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef load_txt(filename,datatype='float'):\r\n    \r\n    if datatype=='float':\r\n        with open(filename) as f:\r\n            temp=[line.split() for line in f]\r\n            sweep=np.zeros((len(temp),len(temp[0])))\r\n            for c in range(len(temp[0])):\r\n                for r in range(len(temp)):\r\n                    sweep[r,c]=float(temp[r][c])  \r\n    else:\r\n        sweep=[]\r\n        with open(filename) as f:\r\n            for line in f:      \r\n                sweep.append(line.strip())\r\n    return sweep\r\n\r\n\r\n","sub_path":"general_functions/loading_files_codes/loading_txt.py","file_name":"loading_txt.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"476496854","text":"from django.contrib.auth import get_user_model\nfrom asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\nfrom .models import Message, Chat\nfrom authentication.models import User\nfrom .views import *\n\nUser = User\n\n\nclass ChatConsumer(WebsocketConsumer):\n\n    def fetch_messages(self, data):\n        messages = get_messages(data['chatSlug'])\n        content = {\n            'command': 'fetch_messages',\n            'messages': self.messages_to_json(get_messages(get_current_chat(data['chatSlug']).slug))\n        }\n        self.send_message(content)\n\n    def new_message(self, data):\n        user = get_user(data['from'])\n        message = Message.objects.create(\n            user=user,\n            text=data['message']\n        )\n        current_chat = get_current_chat(data['chatSlug'])\n        current_chat.messages.add(message)\n        current_chat.save()\n        content = {\n            'command': 'new_message',\n            'message': self.message_to_json(message),\n            'messages': self.messages_to_json(get_messages(get_current_chat(data['chatSlug']).slug))\n        }\n        return self.send_chat_message(content)\n\n    def broadcast_message(self, data):\n        text = data['message']\n        chats = Chat.objects.filter(hospital=Hospital.objects.get(staff=get_user(data['from'])))\n        message = Message.objects.create(user=get_user(data['from']), text=text)\n        message.save()\n        for chat in chats:\n            chat.messages.add(message)\n            chat.save()\n            async_to_sync(self.channel_layer.group_send)(\n                f'chat_{chat.slug}',\n                {\n                    'type': 'chat_message',\n                    'message': {\n                        'command': 'broadcast_message',\n                        'message': self.message_to_json(message),\n                        'messages': self.messages_to_json(chat.messages.all())\n                    }\n                }\n            )\n\n    def messages_to_json(self, messages):\n        result = []\n        for message in messages:\n            result.append(self.message_to_json(message))\n        return result\n\n    def message_to_json(self, message):\n        return {\n            'id': message.id,\n            'user': message.user.email,\n            'message': message.text,\n            'timestamp': message.sent.__str__()\n        }\n\n    commands = {\n        'fetch_messages': fetch_messages,\n        'new_message': new_message,\n        'broadcast_message': broadcast_message,\n    }\n\n    def connect(self):\n        self.room_name = self.scope['url_route']['kwargs']['room_name']\n        self.room_group_name = 'chat_%s' % self.room_name\n        async_to_sync(self.channel_layer.group_add)(\n            self.room_group_name,\n            self.channel_name\n        )\n        self.accept()\n\n    def disconnect(self, close_code):\n        async_to_sync(self.channel_layer.group_discard)(\n            self.room_group_name,\n            self.channel_name\n        )\n\n    def receive(self, text_data):\n        data = json.loads(text_data)\n        self.commands[data['command']](self, data)\n\n    def send_chat_message(self, message):\n        async_to_sync(self.channel_layer.group_send)(\n            self.room_group_name,\n            {\n                'type': 'chat_message',\n                'message': message\n            }\n        )\n\n    def send_message(self, message):\n        self.send(text_data=json.dumps(message))\n\n    def chat_message(self, event):\n        message = event['message']\n        self.send(text_data=json.dumps(message))\n","sub_path":"chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"319732092","text":"import unittest\nfrom easy_spider.network.request import Request\nfrom easy_spider.core.env import async_env\nfrom easy_spider.core.spider import AsyncSpider, RecoverableSpider\nfrom easy_spider.filters.build_in import GenerationFilter, URLRegFilter\n# from test import mock_env\n\n\nclass MySpider(AsyncSpider):\n\n    def init(self):\n        self.num_threads = 4\n        self.start_targets = [\"http://localhost:5000/test_extract\"]\n\n    def handle(self, response):\n        print(response.bs.title)\n        yield from super().handle(response)\n\n\nclass MyRecoverableSpider(RecoverableSpider):\n    def init(self):\n        self.num_threads = 1\n        self.start_targets = [\"https://github.blog/\"]\n        self.filter = URLRegFilter(r\"^https://github\\.blog/page/\\d+/$\")\n        self.num_threads = 1\n\n    def handle(self, response):\n        print(response.bs.title)\n        yield from super().handle(response)\n\n\nclass TestCore(unittest.TestCase):\n\n    def setUp(self) -> None:\n        self.my_spider = MySpider()\n\n    # def test_set_default_method(self):\n    #     r = Request(\"test\")\n    #     self.my_spider.method = 'POST'\n    #     self.my_spider._set_default_request_param(r)\n    #     self.assertEqual(r.method, 'POST')\n    #\n    # def test_core(self):\n    #     self.my_spider.method = 'GET'\n    #     async_env.run(self.my_spider)\n    #\n    # def test_spider_with_generation_filter(self):\n    #     spider = MySpider()\n    #     spider.filter = spider.filter + GenerationFilter(max_generation=1)\n    #     async_env.run(spider)\n\n    def test_recover(self):\n        spider = MyRecoverableSpider()\n        with self.assertRaises(ValueError):\n            async_env.run(spider)\n        spider.name = \"test_recover\"\n        async_env.run(spider)\n\n\nif __name__ == '__main__':\n    unittest.main()\n","sub_path":"test/test_env.py","file_name":"test_env.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"128198410","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# -*- coding: future_fstrings -*-\n\n\"\"\"\ndedupe provides the main user interface for the library the\nDedupe class\n\"\"\"\n\"\"\"\nblockData\nUse blocking rules from predicates to create blocks (preliminary clusters).\n\nThe blocking.Fingerprinter.__call__ function takes the list of\nrecords (data_d) and creates groups of records based on\nthe predicates computed during training. This function takes\nthose results and converts them into a dictionary.\n\nblocks: (dict)\n    key = (str) the stringified predicate rule\n        A predicate rule can involve 1+ predicates. For example, a\n        predicate rule might be:\n        (   SimplePredicate: (wholeFieldPredicate, gender),\n            SimplePredicate: (wholeFieldPredicate, city)\n        )\n        For a record with city = 'Prince George' and gender = 'female',\n        the stringified predicate rule would be:\n            'female:Prince George:0'\n        The final number indicates the predicate rule number (0)\n    value = (list)[str] list of record ids which are in this\n        blocked cluster\n\"\"\"\n\nimport itertools\nimport logging\nimport pickle\nimport multiprocessing\nimport warnings\nimport os\nfrom collections import OrderedDict\nimport tempfile\nimport sqlite3\nimport numpy\nimport json\nimport rlr\nimport dedupe.core as core\nimport dedupe.serializer as serializer\nimport dedupe.blocking as blocking\nimport dedupe.clustering as clustering\nfrom dedupe.distances import Distances\nimport dedupe.labeler as labeler\nimport dedupe.predicates\nfrom typing import (Mapping,\n                    Optional,\n                    List,\n                    Tuple,\n                    Set,\n                    Dict,\n                    Union,\n                    Generator,\n                    Iterable,\n                    Sequence,\n                    BinaryIO,\n                    cast,\n                    TextIO)\nfrom typing_extensions import Literal\nfrom dedupe._typing import (Data,\n                            Clusters,\n                            RecordPairs,\n                            RecordID,\n                            RecordDict,\n                            Blocks,\n                            TrainingExample,\n                            LookupResults,\n                            Links,\n                            TrainingData,\n                            Classifier,\n                            JoinConstraint)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Matching(object):\n    \"\"\"\n    Base Class for Record Matching Classes\n\n    Public methods:\n\n    - `__init__`\n    - `thresholdBlocks`\n    - `matchBlocks`\n    \"\"\"\n\n    def __init__(self, num_cores: Optional[int], **kwargs) -> None:\n        logger.debug(\"Initializing Matching class\")\n        if num_cores is None:\n            self.num_cores = multiprocessing.cpu_count()\n        else:\n            self.num_cores = num_cores\n\n        self._fingerprinter: Optional[blocking.Fingerprinter] = None\n        self.distances: Distances\n        self.classifier: Classifier\n        self.predicates: Sequence[dedupe.predicates.Predicate]\n        self.loaded_indices = False\n\n    @property\n    def fingerprinter(self) -> blocking.Fingerprinter:\n        if self._fingerprinter is None:\n            raise ValueError('the record fingerprinter is not intialized, '\n                             'please run the train method')\n        return self._fingerprinter\n\n    def thresholdBlocks(self, blocks, recall_weight=1.5):  # pragma: nocover\n        \"\"\"\n        Returns the threshold that maximizes the expected F score, a\n        weighted average of precision and recall for a sample of\n        blocked data.\n\n        Arguments:\n\n        blocks -- Sequence of tuples of records, where each tuple is a\n                  set of records covered by a blocking predicate\n\n        recall_weight -- Sets the tradeoff between precision and\n                         recall. I.e. if you care twice as much about\n                         recall as you do precision, set recall_weight\n                         to 2.\n\n        \"\"\"\n        candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks))\n\n        probability = core.scoreDuplicates(candidate_records,\n                                           self.distances,\n                                           self.classifier,\n                                           self.num_cores)['score']\n\n        probability = probability.copy()\n        probability.sort()\n        probability = probability[::-1]\n\n        expected_dupes = numpy.cumsum(probability)\n\n        recall = expected_dupes / expected_dupes[-1]\n        precision = expected_dupes / numpy.arange(1, len(expected_dupes) + 1)\n\n        score = recall * precision / (recall + recall_weight ** 2 * precision)\n\n        i = numpy.argmax(score)\n\n        logger.info('Maximum expected recall and precision')\n        logger.info('recall: %2.3f', recall[i])\n        logger.info('precision: %2.3f', precision[i])\n        logger.info('With threshold: %2.3f', probability[i])\n\n        return probability[i]\n\n    def write_settings(self, file_obj, index=False):  # pragma: no cover\n        \"\"\"\n        Write a settings file containing the\n        data model and predicates to a file object\n\n        Keyword arguments:\n        file_obj -- file object to write settings data into\n        \"\"\"\n\n        pickle.dump(self.distances, file_obj)\n        pickle.dump(self.classifier, file_obj)\n        pickle.dump(self.predicates, file_obj)\n\n        if index:\n            self._writeIndices(file_obj)\n\n    def _writeIndices(self, file_obj):\n        indices = {}\n        doc_to_ids = {}\n        canopies = {}\n        for full_predicate in self.predicates:\n            for predicate in full_predicate:\n                if hasattr(predicate, 'index') and predicate.index:\n                    doc_to_ids[predicate] = dict(predicate.index._doc_to_id)\n                    if hasattr(predicate, \"canopy\"):\n                        canopies[predicate] = predicate.canopy\n                    else:\n                        try:\n                            indices[predicate] = predicate.index._index\n                        except AttributeError:\n                            pass\n\n        pickle.dump(canopies, file_obj)\n        pickle.dump(indices, file_obj)\n        pickle.dump(doc_to_ids, file_obj)\n\n    def score(self, pairs, classifier_threshold=0.5):\n        \"\"\"\n        Scores pairs of records. Returns pairs of tuples of records id and\n        associated probabilites that the pair of records are match\n        Args:\n            pairs: Iterator of pairs of records\n        \"\"\"\n        try:\n            matches = core.scoreDuplicates(pairs,\n                                           self.distances,\n                                           self.classifier,\n                                           self.num_cores,\n                                           classifier_threshold)\n        except RuntimeError:\n            raise RuntimeError('''\n                You need to either turn off multiprocessing or protect\n                the calls to the Dedupe methods with a\n                `if __name__ == '__main__'` in your main module, see\n                https://docs.python.org/3/library/multiprocessing.html#the-spawn-and-forkserver-start-methods''')\n\n        return matches\n\n\nclass IntegralMatching(Matching):\n    \"\"\"\n    This class is for linking class where we need to score all possible\n    pairs before deciding on any matches\n    \"\"\"\n\n    def score(self,\n              pairs: RecordPairs,\n              classifier_threshold: float = 0.5) -> numpy.ndarray:\n        \"\"\"\n        Scores pairs of records. Returns pairs of tuples of records id and\n        associated probabilites that the pair of records are match\n        Args:\n            pairs: Iterator of pairs of records\n        \"\"\"\n        try:\n            matches = core.scoreDuplicates(pairs,\n                                           self.distances,\n                                           self.classifier,\n                                           self.num_cores,\n                                           classifier_threshold)\n        except RuntimeError:\n            raise RuntimeError('''\n                You need to either turn off multiprocessing or protect\n                the calls to the Dedupe methods with a\n                `if __name__ == '__main__'` in your main module, see\n                https://docs.python.org/3/library/multiprocessing.html#the-spawn-and-forkserver-start-methods''')\n\n        return matches\n\n\nclass DedupeMatching(Matching):\n    \"\"\"\n    Class for Deduplication, extends Matching.\n\n    Use DedupeMatching when you have a dataset that can contain\n    multiple references to the same entity.\n\n    Public methods:\n\n    - `__init__`\n    - `match`\n    - `threshold`\n    \"\"\"\n\n    ActiveLearner = labeler.DedupeDisagreementLearner\n\n    def __init__(self, *args, **kwargs):\n        logger.debug(\"Initializing DedupeMatching, calling super class Matching constructor\")\n        super().__init__(*args, **kwargs)\n        self._cluster = clustering.cluster\n\n    def partition(self, data, classifier_threshold=0.5, cluster_threshold=0.5,\n                  generator=False):  # pragma: no cover\n        \"\"\"Identifies records that all refer to the same entity, returns\n        tuples containing a set of record ids and a confidence score as a\n        float between 0 and 1. The record_ids within each set should\n        refer to the same entity and the confidence score is a measure\n        of our confidence that all the records in a cluster refer to\n        the same entity.\n\n        This method should only used for small to moderately sized\n        datasets for larger data, you need may need to generate your\n        own pairs of records and feed them to :func:`~score`.\n\n        Args:\n            data: Dictionary of records, where the keys are record_ids\n                  and the values are dictionaries with the keys being\n                  field names\n            threshold: Number between 0 and 1 (Default is 0.5).  We\n                       will only consider put together records into\n                       clusters if the `cophenetic similarity\n                       `_ of\n                       the cluster is greater than the threshold.\n                       Lowering the number will increase recall,\n                       raising it will increase precision\n\n        Returns:\n            clusters: (list)[tuple] list of clustered duplicates\n                'idx' = id of record\n                'scorex' = score, float between 0 and 1\n                [\n                    (('id1', 'id2', 'id3'), [score1, score2, score3])\n                ]\n\n        .. code:: python\n           > clusters = matcher.partition(data, threshold=0.5)\n           > print(duplicates)\n           [((1, 2, 3), (0.790, 0.860, 0.790)),\n            ((4, 5), (0.720, 0.720)),\n            ((10, 11), (0.899, 0.899))]\n\n        \"\"\"\n        logger.debug(\"DedupeMatching.partition\")\n        pairs = self.pairs(data)\n        pair_scores = self.score(pairs, classifier_threshold=classifier_threshold)\n        clusters = self.cluster(pair_scores, threshold=cluster_threshold)\n\n        try:\n            mmap_file = pair_scores.filename\n            del pair_scores\n            os.remove(mmap_file)\n        except AttributeError:\n            pass\n\n        if generator:\n            return clusters\n        else:\n            return list(clusters)\n\n    def _add_singletons(self, data, clusters):\n\n        singletons = set(data.keys())\n\n        for record_ids, score in clusters:\n            singletons.difference_update(record_ids)\n            yield (record_ids, score)\n\n        for singleton in singletons:\n            yield (singleton, ), (1.0, )\n\n    def pairs(self, data):\n        \"\"\"Yield pairs of records that share common fingerprints.\n\n        A fingerprint is a combination of n predicates\n        Each pair will occur at most once. If you override this\n        method, you need to take care to ensure that this remains\n        true, as downstream methods, particularly :func:`cluster`, assumes\n        that every pair of records is compared no more than once.\n\n        Args:\n            data: (dict) Dictionary of records, where the keys are record_ids\n                  and the values are dictionaries with the keys being\n                  field names i.e.\n\n                  {\n                    'record_id': record\n                  }\n\n        Example:\n\n        Suppose you have the following data:\n        .. code:: python\n            > print(data)\n            {'0': {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'},\n             '1': {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'},\n             '2': {'first_name': 'Sam', 'last_name': 'Smith', 'address': '123 Main'}}\n\n        To find out which predicates are used for your fingerprints:\n        .. code:: python\n            > print(deduper.fingerprinter.predicates)\n            ((SimplePredicate: (sortedAcronym, first_name),\n              SimplePredicate: (sortedAcronym, last_name)),\n             (SimplePredicate: (wholeFieldPredicate, last_name),\n             (SimplePredicate: (wholeFieldPredicate, address))))\n\n        Then your output will be:\n        .. code:: python\n            > pairs = deduper.pairs(data)\n            > print(list(pairs))\n            [(('0', {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'}),\n              ('1', {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'})),\n             (('0', {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'}),\n              ('2', {'first_name': 'Sam', 'last_name': 'Smith', 'address': '123 Main'})),\n             (('1', {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'}),\n              ('2', {'first_name': 'Sam', 'last_name': 'Smith', 'address': '123 Main'}))\n             ]\n\n        In this example, because of the predicates we had, all the records had some similarity.\n        If, on the other hand, our predicates had been:\n        .. code:: python\n            > print(deduper.fingerprinter.predicates)\n            ((SimplePredicate: (sortedAcronym, first_name),\n              SimplePredicate: (sortedAcronym, last_name)),\n             (SimplePredicate: (wholeFieldPredicate, first_name),\n             (SimplePredicate: (wholeFieldPredicate, address))))\n\n        then our output would be:\n        .. code:: python\n            > pairs = deduper.pairs(data)\n            > print(list(pairs))\n            [(('0', {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'}),\n              ('1', {'first_name': 'Pat', 'last_name': 'Smith', 'address': '123 Main'}))\n             ]\n        \"\"\"\n\n        self.fingerprinter.index_all(data)\n\n        id_type = core.sqlite_id_type(data)\n\n        # Blocking and pair generation are typically the first memory\n        # bottlenecks, so we'll use sqlite3 to avoid doing them in memory\n        with tempfile.TemporaryDirectory() as temp_dir:\n            con = sqlite3.connect(temp_dir + '/blocks.db')\n\n            con.execute('''CREATE TABLE blocking_map\n                           (block_key text, record_id {id_type})\n                        '''.format(id_type=id_type))\n\n            con.executemany(\"INSERT INTO blocking_map values (?, ?)\",\n                            self.fingerprinter(data.items()))\n\n            self.fingerprinter.reset_indices()\n\n            con.execute('''CREATE INDEX block_key_idx\n                           ON blocking_map (block_key)''')\n            pairs = con.execute('''SELECT DISTINCT a.record_id, b.record_id\n                                   FROM blocking_map a\n                                   INNER JOIN blocking_map b\n                                   USING (block_key)\n                                   WHERE a.record_id < b.record_id''')\n\n            for a_record_id, b_record_id in pairs:\n                yield ((a_record_id, data[a_record_id]),\n                       (b_record_id, data[b_record_id]))\n\n            pairs.close()\n            con.close()\n\n    def cluster(self,\n                scores: numpy.ndarray,\n                threshold: float = 0.5) -> Clusters:\n        r\"\"\"From the similarity scores of pairs of records, decide which groups\n        of records are all referring to the same entity.\n\n        Yields tuples containing a sequence of record ids and corresponding\n        sequence of confidence score as a float between 0 and 1. The\n        record_ids within each set should refer to the same entity and the\n        confidence score is a measure of our confidence a particular entity\n        belongs in the cluster.\n\n        Each confidence scores is a measure of how similar the record is\n        to the other records in the cluster. Let :math:`\\phi(i,j)` be the pair-wise\n        similarity between records :math:`i` and :math:`j`. Let :math:`N` be the number of\n        records in the cluster.\n\n        .. math::\n           \\text{confidence score}_i = 1 - \\sqrt {\\frac{\\sum_{j}^N (1 - \\phi(i,j))^2}{N -1}}\n        This measure is similar to the average squared distance\n        between the focal record and the other records in the\n        cluster. These scores can be `combined to give a total score\n        for the cluster\n        `_.\n\n        .. math::\n           \\text{cluster score} = 1 - \\sqrt { \\frac{\\sum_i^N(1 - \\mathrm{score}_i)^2 \\cdot (N - 1) } { 2 N^2}}\n\n        Args:\n            scores: a numpy `structured array `_\n                with a dtype of `[('pairs', id_type, 2),\n                    ('score', 'f4')]` where dtype is either a str\n                    or int, and score is a number between 0 and\n                    1. The 'pairs' column contains pairs of ids of\n                    the records compared and the 'score' column\n                    should contains the similarity score for that\n                    pair of records.\n                    For each pair, the smaller id should be first.\n            threshold: Number between 0 and 1. We will only consider\n                       put together records into clusters if the\n                       `cophenetic similarity\n                       `_ of\n                       the cluster is greater than the threshold.\n                       Lowering the number will increase recall,\n                       raising it will increase precision\n                       Defaults to 0.5.\n        Yields:\n            (tuple)[tuple]: a tuple of two tuples, where the first tuple is the\n                list of record_ids in a cluster, and the second tuple is the\n                corresponding probabilities of being in that cluster.\n\n        Example:\n        .. code:: python\n\n           > pairs = matcher.pairs(data)\n           > scores = matcher.scores(pairs)\n           > clusters = matcher.cluster(scores)\n           > print(list(clusters))\n           [((1, 2, 3), (0.790, 0.860, 0.790)),\n            ((4, 5), (0.720, 0.720)),\n            ((10, 11), (0.899, 0.899))]\n        \"\"\"\n\n        logger.debug(\"matching done, begin clustering\")\n\n        yield from clustering.cluster(scores, threshold)\n\n\nclass RecordLinkMatching(Matching):\n    \"\"\"\n    Class for Record Linkage, extends Matching.\n\n    Use RecordLinkMatching when you have two datasets that you want to merge\n    where each dataset, individually, contains no duplicates.\n\n    Public methods:\n\n    - `__init__`\n    - `match`\n    - `threshold`\n    \"\"\"\n\n    ActiveLearner = labeler.RecordLinkDisagreementLearner\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self._cluster = clustering.greedyMatching\n\n    def matchBlocks(self, blocks, classifier_threshold=.5,\n                    cluster_threshold=0.5, *args, **kwargs):\n        \"\"\"\n        Partitions blocked data and generates a sequence of clusters,\n        where each cluster is a tuple of record ids\n\n        Keyword arguments:\n\n        blocks -- Sequence of tuples of records, where each tuple is a\n                  set of records covered by a blocking predicate\n\n        threshold -- Number between 0 and 1 (default is .5). We will\n                      only consider as duplicates record pairs as\n                      duplicates if their estimated duplicate\n                      likelihood is greater than the threshold.\n\n                      Lowering the number will increase recall,\n                      raising it will increase precision\n\n        \"\"\"\n        logger.debug(\"RecordLinkMatching.matchBlocks\")\n        candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks))\n        matches = core.scoreDuplicates(candidate_records,\n                                       self.distances,\n                                       self.classifier,\n                                       self.num_cores,\n                                       classifier_threshold)\n        logger.debug(\"matching done, begin clustering\")\n\n        for cluster in self._cluster(matches, cluster_threshold, *args, **kwargs):\n            yield cluster\n\n        try:\n            match_file = matches.filename\n            del matches\n            os.remove(match_file)\n        except AttributeError:\n            pass\n\n    def match(self, data_1, data_2, threshold=0.5, generator=False):  # pragma: no cover\n        \"\"\"\n        Identifies pairs of records that refer to the same entity, returns\n        tuples containing a set of record ids and a confidence score as a float\n        between 0 and 1. The record_ids within each set should refer to the\n        same entity and the confidence score is the estimated probability that\n        the records refer to the same entity.\n\n        This method should only used for small to moderately sized datasets\n        for larger data, use matchBlocks\n\n        Arguments:\n        data_1    -- Dictionary of records from first dataset, where the\n                     keys are record_ids and the values are dictionaries\n                     with the keys being field names\n\n        data_2    -- Dictionary of records from second dataset, same form\n                     as data_1\n\n        threshold -- Number between 0 and 1 (default is .5). We will consider\n                     records as potential duplicates if the predicted\n                     probability of being a duplicate is above the threshold.\n\n                     Lowering the number will increase recall, raising it\n                     will increase precision\n        \"\"\"\n\n        blocked_pairs = self._blockData(data_1, data_2)\n        clusters = self.matchBlocks(blocked_pairs, threshold)\n\n        if generator:\n            return clusters\n        else:\n            return list(clusters)\n\n    def threshold(self, data_1, data_2, recall_weight=1.5):  # pragma: no cover\n        \"\"\"\n        Returns the threshold that maximizes the expected F score,\n        a weighted average of precision and recall for a sample of\n        data.\n\n        Arguments:\n        data_1        --  Dictionary of records from first dataset, where the\n                          keys are record_ids and the values are dictionaries\n                          with the keys being field names\n\n        data_2        --  Dictionary of records from second dataset, same form\n                          as data_1\n\n        recall_weight -- Sets the tradeoff between precision and\n                         recall. I.e. if you care twice as much about\n                         recall as you do precision, set recall_weight\n                         to 2.\n        \"\"\"\n\n        blocked_pairs = self._blockData(data_1, data_2)\n        return self.thresholdBlocks(blocked_pairs, recall_weight)\n\n    def _blockedPairs(self, blocks):\n        \"\"\"\n        Generate tuples of pairs of records from a block of records\n\n        Arguments:\n\n        blocks -- an iterable sequence of blocked records\n        \"\"\"\n\n        block, blocks = core.peek(blocks)\n        self._checkBlock(block)\n\n        product = itertools.product\n\n        pairs = (product(base, target) for base, target in blocks)\n\n        return pairs\n\n    def _blockGenerator(self, messy_data, blocked_records):\n        block_groups = itertools.groupby(self.fingerprinter(messy_data.items()),\n                                         lambda x: x[1])\n\n        for i, (record_id, block_keys) in enumerate(block_groups):\n            if i % 100 == 0:\n                logger.info(\"%s records\" % i)\n\n            A = [(record_id, messy_data[record_id], set())]\n\n            B = {}\n\n            for block_key, _ in block_keys:\n                if block_key in blocked_records:\n                    B.update(blocked_records[block_key])\n\n            B = [(rec_id, record, set())\n                 for rec_id, record\n                 in B.items()]\n\n            if B:\n                yield (A, B)\n\n    def _blockData(self, data_1, data_2):\n\n        blocked_records = {}\n\n        if not self.loaded_indices:\n            self.fingerprinter.index_all(data_2)\n\n        for block_key, record_id in self.fingerprinter(data_2.items(), target=True):\n            block = blocked_records.setdefault(block_key, {})\n            block[record_id] = data_2[record_id]\n\n        for each in self._blockGenerator(data_1, blocked_records):\n            yield each\n\n    def _checkBlock(self, block):\n        if block:\n            try:\n                base, target = block\n            except ValueError:\n                raise ValueError(\"Each block must be a made up of two \"\n                                 \"sequences, (base_sequence, target_sequence)\")\n\n            if base:\n                try:\n                    base_id, base_record, base_smaller_ids = base[0]\n                except ValueError:\n                    raise ValueError(\n                        \"Each sequence must be made up of 3-tuple \"\n                        \"like (record_id, record, covered_blocks)\")\n                self.distances.check(base_record)\n            if target:\n                try:\n                    target_id, target_record, target_smaller_ids = target[0]\n                except ValueError:\n                    raise ValueError(\n                        \"Each sequence must be made up of 3-tuple \"\n                        \"like (record_id, record, covered_blocks)\")\n                self.distances.check(target_record)\n\n\nclass StaticMatching(Matching):\n    \"\"\"\n    Class for initializing a dedupe object from a settings file,\n    extends Matching.\n\n    Public methods:\n    - __init__\n    \"\"\"\n\n    def __init__(self,\n                 settings_file,\n                 num_cores=None, **kwargs):  # pragma: no cover\n        \"\"\"\n        Initialize from a settings file\n        #### Example usage\n\n            # initialize from a settings file\n            with open('my_learned_settings', 'rb') as f:\n                deduper = dedupe.StaticDedupe(f)\n\n        #### Keyword arguments\n\n        `settings_file`\n        A file object containing settings data.\n\n\n        Settings files are typically generated by saving the settings\n        learned from ActiveMatching. If you need details for this\n        file see the method [`write_settings`][[api.py#write_settings]].\n        \"\"\"\n        Matching.__init__(self, num_cores, **kwargs)\n\n        try:\n            self.distances = pickle.load(settings_file)\n            self.classifier = pickle.load(settings_file)\n            self.predicates = pickle.load(settings_file)\n        except (KeyError, AttributeError):\n            raise SettingsFileLoadingException(\n                \"This settings file is not compatible with \"\n                \"the current version of dedupe. This can happen \"\n                \"if you have recently upgraded dedupe.\")\n        except:  # noqa: E722\n            raise SettingsFileLoadingException(\n                \"Something has gone wrong with loading the settings file. \"\n                \"Try deleting the file\")\n\n        try:\n            self._loadIndices(settings_file)\n        except EOFError:\n            pass\n        except (KeyError, AttributeError):\n            raise SettingsFileLoadingException(\n                \"This settings file is not compatible with \"\n                \"the current version of dedupe. This can happen \"\n                \"if you have recently upgraded dedupe.\")\n        except:  # noqa: E722\n            raise SettingsFileLoadingException(\n                \"Something has gone wrong with loading the settings file. \"\n                \"Try deleting the file\")\n\n        logger.info(self.predicates)\n\n        self._fingerprinter = blocking.Fingerprinter(self.predicates)\n\n    def _loadIndices(self, settings_file):\n        canopies = pickle.load(settings_file)\n        indices = pickle.load(settings_file)\n        doc_to_ids = pickle.load(settings_file)\n\n        for full_predicate in self.predicates:\n            for predicate in full_predicate:\n                if hasattr(predicate, \"index\") and predicate.index is None:\n                    predicate.index = predicate.initIndex()\n                    max_id = max(doc_to_ids[predicate].values())\n                    predicate.index._doc_to_id = core.Enumerator(max_id + 1,\n                                                                 doc_to_ids[predicate])\n\n                    if hasattr(predicate, \"canopy\"):\n                        predicate.canopy = canopies[predicate]\n                    else:\n                        try:\n                            predicate.index._index = indices[predicate]\n                        except KeyError:\n                            pass\n\n        self.loaded_indices = True\n\n\nclass ActiveMatching(Matching):\n    classifier = rlr.RegularizedLogisticRegression()\n    ActiveLearner = None\n\n    \"\"\"\n    Class for training dedupe extends Matching.\n\n    Public methods:\n    - __init__\n    - readTraining\n    - train\n    - write_settings\n    - write_training\n    - uncertainPairs\n    - markPairs\n    - cleanupTraining\n    \"\"\"\n\n    def __init__(self,\n                 variable_definition,\n                 data_sample=None,\n                 num_cores=None, **kwargs):\n        \"\"\"\n        Initialize from a data model and data sample.\n\n        #### Example usage\n\n            # initialize from a defined set of fields\n            variable_definition = [{'field' : 'Site name', 'type': 'String'},\n                      {'field' : 'Address', 'type': 'String'},\n                      {'field' : 'Zip', 'type': 'String',\n                       'Has Missing':True},\n                      {'field' : 'Phone', 'type': 'String',\n                       'Has Missing':True},\n                     ]\n\n            deduper = dedupe.Dedupe(fields)\n\n\n        #### Additional detail\n\n        A field definition is a list of dictionaries where each dictionary\n        describes a variable to use for comparing records.\n\n        For details about variable types, check the documentation.\n        `_\n        \"\"\"\n        logger.debug(\"Initializing ActiveMatching class\")\n        Matching.__init__(self, num_cores, **kwargs)\n\n        self.distances = Distances(variable_definition)\n\n        if data_sample is not None:\n            raise UserWarning(\n                'data_sample is deprecated, use the .sample method')\n\n        self.active_learner = None\n\n        self.training_pairs = OrderedDict({u'distinct': [],\n                                           u'match': []})\n\n        self._fingerprinter = None\n\n    def cleanupTraining(self):  # pragma: no cover\n        '''\n        Clean up data we used for training. Free up memory.\n        '''\n        del self.training_pairs\n        del self.active_learner\n\n    def _read_training(self, training_file):\n        '''\n        Read training from previously built training data file object\n\n        Arguments:\n\n        training_file -- file object containing the training data\n        '''\n\n        logger.info('reading training from file')\n        training_pairs = json.load(training_file,\n                                   cls=serializer.dedupe_decoder)\n\n        try:\n            self.mark_pairs(training_pairs)\n        except AttributeError as e:\n            if \"Attempting to block with an index predicate without indexing records\" in str(e):\n                raise UserWarning('Training data has records not known '\n                                  'to the active learner. Read training '\n                                  'in before initializing the active '\n                                  'learner with the sample method, or '\n                                  'use the prepare_training method.')\n            else:\n                raise\n\n    def train(self, recall=0.95, index_predicates=True):  # pragma: no cover\n        \"\"\"\n        Keyword arguments:\n\n        maximum_comparisons -- The maximum number of comparisons a\n                               blocking rule is allowed to make.\n\n                               Defaults to 1000000\n\n        recall -- The proportion of true dupe pairs in our training\n                  data that that we the learned blocks must cover. If\n                  we lower the recall, there will be pairs of true\n                  dupes that we will never directly compare.\n\n                  recall should be a float between 0.0 and 1.0, the default\n                  is 0.95\n\n        index_predicates -- Should dedupe consider predicates that\n                            rely upon indexing the data. Index predicates can\n                            be slower and take substantial memory.\n\n                            Defaults to True.\n        \"\"\"\n        logger.debug(\"ActiveMatching.train\")\n        examples, y = flatten_training(self.training_pairs)\n        logger.debug(\"Fit classifier with active label training data\")\n        self.classifier.fit(self.distances.compute_distance_matrix(examples), y)\n        logger.debug(f\"Number of matches: {len(self.training_pairs['match'])}\")\n        self.predicates = self.active_learner.learn_predicates(\n            recall, index_predicates)\n        self._fingerprinter = blocking.Fingerprinter(self.predicates)\n        self._fingerprinter.reset_indices()\n\n    def write_training(self, file_obj):  # pragma: no cover\n        \"\"\"\n        Write to a json file that contains labeled examples\n\n        Keyword arguments:\n        file_obj -- file object to write training data to\n        \"\"\"\n\n        json.dump(self.training_pairs,\n                  file_obj,\n                  default=serializer._to_json,\n                  ensure_ascii=True)\n\n    def uncertain_pairs(self):\n        '''\n        Provides a list of the pairs of records that dedupe is most\n        curious to learn if they are matches or distinct.\n\n        Useful for user labeling.\n\n        '''\n\n        return self.active_learner.pop()\n\n    def mark_pairs(self, labeled_pairs):\n        '''\n        Argument :\n\n        labeled_pairs -- A dictionary with two keys, `match` and `distinct`\n                         the values are lists that can contain pairs of records\n        '''\n        self._checkTrainingPairs(labeled_pairs)\n\n        for label, examples in labeled_pairs.items():\n            self.training_pairs[label].extend(examples)\n\n        if self.active_learner:\n            examples, y = flatten_training(labeled_pairs)\n            self.active_learner.mark(examples, y)\n\n    def _checkTrainingPairs(self, labeled_pairs):\n        try:\n            labeled_pairs.items()\n            labeled_pairs[u'match']\n            labeled_pairs[u'distinct']\n        except (AttributeError, KeyError):\n            raise ValueError('labeled_pairs must be a dictionary with keys '\n                             '\"distinct\" and \"match\"')\n\n        if labeled_pairs[u'match']:\n            pair = labeled_pairs[u'match'][0]\n            self._checkRecordPair(pair)\n\n        if labeled_pairs[u'distinct']:\n            pair = labeled_pairs[u'distinct'][0]\n            self._checkRecordPair(pair)\n\n        if not labeled_pairs[u'distinct'] and not labeled_pairs[u'match']:\n            warnings.warn(\"Didn't return any labeled record pairs\")\n\n    def _checkRecordPair(self, record_pair):\n        try:\n            a, b = record_pair\n        except ValueError:\n            raise ValueError(\"The elements of data_sample must be pairs \"\n                             \"of record_pairs\")\n        try:\n            record_pair[0].keys() and record_pair[1].keys()\n        except AttributeError:\n            raise ValueError(\"A pair of record_pairs must be made up of two \"\n                             \"dictionaries \")\n\n        self.distances.check(record_pair[0])\n        self.distances.check(record_pair[1])\n\n\nclass StaticDedupe(DedupeMatching, StaticMatching):\n    \"\"\"\n    Mixin Class for Static Deduplication\n    \"\"\"\n\n\nclass Dedupe(DedupeMatching, ActiveMatching):\n    \"\"\"\n    Class for active learning deduplication. Use deduplication when you have\n    data that can contain multiple records that can all refer to the same\n    entity.\n    \"\"\"\n\n    canopies = True\n\n    def prepare_training(self,\n                         data: Data,\n                         training_file: TextIO = None,\n                         sample_size: int = 1500,\n                         blocked_proportion: float = 0.9,\n                         original_length: int = None) -> None:\n        \"\"\"Sets up the learner.\n\n        Initialize the active learner with your data and, optionally,\n        existing training data.\n\n        Args:\n            data: (dict) Dictionary of records, where the keys are\n                  record_ids and the values are dictionaries\n                  with the keys being field names\n            training_file: file object containing training data\n            sample_size: (int) Size of the sample to draw\n            blocked_proportion: The proportion of record pairs to be sampled from similar records, as opposed to randomly selected pairs. Defaults to 0.9.\n            original_length: If `data` is a subsample of all your data,\n                             `original_length` should be the size of\n                             your complete data. By default,\n                             `original_length` defaults to the length of\n                             `data`.\n\n        .. code:: python\n           matcher.prepare_training(data_d, 150000, .5)\n           # or\n           with open('training_file.json') as f:\n               matcher.prepare_training(data_d, training_file=f)\n\n        \"\"\"\n\n        logger.debug(\"Preparing training\")\n        if training_file:\n            logger.debug(\"Reading active labels from training file\")\n            self._read_training(training_file)\n        self._sample(data, sample_size, blocked_proportion, original_length)\n\n    def _sample(self,\n                data: Data,\n                sample_size: int = 15000,\n                blocked_proportion: float = 0.5,\n                original_length: int = None) -> None:\n        \"\"\"Draw a sample of record pairs from the dataset\n        (a mix of random pairs & pairs of similar records)\n        and initialize active learning with this sample\n\n        Args:\n\n            data: (dict) Dictionary of records, where the keys are\n                record_ids and the values are dictionaries with the keys being\n                field names\n            sample_size: (int) Size of the sample to draw\n            blocked_proportion: Proportion of the sample that will be blocked\n            original_length: Length of original data, should be set if `data` is\n                                   a sample of full data\n\n\n        \"\"\"\n        logger.debug(\"api.Dedupe.sample\")\n        self._checkData(data)\n\n        if not original_length:\n            original_length = len(data)\n\n        # We need the active learner to know about all our\n        # existing training data, so add them to data dictionary\n        examples, y = flatten_training(self.training_pairs)\n\n        self.active_learner = self.ActiveLearner(self.distances,\n                                                 data,\n                                                 blocked_proportion,\n                                                 sample_size,\n                                                 original_length,\n                                                 index_include=examples)\n        logger.debug(\"Marking active training data\")\n        self.active_learner.mark(examples, y)\n\n    def _checkData(self, data):\n        \"\"\"Check that data is not empty and that each record has required fields.\n        \"\"\"\n        logger.debug(\"Checking input data is valid\")\n        if len(data) == 0:\n            raise ValueError(\n                'Dictionary of records is empty.')\n\n        self.distances.check(next(iter(data.values())))\n\n\nclass StaticRecordLink(RecordLinkMatching, StaticMatching):\n    \"\"\"\n    Mixin Class for Static Record Linkage\n    \"\"\"\n\n\nclass RecordLink(RecordLinkMatching, ActiveMatching):\n    \"\"\"\n    Mixin Class for Active Learning Record Linkage\n\n    Public Methods\n    - sample\n    \"\"\"\n    canopies = False\n\n    def prepare_training(self,\n                         data_1,\n                         data_2,\n                         training_file=None,\n                         sample_size=15000,\n                         blocked_proportion=0.5,\n                         original_length_1=None,\n                         original_length_2=None):\n        '''\n        Sets up the learner.\n        Arguments:\n\n        data_1      -- Dictionary of records from first dataset, where the\n                       keys are record_ids and the values are dictionaries\n                       with the keys being field names\n        data_2      -- Dictionary of records from second dataset, same\n                       form as data_1\n        training_file -- file object containing training data\n        '''\n\n        if training_file:\n            self._read_training(training_file)\n        self.sample(data_1,\n                    data_2,\n                    sample_size,\n                    blocked_proportion,\n                    original_length_1,\n                    original_length_2)\n\n    def sample(self,\n               data_1,\n               data_2,\n               sample_size=15000,\n               blocked_proportion=0.5,\n               original_length_1=None,\n               original_length_2=None):\n        '''\n        Draws a random sample of combinations of records from\n        the first and second datasets, and initializes active\n        learning with this sample\n\n        Arguments:\n\n        data_1      -- Dictionary of records from first dataset, where the\n                       keys are record_ids and the values are dictionaries\n                       with the keys being field names\n        data_2      -- Dictionary of records from second dataset, same\n                       form as data_1\n\n        sample_size -- Size of the sample to draw\n        '''\n        self._checkData(data_1, data_2)\n\n        # We need the active learner to know about all our\n        # existing training data, so add them to data dictionaries\n        examples, y = flatten_training(self.training_pairs)\n\n        self.active_learner = self.ActiveLearner(self.distances,\n                                                 data_1,\n                                                 data_2,\n                                                 blocked_proportion,\n                                                 sample_size,\n                                                 original_length_1,\n                                                 original_length_2,\n                                                 index_include=examples)\n\n        self.active_learner.mark(examples, y)\n\n    def _checkData(self, data_1, data_2):\n        if len(data_1) == 0:\n            raise ValueError(\n                'Dictionary of records from first dataset is empty.')\n        elif len(data_2) == 0:\n            raise ValueError(\n                'Dictionary of records from second dataset is empty.')\n\n        self.distances.check(next(iter(data_1.values())))\n        self.distances.check(next(iter(data_2.values())))\n\n\nclass GazetteerMatching(RecordLinkMatching):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        self._cluster = clustering.gazetteMatching\n\n    def _blockData(self, messy_data):\n        for each in self._blockGenerator(messy_data, self.blocked_records):\n            yield each\n\n    def index(self, data):  # pragma: no cover\n\n        self.fingerprinter.index_all(data)\n\n        for block_key, record_id in self.fingerprinter(data.items(), target=True):\n            if block_key not in self.blocked_records:\n                self.blocked_records[block_key] = {}\n            self.blocked_records[block_key][record_id] = data[record_id]\n\n    def unindex(self, data):  # pragma: no cover\n\n        for field in self.fingerprinter.index_fields:\n            self.fingerprinter.unindex((record[field]\n                                  for record\n                                  in data.values()),\n                                 field)\n\n        for block_key, record_id in self.fingerprinter(data.items()):\n            try:\n                del self.blocked_records[block_key][record_id]\n            except KeyError:\n                pass\n\n    def matchBlocks(self, blocks, threshold=.5, *args, **kwargs):\n        \"\"\"\n        Partitions blocked data and generates a sequence of clusters, where\n        each cluster is a tuple of record ids\n\n        Keyword arguments:\n\n        blocks -- Sequence of tuples of records, where each tuple is a\n                  set of records covered by a blocking predicate\n\n        threshold -- Number between 0 and 1 (default is .5). We will\n                      only consider as duplicates record pairs as\n                      duplicates if their estimated duplicate\n                      likelihood is greater than the threshold.\n\n                      Lowering the number will increase recall,\n                      raising it will increase precision\n\n        \"\"\"\n        candidate_records = self._blockedPairs(blocks)\n\n        matches = core.scoreGazette(candidate_records,\n                                    self.distances,\n                                    self.classifier,\n                                    self.num_cores,\n                                    threshold=threshold)\n\n        logger.debug(\"matching done, begin clustering\")\n\n        return self._cluster(matches, *args, **kwargs)\n\n    def match(self, messy_data, threshold=0.5, n_matches=1, generator=False):  # pragma: no cover\n        \"\"\"Identifies pairs of records that refer to the same entity, returns\n        tuples containing a set of record ids and a confidence score as a float\n        between 0 and 1. The record_ids within each set should refer to the\n        same entity and the confidence score is the estimated probability that\n        the records refer to the same entity.\n\n        This method should only used for small to moderately sized datasets\n        for larger data, use matchBlocks\n\n        Arguments:\n        messy_data -- Dictionary of records from messy dataset, where the\n                      keys are record_ids and the values are dictionaries with\n                      the keys being field names\n\n        threshold -- Number between 0 and 1 (default is .5). We will consider\n                     records as potential duplicates if the predicted\n                     probability of being a duplicate is above the threshold.\n\n                     Lowering the number will increase recall, raising it\n                     will increase precision\n\n        n_matches -- Maximum number of possible matches from the canonical\n                     record set to match against each record in the messy\n                     record set\n        \"\"\"\n        blocked_pairs = self._blockData(messy_data)\n\n        clusters = self.matchBlocks(blocked_pairs, threshold, n_matches)\n\n        clusters = (cluster for cluster in clusters if len(cluster))\n\n        if generator:\n            return clusters\n        else:\n            return list(clusters)\n\n    def write_settings(self, file_obj, index=False):  # pragma: no cover\n        \"\"\"\n        Write a settings file containing the\n        data model and predicates to a file object\n\n        Keyword arguments:\n        file_obj -- file object to write settings data into\n        \"\"\"\n        super().write_settings(file_obj, index)\n\n        if index:\n            pickle.dump(self.blocked_records, file_obj)\n\n\nclass Gazetteer(RecordLink, GazetteerMatching):\n\n    def __init__(self, *args, **kwargs):  # pragma: no cover\n        super().__init__(*args, **kwargs)\n        self.blocked_records = OrderedDict({})\n\n\nclass StaticGazetteer(StaticRecordLink, GazetteerMatching):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        settings_file = args[0]\n\n        try:\n            self.blocked_records = pickle.load(settings_file)\n        except EOFError:\n            self.blocked_records = OrderedDict({})\n        except (KeyError, AttributeError):\n            raise SettingsFileLoadingException(\n                \"This settings file is not compatible with \"\n                \"the current version of dedupe. This can happen \"\n                \"if you have recently upgraded dedupe.\")\n        except:  # noqa: E722\n            raise SettingsFileLoadingException(\n                \"Something has gone wrong with loading the settings file. \"\n                \"Try deleting the file\")\n\n\nclass EmptyTrainingException(Exception):\n    pass\n\n\nclass SettingsFileLoadingException(Exception):\n    pass\n\n\ndef flatten_training(training_pairs):\n    \"\"\"Convert active label training pairs to two lists.\n\n    Args:\n        :training_pairs: (dict) dictionary of either 'match' or 'distinct', where\n            'match' is a list of pairs of records which are the same, and\n            'distinct' is a list of pairs of records which are different\n\n        {\n            'match': [\n                [record_1, record_2]\n            ],\n            'distinct': [\n                [record_1, record_3]\n            ]\n        }\n\n    Returns:\n        :examples: (list)[list] ordered list of all the record pairs (distinct and match)\n\n            [\n                [record_1, record_2],\n                [record_1, record_3]\n            ]\n        :y: (list)[int] list of either 1 or 0, corresponding to examples list\n            1 = match\n            0 = distinct\n    \"\"\"\n    examples = []\n    y = []\n    for label, pairs in training_pairs.items():\n        for pair in pairs:\n            if label == 'match':\n                y.append(1)\n                examples.append(pair)\n            elif label == 'distinct':\n                y.append(0)\n                examples.append(pair)\n    return examples, numpy.array(y)\n","sub_path":"dedupe/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":50842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"150380595","text":"\"\"\"\nMIT License\n\nCopyright (c) 2020 Shantanu Ghosh\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport statistics\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom DCN_network import DCN_network\nfrom Utils import Utils\nfrom dataloader import DataLoader\nfrom shallow_train import shallow_train\n\n\nclass Model_25_1_25:\n    def run_all_expeiments(self):\n        csv_path = \"Dataset/ihdp_sample.csv\"\n        split_size = 0.8\n        device = Utils.get_device()\n        print(device)\n        results_list = []\n\n        train_parameters_SAE = {\n            \"epochs\": 200,\n            \"lr\": 0.0001,\n            \"batch_size\": 32,\n            \"shuffle\": True,\n            \"sparsity_probability\": 0.08,\n            \"weight_decay\": 0.0003,\n            \"BETA\": 0.4\n        }\n\n        print(str(train_parameters_SAE))\n        file1 = open(\"Details_original_1.txt\", \"a\")\n        file1.write(str(train_parameters_SAE))\n        file1.write(\"\\n\")\n        file1.write(\"Without batch norm\")\n        file1.write(\"\\n\")\n        for iter_id in range(100):\n            iter_id += 1\n            print(\"--\" * 20)\n            print(\"iter_id: {0}\".format(iter_id))\n            print(\"--\" * 20)\n            # load data for propensity network\n            dL = DataLoader()\n            np_covariates_X_train, np_covariates_X_test, np_covariates_Y_train, np_covariates_Y_test = \\\n                dL.preprocess_data_from_csv_augmented(csv_path, split_size)\n\n            trained_models = self.__train_eval_DCN(iter_id,\n                                                   np_covariates_X_train,\n                                                   np_covariates_Y_train,\n                                                   dL, device)\n\n            sparse_classifier = trained_models[\"sparse_classifier\"]\n\n            # test DCN network\n            reply = self.__test_DCN(iter_id,\n                                    np_covariates_X_test,\n                                    np_covariates_Y_test,\n                                    dL,\n                                    sparse_classifier,\n                                    device)\n\n            MSE_SAE_e2e = reply[\"MSE_SAE_e2e\"]\n            true_ATE_SAE_e2e = reply[\"true_ATE_SAE_e2e\"]\n            predicted_ATE_SAE_e2e = reply[\"predicted_ATE_SAE_e2e\"]\n\n            file1.write(\"Iter: {0}, MSE_Sparse_e2e: {1}, MSE_Sparse_stacked_all_layer_active: {2}, \"\n                        \"MSE_Sparse_stacked_cur_layer_active: {3},\"\n                        \" MSE_NN: {4}, MSE_LR: {5}, MSE_LR_Lasso: {6}\\n\"\n                        .format(iter_id, MSE_SAE_e2e, 0,\n                                0, 0, 0, 0))\n            result_dict = OrderedDict()\n            result_dict[\"iter_id\"] = iter_id\n            result_dict[\"MSE_SAE_e2e\"] = MSE_SAE_e2e\n            result_dict[\"true_ATE_SAE_e2e\"] = true_ATE_SAE_e2e\n            result_dict[\"predicted_ATE_SAE_e2e\"] = predicted_ATE_SAE_e2e\n\n            results_list.append(result_dict)\n\n        MSE_set_SAE_e2e = []\n\n        true_ATE_SAE_set_e2e = []\n        predicted_ATE_SAE_set_e2e = []\n\n        for result in results_list:\n            MSE_set_SAE_e2e.append(result[\"MSE_SAE_e2e\"])\n            true_ATE_SAE_set_e2e.append(result[\"true_ATE_SAE_e2e\"])\n\n            predicted_ATE_SAE_set_e2e.append(result[\"predicted_ATE_SAE_e2e\"])\n\n        print(\"\\n-------------------------------------------------\\n\")\n\n        MSE_total_SAE_e2e = np.mean(np.array(MSE_set_SAE_e2e))\n        std_MSE_SAE_e2e = statistics.pstdev(MSE_set_SAE_e2e)\n        Mean_ATE_SAE_true_e2e = np.mean(np.array(true_ATE_SAE_set_e2e))\n        std_ATE_SAE_true_e2e = statistics.pstdev(true_ATE_SAE_set_e2e)\n        Mean_ATE_SAE_predicted_e2e = np.mean(np.array(predicted_ATE_SAE_set_e2e))\n        std_ATE_SAE_predicted_e2e = statistics.pstdev(predicted_ATE_SAE_set_e2e)\n\n        print(\"Using SAE E2E, MSE: {0}, SD: {1}\".format(MSE_total_SAE_e2e, std_MSE_SAE_e2e))\n        print(\"Using SAE E2E, true ATE: {0}, SD: {1}\".format(Mean_ATE_SAE_true_e2e, std_ATE_SAE_true_e2e))\n        print(\"Using SAE E2E, predicted ATE: {0}, SD: {1}\".format(Mean_ATE_SAE_predicted_e2e,\n                                                                  std_ATE_SAE_predicted_e2e))\n        print(\"--\" * 20)\n\n        file1.write(\"\\n##################################################\")\n        file1.write(\"\\n\")\n        file1.write(\"Using SAE E2E, MSE: {0}, SD: {1}\".format(MSE_total_SAE_e2e, std_MSE_SAE_e2e))\n        file1.write(\"\\nUsing SAE E2E, true ATE: {0}, SD: {1}\".format(Mean_ATE_SAE_true_e2e, std_ATE_SAE_true_e2e))\n        file1.write(\"\\nUsing SAE E2E, predicted ATE: {0}, SD: {1}\".format(Mean_ATE_SAE_predicted_e2e,\n                                                                          std_ATE_SAE_predicted_e2e))\n        file1.write(\"\\n-------------------------------------------------\\n\")\n        file1.write(\"\\n-------------------------------------------------\\n\")\n        file1.write(\"\\n##################################################\")\n\n        Utils.write_to_csv(\"./MSE/Results_consolidated.csv\", results_list)\n\n    def __train_eval_DCN(self, iter_id, np_covariates_X_train, np_covariates_Y_train, dL, device):\n        print(\"----------- Training and evaluation phase ------------\")\n        ps_train_set = dL.convert_to_tensor(np_covariates_X_train, np_covariates_Y_train)\n\n        # using SAE\n        sparse_classifier = \\\n            self.__train_propensity_net_SAE(ps_train_set, np_covariates_X_train,\n                                            np_covariates_Y_train, dL,\n                                            iter_id, device)\n\n        return {\n            \"sparse_classifier\": sparse_classifier\n        }\n\n    def __train_propensity_net_SAE(self, ps_train_set, np_covariates_X_train, np_covariates_Y_train, dL,\n                                   iter_id, device):\n        # !!! best parameter list\n        train_parameters_SAE = {\n            'epochs': 400,\n            'lr': 0.001,\n            \"batch_size\": 32,\n            \"shuffle\": True,\n            \"train_set\": ps_train_set,\n            \"sparsity_probability\": 0.08,\n            \"weight_decay\": 0.0003,\n            \"BETA\": 0.4\n        }\n\n        ps_net_SAE = shallow_train()\n        print(\"############### Propensity Score SAE net Training ###############\")\n        sparse_classifier = ps_net_SAE.train(train_parameters_SAE, device, phase=\"train\")\n\n        # eval propensity network using SAE\n        model_path_e2e = \"./DCNModel/SAE_E2E_DCN_model_iter_id_\" + str(iter_id) + \"_epoch_{0}_lr_{1}.pth\"\n        print(\"----------End to End SAE training----------\")\n\n        self.__train_DCN_SAE(ps_net_SAE, ps_train_set, device, np_covariates_X_train,\n                             np_covariates_Y_train, iter_id, dL, sparse_classifier, model_path_e2e)\n\n        return sparse_classifier\n\n    def __train_DCN_SAE(self, ps_net_SAE, ps_train_set, device, np_covariates_X_train,\n                        np_covariates_Y_train, iter_id, dL, sparse_classifier, model_path):\n        # eval propensity network using SAE\n        ps_score_list_SAE = ps_net_SAE.eval(ps_train_set, device, phase=\"eval\",\n                                            sparse_classifier=sparse_classifier)\n\n        # load data for ITE network using SAE\n        print(\"############### DCN Training using SAE ###############\")\n        data_loader_dict_SAE = dL.prepare_tensor_for_DCN(np_covariates_X_train,\n                                                         np_covariates_Y_train,\n                                                         ps_score_list_SAE,\n                                                         is_synthetic=True)\n\n        self.__train_DCN(data_loader_dict_SAE, model_path, dL, device)\n\n    @staticmethod\n    def __train_DCN(data_loader_dict, model_path, dL, device):\n        treated_group = data_loader_dict[\"treated_data\"]\n        np_treated_df_X = treated_group[0]\n        np_treated_ps_score = treated_group[1]\n        np_treated_df_Y_f = treated_group[2]\n        np_treated_df_Y_cf = treated_group[3]\n        tensor_treated = dL.convert_to_tensor_DCN(np_treated_df_X, np_treated_ps_score,\n                                                  np_treated_df_Y_f, np_treated_df_Y_cf)\n\n        control_group = data_loader_dict[\"control_data\"]\n        np_control_df_X = control_group[0]\n        np_control_ps_score = control_group[1]\n        np_control_df_Y_f = control_group[2]\n        np_control_df_Y_cf = control_group[3]\n        tensor_control = dL.convert_to_tensor_DCN(np_control_df_X, np_control_ps_score,\n                                                  np_control_df_Y_f, np_control_df_Y_cf)\n\n        DCN_train_parameters = {\n            \"epochs\": 100,\n            \"lr\": 0.001,\n            \"treated_batch_size\": 1,\n            \"control_batch_size\": 1,\n            \"shuffle\": True,\n            \"treated_set_train\": tensor_treated,\n            \"control_set_train\": tensor_control,\n            \"model_save_path\": model_path,\n            \"input_nodes\": 100\n        }\n\n        # train DCN network\n        dcn = DCN_network()\n        dcn.train(DCN_train_parameters, device)\n\n    def __test_DCN(self, iter_id, np_covariates_X_test, np_covariates_Y_test, dL, sparse_classifier, device):\n        print(\"----------- Testing phase ------------\")\n        ps_test_set = dL.convert_to_tensor(np_covariates_X_test, np_covariates_Y_test)\n\n        # using SAE\n        model_path_e2e = \"./DCNModel/SAE_E2E_DCN_model_iter_id_{0}_epoch_100_lr_0.001.pth\".format(iter_id)\n\n        propensity_score_save_path_e2e = \"./MSE/SAE_E2E_Prop_score_{0}.csv\"\n\n        ITE_save_path_e2e = \"./MSE/ITE/ITE_SAE_E2E_iter_{0}.csv\"\n\n        print(\"############### DCN Testing using SAE E2E ###############\")\n        MSE_SAE_e2e, true_ATE_SAE_e2e, predicted_ATE_SAE_e2e = \\\n            self.__test_DCN_SAE(iter_id, np_covariates_X_test,\n                                np_covariates_Y_test, dL, device,\n                                ps_test_set, sparse_classifier, model_path_e2e,\n                                propensity_score_save_path_e2e, ITE_save_path_e2e)\n\n        return {\n\n            \"MSE_SAE_e2e\": MSE_SAE_e2e,\n            \"true_ATE_SAE_e2e\": true_ATE_SAE_e2e,\n            \"predicted_ATE_SAE_e2e\": predicted_ATE_SAE_e2e,\n        }\n\n    def __test_DCN_SAE(self, iter_id, np_covariates_X_test, np_covariates_Y_test, dL, device,\n                       ps_test_set, sparse_classifier, model_path, propensity_score_csv_path,\n                       ite_csv_path):\n        # testing using SAE\n        ps_net_SAE = shallow_train()\n        ps_score_list_SAE = ps_net_SAE.eval(ps_test_set, device, phase=\"eval\",\n                                            sparse_classifier=sparse_classifier)\n        Utils.write_to_csv(propensity_score_csv_path.format(iter_id), ps_score_list_SAE)\n\n        # load data for ITE network using SAE\n        data_loader_dict_SAE = dL.prepare_tensor_for_DCN(np_covariates_X_test,\n                                                         np_covariates_Y_test,\n                                                         ps_score_list_SAE,\n                                                         is_synthetic=True)\n        MSE_SAE, true_ATE_SAE, predicted_ATE_SAE, ITE_dict_list = self.__do_test_DCN(data_loader_dict_SAE,\n                                                                                     dL, device,\n                                                                                     model_path)\n\n        Utils.write_to_csv(ite_csv_path.format(iter_id), ITE_dict_list)\n        return MSE_SAE, true_ATE_SAE, predicted_ATE_SAE\n\n    @staticmethod\n    def __do_test_DCN(data_loader_dict, dL, device, model_path):\n        treated_group = data_loader_dict[\"treated_data\"]\n        np_treated_df_X = treated_group[0]\n        np_treated_ps_score = treated_group[1]\n        np_treated_df_Y_f = treated_group[2]\n        np_treated_df_Y_cf = treated_group[3]\n        tensor_treated = dL.convert_to_tensor_DCN(np_treated_df_X, np_treated_ps_score,\n                                                  np_treated_df_Y_f, np_treated_df_Y_cf)\n\n        control_group = data_loader_dict[\"control_data\"]\n        np_control_df_X = control_group[0]\n        np_control_ps_score = control_group[1]\n        np_control_df_Y_f = control_group[2]\n        np_control_df_Y_cf = control_group[3]\n        tensor_control = dL.convert_to_tensor_DCN(np_control_df_X, np_control_ps_score,\n                                                  np_control_df_Y_f, np_control_df_Y_cf)\n\n        DCN_test_parameters = {\n            \"treated_set\": tensor_treated,\n            \"control_set\": tensor_control,\n            \"model_save_path\": model_path,\n            \"input_nodes\": 100\n        }\n\n        dcn = DCN_network()\n        response_dict = dcn.eval(DCN_test_parameters, device, input_nodes=100)\n        err_treated = [ele ** 2 for ele in response_dict[\"treated_err\"]]\n        err_control = [ele ** 2 for ele in response_dict[\"control_err\"]]\n\n        true_ATE = sum(response_dict[\"true_ITE\"]) / len(response_dict[\"true_ITE\"])\n        predicted_ATE = sum(response_dict[\"predicted_ITE\"]) / len(response_dict[\"predicted_ITE\"])\n\n        total_sum = sum(err_treated) + sum(err_control)\n        total_item = len(err_treated) + len(err_control)\n        MSE = total_sum / total_item\n        print(\"MSE: {0}\".format(MSE))\n        max_treated = max(err_treated)\n        max_control = max(err_control)\n        max_total = max(max_treated, max_control)\n\n        min_treated = min(err_treated)\n        min_control = min(err_control)\n        min_total = min(min_treated, min_control)\n        print(\"Max: {0}, Min: {1}\".format(max_total, min_total))\n\n        return MSE, true_ATE, predicted_ATE, response_dict[\"ITE_dict_list\"]\n        # np.save(\"treated_err.npy\", err_treated)\n        # np.save(\"control_err.npy\", err_control)\n","sub_path":"IHDP/Model25_10_25.py","file_name":"Model25_10_25.py","file_ext":"py","file_size_in_byte":14740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"29418946","text":"import main as EvensAndOdds\n\nimport random\nimport string\n\nprompts = []\ninputs = []\n\ndef random_string_generator(str_size, allowed_chars):\n  return ''.join(random.choice(allowed_chars) for x in range(str_size))\n\n\ndef mock_int_input(*args, **kwargs):\n  \"\"\"Returns an integer 1-999 as a str\"\"\"\n  prompts.append(args[0]) # Keep track of prompts\n\n  str_size = random.randint(1,3)\n  chars = string.digits\n  s = random_string_generator(str_size, chars)\n  inputs.append(s) # Keep track of returned values\n  return s\n\ndef test_numbers_to_check_prompt(monkeypatch):\n  \"\"\"This test case makes sure the first input prompt asks for 'how many numbers'\"\"\"\n  monkeypatch.setattr('builtins.input', mock_int_input)  \n  prompts.clear()\n  inputs.clear()\n\n  EvensAndOdds.main()\n  # Assert the first prompt is about 'how many numbers'\n  assert 'how many numbers' in prompts[0].lower()\n\ndef test_enter_number_prompts(monkeypatch, capsys):\n  \"\"\"This test case makes sure the program outputs 'Enter number: '\"\"\"\n  monkeypatch.setattr('builtins.input', mock_int_input)\n  prompts.clear()\n  inputs.clear()\n\n  EvensAndOdds.main()\n  # output = capsys.readouterr().out\n  prompt_count = 0\n  for p in prompts:\n    if p.lower().startswith(\"enter number\"): # Count prompts starting with \"enter number\"\n      prompt_count+=1\n  assert prompt_count == int(inputs[0])\n\ndef test_even_oddness(monkeypatch, capsys):\n  \"\"\"This test case makes sure that even/odd numbers are displayed correctly\"\"\"\n  monkeypatch.setattr('builtins.input', mock_int_input)\n  prompts.clear()\n  inputs.clear()\n\n  EvensAndOdds.main()\n  output = capsys.readouterr().out\n  for line in output.split('\\n'):\n    d = line.split(\" \")[0]\n    if d.startswith(\"-\"): # .isdigit() doesn't work on negatives so slice '-' from the str.\n      d = d[1:]\n\n    if d.isdigit():\n      if int(d) % 2 == 0: assert \"even\" in line.lower()\n      else: assert \"odd\" in line.lower()\n\ndef test_even_odd_count(monkeypatch, capsys):\n  \"\"\"This test verifies that the even and odd count are correct.\"\"\"\n  monkeypatch.setattr('builtins.input', mock_int_input)\n  prompts.clear()\n  inputs.clear()\n\n  EvensAndOdds.main()\n  output = capsys.readouterr().out.split('\\n')\n\n  even_count, odd_count = 0, 0\n  for x in inputs[1:]: # Skip first input which is loop number\n    x = int(x)\n    if x % 2 == 0: even_count += 1\n    else: odd_count += 1\n\n  # get index of list item containing substring from https://stackoverflow.com/a/38303263\n  odd_count_index = [idx for idx, s in enumerate(output) if 'you entered' in s.lower() and 'odd' in s.lower()][0]\n  even_count_index = [idx for idx, s in enumerate(output) if 'you entered' in s.lower() and 'even' in s.lower()][0]\n\n  # Assert that each line says the correct count.\n  odd_count_line = output[odd_count_index]\n  assert str(odd_count) in odd_count_line\n  even_count_line = output[even_count_index]\n  assert str(even_count) in even_count_line","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"290098025","text":"# Same Python interpreter for all time steps\n# We use count for one time initializations\ntry:\n    count = count + 1\nexcept NameError:\n    count = 0\n\nif count == 0:\n    import sys\n    # CHANGE this path to the result of:\n    # echo $(spack location --install-dir paraview)/lib/python*/site-packages\n    paraview_path = \"/projects/spack/opt/spack/linux-ubuntu18.04-x86_64/gcc-7.3.0/paraview-develop-qhm2ssmu2e3ko3jpz6xijn6b64u7nwnp//lib/python2.7/site-packages\"\n    sys.path.append(paraview_path)\n\n    # ParaView API\n    # WARNING: this does not work inside the plugin\n    #          unless you have the same import in paraview-vis.py\n    from mpi4py import MPI\n    import paraview\n    paraview.options.batch = True\n    paraview.options.symmetric = True\n    from paraview.simple import LoadPlugin, Show, ColorBy,\\\n        GetColorTransferFunction, GetActiveView, ResetCamera, GetActiveCamera,\\\n        GetScalarBar, Render, WriteImage, CreateWriter\n    import ascent_extract\n\n    # CHANGE this path to the result of:\n    # echo $(spack location --install-dir ascent)/examples/ascent/paraview-vis/paraview_ascent_source.py\n    scriptName = \"/projects/spack/opt/spack/linux-ubuntu18.04-x86_64/gcc-7.3.0/ascent-develop-ncrcrl6ib5k6zkcffd6k6repvkk3b44e/examples/ascent/paraview-vis/paraview_ascent_source.py\"\n    LoadPlugin(scriptName, remote=True, ns=globals())\n    ascentSource = AscentSource()\n    # show the boundary topology. For the main topology use Port 0.\n    ascentSource.Port = 1\n    rep = Show()\n\n    ColorBy(rep, (\"CELLS\", \"boundary_attribute\"))\n    # rescale transfer function\n    lut = GetColorTransferFunction('boundary_attribute')\n    lut.RescaleTransferFunction(1, 3)\n    # show color bar\n    renderView1 = GetActiveView()\n    lut = GetScalarBar(lut, renderView1)\n    lut.Title = 'boundary_attribute'\n    lut.ComponentTitle = ''\n    # set color bar visibility\n    lut.Visibility = 1\n    # show color legend\n    rep.SetScalarBarVisibility(renderView1, True)\n\n    cam = GetActiveCamera()\n    cam.Elevation(30)\n    cam.Azimuth(30)\n\nnode = ascent_extract.ascent_data().child(0)\ndomain_id = node[\"state/domain_id\"]\ncycle = node[\"state/cycle\"]\nimageName = \"image_{0:04d}.png\".format(int(cycle))\ndataName = \"paraviewdata_{0:04d}\".format(int(cycle))\nascentSource.Count = count\nResetCamera()\nRender()\nSaveScreenshot(imageName, ImageResolution=(1024, 1024))\n# writer = CreateWriter(dataName + \".pvtu\", ascentSource)\n# writer.UpdatePipeline()\n\n\n# # VTK API\n# from ascent_to_vtk import AscentSource, write_vtk\n# ascentSource = AscentSource()\n# ascentSource.Update()\n# write_vtk(\"vtkdata-main\", ascentSource.GetNode(),\n#            ascentSource.GetOutputDataObject(0))\n\n\n# # Python API\n# from ascent_to_vtk import ascent_to_vtk, write_vtk, write_json\n# node = ascent_data().child(0)\n# write_json(\"blueprint\", node)\n# data = ascent_to_vtk(node, \"main\")\n# write_vtk(\"pythondata-main\", node, data)\n# data = ascent_to_vtk(node, \"boundary\")\n# write_vtk(\"pythondata-boundary\", node, data)\n","sub_path":"src/examples/paraview-vis/paraview-vis-laghos.py","file_name":"paraview-vis-laghos.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"204780727","text":"import bisect\n\n\nclass SegmentTree:\n    def __init__(self, arr):\n        self.st = [0] * 4 * len(arr)\n\n    def update(self, id, left, right, i, val):\n        if i < left or i > right:\n            return\n        if left == right:\n            self.st[id] = val\n            return\n        mid = (left + right) // 2\n        self.update(id * 2 + 1, left, mid, i, val)\n        self.update(id * 2 + 2, mid + 1, right, i, val)\n        self.st[id] = max(self.st[id * 2 + 1], self.st[id * 2 + 2])\n\n    def getMax(self, id, left, right, u, v):\n        # [left - right - u - v], [u - v - left - right]\n        if u > right or v < left:\n            return 0\n        # [u - left - right - v]\n        if u <= left and right <= v:\n            return self.st[id]\n        mid = (left + right) // 2\n        l = self.getMax(id * 2 + 1, left, mid, u, v)\n        r = self.getMax(id * 2 + 2, mid + 1, right, u, v)\n        return max(l, r)\n\n\nclass Solution:\n    def lengthOfLIS(self, nums, k: int) -> int:\n        m = max(nums)\n        st = SegmentTree([0] * (m + 1))\n        for i, x in enumerate(nums):\n            newVal = st.getMax(0, 0, m, x - k, x - 1) + 1\n            oldVal = st.getMax(0, 0, m, x, x)\n            if newVal > oldVal:\n                st.update(0, 0, m, x, newVal)\n        return st.getMax(0, 0, m, 0, max(nums))\n\n\ns = Solution()\nprint(s.lengthOfLIS([1, 100, 500, 100000, 100000], 100000))\nprint(s.lengthOfLIS([4, 2, 1, 4, 3, 4, 5, 8, 15], 3))\nprint(s.lengthOfLIS([2, 3, 1, 2, 5], 2))\nprint(s.lengthOfLIS([1, 3, 3, 4], 1))\n","sub_path":"leetcode/2022/contest/weekly-310/Contest4.py","file_name":"Contest4.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"179796155","text":"# Copyright (C) 2020 Intel Corporation\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,\n# software 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\n# and limitations under the License.\n\n\"\"\" Converts WiderFace annotation to COCO format. \"\"\"\n\nimport argparse\n\nfrom ote.datasets.face_detection.wider_face.convert_annotation import convert_to_coco\n\n\ndef parse_args():\n    \"\"\" Parses input arguments. \"\"\"\n\n    parser = argparse.ArgumentParser(description='Convert dataset')\n    parser.add_argument('input_annotation',\n                        help=\"Path to annotation file like wider_face_train_bbx_gt.txt\")\n    parser.add_argument('images_dir',\n                        help=\"Path to folder with images like WIDER_train/images\")\n    parser.add_argument('output_annotation', help=\"Path to output json file\")\n    parser.add_argument('--with_landmarks', action='store_true',\n                        help=\"Whether to read landmarks\")\n\n    return parser.parse_args()\n\n\nargs = parse_args()\nconvert_to_coco(args.input_annotation, args.images_dir,\n                args.output_annotation, args.with_landmarks)\n","sub_path":"models/object_detection/model_templates/face-detection/tools/wider_to_coco.py","file_name":"wider_to_coco.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"437647178","text":"import pandas as pd\n\n\nclass Renko():\n    def __init__(self, name=None):\n        self.name = name\n\n\nclass RenkoFixBrickSize(Renko):\n    def __init__(self, brick_size, name=None):\n        Renko.__init__(self, name)\n        self.brick_size = brick_size\n        self.renko = pd.DataFrame(\n            columns=['price_last', 'price_min', 'price_max',\n                     'dt_start', 'dt_end', 'trend',\n                     'volume'],\n            dtype='int64',\n        )\n        self.renko[['trend']] = self.renko[['trend']].astype(int)\n        self.renko[['price_last', 'price_min', 'price_max', 'volume']] = self.renko[\n            ['price_last', 'price_min', 'price_max', 'volume']].astype(float)\n        self.renko[['dt_start', 'dt_end']] = self.renko[\n            ['dt_start', 'dt_end']].astype('datetime64')\n\n        # import ipdb; ipdb.set_trace()\n\n    def _brick_limits(self, price_ref):\n        brick_size = float(self.brick_size)\n\n        min = int(price_ref / self.brick_size) * brick_size\n        max = min + brick_size\n\n        return (min, max)\n\n\n    def _new_brick(self, price, date, volume):\n        (brick_lower_limit, brick_upper_limit) = self._brick_limits(price)\n\n        new_brick = {\n            'price_last': price,\n            'price_min': brick_lower_limit,\n            'price_max': brick_upper_limit,\n        }\n\n        # Add optional info\n        if date is not None:\n            new_brick['dt_start'] = date\n            new_brick['dt_end'] = date\n        if volume is not None:\n            new_brick['volume'] = volume\n\n        self.renko = self.renko.append(new_brick, ignore_index=True)\n\n    def new_quotes(self, prices, dates=None, volumes=None):\n        if dates is None:\n            dates = [None] * len(prices)\n        if volumes is None:\n            volumes = [None] * len(prices)\n\n        if len(self.renko) == 0:\n            self._new_brick(prices[0], dates[0], volumes[0])\n            self.renko.loc[self.renko.index[-1], 'trend'] = 0\n            return self.new_quotes(prices[1:], dates[1:], volumes[1:])\n\n        for (price, date, volume) in zip(prices, dates, volumes):\n            last_brick = self.renko.iloc[-1]\n\n            if price >= last_brick.price_max:\n                self._new_brick(price, date, volume)\n                self.renko.loc[self.renko.index[-1], 'trend'] = 1\n                pass\n            elif price <= last_brick.price_min:\n                self._new_brick(price, date, volume)\n                self.renko.loc[self.renko.index[-1], 'trend'] = -1\n                pass\n            else:\n                # The quote is in the same renko brick\n                self.renko.loc[self.renko.index[-1], 'price_last'] = price\n                if date is not None:\n                    self.renko.loc[self.renko.index[-1], 'dt_end'] = date\n                if volume is not None:\n                    self.renko.loc[self.renko.index[-1], 'volume'] += volume\n\n        pass\n","sub_path":"renko.py","file_name":"renko.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"588021783","text":"import sys, http.client, urllib.request, urllib.parse, urllib.error, json\nimport ssl\n\nfrom pprint import pprint\n\n\ndef concat(args, con=\"\"):\n    rez = args[0]\n    for a in args[1:]:\n        rez += con + a\n    return rez\n\n\ndef get_url(domain, url):\n    # Headers are used if you need authentication\n    headers = {}\n\n    # If you know something might fail - ALWAYS place it in a try ... except\n    try:\n        conn = http.client.HTTPSConnection(domain, context=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH))\n        conn.request(\"GET\", url, \"\", headers)\n        response = conn.getresponse()\n        data = response.read()\n        conn.close()\n        return data\n    except Exception as e:\n        # These are standard elements in every error.\n        print(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n\n    # Failed to get data!\n    return None\n\nquery1 = \"2012-02\"\nquery2 = '884227'\n# This makes sure that any funny characters (including spaces) in the query are\n# modified to a format that url's accept.\nquery = urllib.parse.quote_plus(query1)\n\n# Call our function.\nurl_data = get_url('data.police.uk', '/api/crimes-at-location?date=' + query1 + '&location_id=' + query2)\n\n\n# We know how our function fails - graceful exit if we have failed.\nif url_data is None:\n    print(\"Failed to get data ... Can not proceed.\")\n    # Graceful exit.\n    sys.exit()\n\n# http.client socket returns bytes - we convert this to utf-8\nurl_data = url_data.decode(\"utf-8\")\n\n# Convert the structured json string into a python variable\nurl_data = json.loads(url_data)\n\n# Pretty print\npprint(url_data)\n\nurl_data = str(url_data)\n\n\nfile = open(\"temporaries/single_query_response\", \"w\")\n\n#file.write(url_data)\n\npprint(url_data, file)\n","sub_path":"bin/data_downloader_python_support_files/api_download.py","file_name":"api_download.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"320450831","text":"#encoding=utf-8\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data',one_hot=True)\n\nx = tf.placeholder(tf.float32,[None,784])\n#x不是一个输入的特定的值,而是一个占位符placeholder,我们在Tensorflow运行计算是输入这个值\n#我们希望能够输入任意数量的Mnist图像,每一张图展开784维的\n#向量。使用[None,784],None表示此张亮的第一个维度可以是任意的长度\n\n#在模型中需要设置权重值和偏置量,当然我们可以吧他们当做另外的输入(使用展位符)\n#但是TensorFlow有一个更好的方法来表示他们:Variable。一个Variable代表一个可以修改的\n#存在在TensorFlow的用于描述交互操作的图中。它们可以用于计算输入值,也可以在计算中修改\n#对于各种机器学习中应用,一般都会有模型参数,可以用Variable表示\nW = tf.Variable(tf.zeros([784,10]))\nb = tf.Variable(tf.zeros([10]))\n\n#我们赋予tf.Variable不同的初值来创建不同的Variable:在这里我们使用全零的张量来初始化W,b\n#W的维度是[784,10],b的维度是[10]\n\n#模型:\ny = tf.nn.softmax(tf.matmul(x,W)+b)\n\n#为了更好的训练模型,定义一个指标来评估这个迷行(一般使用成本(cost)或者损失(loss))\n#然后尽量最小化这个指标,,在这里使用\"交叉熵\"(ccross-entropy)\n#交叉熵是用来衡量我们的预测用于描述真相的低效性\n\n#为了计算交叉熵,我们添加一个新的占位符用于输入正确值:\ny_ = tf.placeholder(\"float\",[None,10])\n\n#计算交叉熵:\ncross_entropy = -tf.reduce_sum(y_*tf.log(y))\n#这里的tf.log()是计算每个元素的对数\n\n'''\n注意,这里的交叉熵不仅仅用来衡量单一的一对预测和真实值,而是所有100幅图片的交叉熵的总和。\n对于100个数据点的预测表现比单一数据点的表现能更好地描述我们的模型的性能。\n'''\ntrain_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n\n#在运行计算之前,我们需要添加一个操作来初始化我们创建的变量:\ninit = tf.initialize_all_variables()\n#现在我们可以在一个Session里面启动我们的模型,并且初始化变量:\nsess = tf.Session()\nsess.run(init)\n\n#训练模型,这里我们让模型循环训练1000次!\nfor i in range(1000):\n  batch_xs, batch_ys = mnist.train.next_batch(100)\n  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\nprint (sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))","sub_path":"DL-NetWork_1/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"420790172","text":"\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\n\r\n\r\nclass Textpad:\r\n    current_open_file = \"no file\"\r\n\r\n    # declaration of open_file function--->\r\n    def open_file(self):\r\n        open_return = filedialog.askopenfile(initialdir=\"C:\\\\Users\\\\Windows 10\\\\Desktop\", title=\"select to open file\", filetypes=((\"text files\", \"*.txt\"),(\"all files\", \"*.*\")))\r\n        if open_return != None:\r\n            self.text_area.delete(1.0, END)\r\n            for line in open_return:\r\n                self.text_area.insert(END, line)\r\n            self.current_open_file = open_return.name\r\n            open_return.close()\r\n\r\n    # declaration of save_as_file function--->\r\n    def save_as_file(self):\r\n        f = filedialog.asksaveasfile(mode=\"w\", defaultextension=\".txt\")\r\n        if f is None:\r\n            return\r\n        text2save = self.text_area.get(1.0, END)\r\n        self.current_open_file = f.name\r\n        f.write(text2save)\r\n        f.close()\r\n\r\n    # declaration of save_file function--->\r\n    def save_file(self):\r\n        if self.current_open_file == \"no file\":\r\n            self.save_as_file()\r\n        else:\r\n            f = open(self.current_open_file, \"w+\")\r\n            f.write(self.text_area.get(1.0, END))\r\n            f.close()\r\n\r\n    # declaration of new_file function--->\r\n    def new_file(self):\r\n        self.text_area.delete(1.0, END)\r\n        self.current_open_file = \"no file\"\r\n\r\n    def cut_text(self):\r\n        self.copy_text()\r\n        self.text_area.delete(\"sel.first\", \"sel.last\")\r\n\r\n    def copy_text(self):\r\n        self.text_area.clipboard_clear()\r\n        self.text_area.clipboard_append(self.text_area.selection_get())\r\n\r\n    def paste_text(self):\r\n        self.text_area.insert(INSERT, self.text_area.clipboard_get())\r\n\r\n    def __init__(self, master):\r\n        self.master = master\r\n        master.title(\"TextPad\")                                                  # set the title name\r\n        master.iconbitmap(r\"notepad.ico\")                                        # set the logo\r\n\r\n        # creating the text area ---->\r\n        self.text_area = Text(self.master, undo=True)\r\n        self.text_area.pack(fill=BOTH, expand=1)\r\n\r\n        # creating main menu ---->\r\n        self.main_menu = Menu()\r\n        self.master.config(menu=self.main_menu)\r\n\r\n        # creating file menu ---->\r\n        self.file_menu = Menu(self.main_menu, tearoff=0)\r\n        self.main_menu.add_cascade(label='File', menu=self.file_menu)\r\n        self.file_menu.add_command(label=\"New\", command=self.new_file)            # function in line no 39.\r\n        self.file_menu.add_command(label=\"Open\", command=self.open_file)          # function in line no 10.\r\n        self.file_menu.add_separator()                                            # create a line in file_menu\r\n        self.file_menu.add_command(label=\"Save\", command=self.save_file)          # function in line no 30.\r\n        self.file_menu.add_command(label=\"Save as\", command=self.save_as_file)    # function in line no 20.\r\n        self.file_menu.add_separator()                                            # create a line in file_menu\r\n        self.file_menu.add_command(label=\"Exit\", command=master.destroy)          # self function.\r\n\r\n        # creating edit menu ---->\r\n        self.edit_menu = Menu(self.main_menu, tearoff=0)\r\n        self.main_menu.add_cascade(label=\"Edit\", menu=self.edit_menu)\r\n        self.edit_menu.add_command(label=\"Undo\", command=self.text_area.edit_undo)  # self function\r\n        self.edit_menu.add_command(label=\"Redo\", command=self.text_area.edit_redo)  # self function\r\n        self.edit_menu.add_separator()                                              # create line in edit_menu\r\n        self.edit_menu.add_command(label=\"Cut\", command=self.cut_text)              # function in line no 43.\r\n        self.edit_menu.add_command(label=\"Copy\", command=self.copy_text)            # function in line no 47.\r\n        self.edit_menu.add_command(label=\"Paste\", command=self.paste_text)          # function in line no 51.\r\n\r\n\r\nroot = Tk()\r\n\r\nte = Textpad(root)\r\n\r\nroot.mainloop()\r\n","sub_path":"notepad.py","file_name":"notepad.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"361864924","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan  6 23:58:06 2017\n\n@author: tejas\n\"\"\"\nfrom build import *\n\ncult = {\n    'Summer Islands': ['summer islands', 'summer islander', 'summer isles'],\n    'Ghiscari': ['ghiscari', 'ghiscaricari',  'ghis'],\n    'Asshai': [\"asshai'i\", 'asshai'],\n    'Lysene': ['lysene', 'lyseni'],\n    'Andal': ['andal', 'andals'],\n    'Braavosi': ['braavosi', 'braavos'],\n    'Dornish': ['dornishmen', 'dorne', 'dornish'],\n    'Myrish': ['myr', 'myrish', 'myrmen'],\n    'Westermen': ['westermen', 'westerman', 'westerlands'],\n    'Westerosi': ['westeros', 'westerosi'],\n    'Stormlander': ['stormlands', 'stormlander'],\n    'Norvoshi': ['norvos', 'norvoshi'],\n    'Northmen': ['the north', 'northmen'],\n    'Free Folk': ['wildling', 'first men', 'free folk'],\n    'Qartheen': ['qartheen', 'qarth'],\n    'Reach': ['the reach', 'reach', 'reachmen'],\n}\n#Grouping all related cultures together\n\ndef get_cult(value):\n    value = value.lower()\n    v = [k for (k, v) in cult.items() if value in v]\n    return v[0] if len(v) > 0 else value.title()\n\ncharacter_predictions.culture.fillna('',inplace=True)    \ncharacter_predictions.loc[:, \"culture\"] = [get_cult(x) for x in character_predictions.culture]\n\ndata = character_predictions.groupby([\"culture\", \"isAlive\"]).count()[\"S.No\"].unstack().copy(deep = True)\n\ndata.loc[:, \"total\"]= data.sum(axis = 1)\ndata=data[data.index!='']\ndata=data.sort_values('total')[[0,1]]\n\np = data.plot.barh(stacked = True, rot = 0, figsize = (14, 12),)\n_ = p.set(xlabel = \"No. of Characters\", ylabel = \"Culture\"), p.legend([\"Dead\", \"Alive\"], loc = \"lower right\")    ","sub_path":"culture_survival.py","file_name":"culture_survival.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"9589573","text":"\"\"\"\n报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:\n1.     1\n2.     11\n3.     21\n4.     1211\n5.     111221\n1 被读作  \"one 1\"  (\"一个一\") , 即 11。\n11 被读作 \"two 1s\" (\"两个一\"), 即 21。\n21 被读作 \"one 2\",  \"one 1\" (\"一个二\" ,  \"一个一\") , 即 1211。\n给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。\n注意:整数顺序将表示为一个字符串。\n\"\"\"\nclass Solution:\n    def count_off(self,s):\n        if len(s) == 1:return '1' + s\n        i = 0\n        new_s = ''\n        i_count = 1\n        while i <= len(s) - 1:\n            i += 1\n            while i <= len(s) - 1 and s[i] == s[i-1]:\n                i_count += 1\n                i += 1\n            new_s = new_s + str(i_count) + s[i-1]\n            i_count = 1\n        return new_s\n    def countAndSay(self, n):\n        \"\"\"\n        :type n: int\n        :rtype: str\n        \"\"\"\n        if n == 1:return '1'\n        s = '1'\n        while n > 1:\n            s = self.count_off(s)\n            n -= 1\n        return s\n\nif __name__ == '__main__':\n    solution = Solution()\n    n = 4\n    print(solution.countAndSay(n))\n","sub_path":"leetcode/Count off.py","file_name":"Count off.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"51795301","text":"import sys\nimport os\nos.chdir('../')\nsys.path.append('./')\nimport nmt.structs as structs\nimport nmt.configurations as config\nimport nmt.train # sets torch's random seed\nimport nmt.all_constants as ac\nimport nmt.utils as ut\nimport nmt.structs.tree_utils as tu\nimport plot_tree\nimport torch\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport os\nimport random\nimport torch.nn.functional as F\n\nrandom.seed(ac.SEED)\ndpi = 400\n\nfontsize = 110\nnrows = 2\n\ndevice = ut.get_device()\n\njust_strengths = True\nplot_strengths = False\nreverse_cmap = True\n\nrelationship_reordering = [0, 3, 4, 5, 6, 7, 8, 1, 2]\n\nname_suffix = '_mask_strengths' if just_strengths else '_heads'\n\nchosen_cmap = plt.get_cmap('Greens')\nif reverse_cmap:\n  chosen_cmap = chosen_cmap.reversed()\n\nen_sample = '(S (NP (PRP He ) ) (VP (VBZ is ) (NP (PRP\\$ my ) (NN father ) ) ) (. . ) )'\n# German for 'He is my father.' -> 'Er ist mein Vater.' (according to Google Translate :P)\nde_sample = '(VROOT (S (PPER-SB Er) (VAFIN-HD ist) (NP-PD (PPOSAT-NK mein) (NN-NK Vater))) ($. .))'\n\nmodels = [\n  (en_sample, 'en2vi_att_sin', 'en2vi_att_ast'),\n  (en_sample, 'en2ur_att_sin', 'en2ur_att_ast'),\n  (en_sample, 'en2tu_att_sin', 'en2tu_att_ast'),\n  (en_sample, 'en2ha_att_sin', 'en2ha_att_ast'),\n  (en_sample, 'en2de_att_sin_100k', 'en2de_att_ast'),\n  (de_sample, 'de2en_att_sin_100k', 'de2en_att_ast'),\n\n  (en_sample, 'en2vi17a2', 'en2vi_tree'),\n  (en_sample, 'en2ur17a2', 'en2ur_tree'),\n  (en_sample, 'en2tu17a2', 'en2tu_tree'),\n  (en_sample, 'en2ha17a2', 'en2ha_tree'),\n  (en_sample, 'en2de17a2_100k', 'en2de_tree'),\n  (de_sample, 'de2en17a2_100k', 'de2en_tree'),\n]\n\ndef plot_mask_strength(ax, params, norm):\n  #ax.set_title('Mask Strength')\n\n  im_mtx = params['self_attn_weights'][:-1][relationship_reordering].detach()\n  ax_im = ax.imshow(im_mtx, cmap=chosen_cmap, norm=norm)\n  xticklabels = [i for i in range(im_mtx.size()[1])]\n  ax.set_xticks(xticklabels)\n  ax.set_xticklabels([i + 1 for i in xticklabels])\n  ax.set_xlabel(\"Attention Head\")\n  yticklabels = tu.HEAD_NAMES[1:-1]\n  ax.set_yticks(range(len(yticklabels)))\n  ax.set_yticklabels([yticklabels[relationship_reordering[i]] for i in range(len(yticklabels))])\n  divider = make_axes_locatable(ax)\n\n  cax = divider.append_axes(\"right\", size=\"6.25%\", pad=0.1)\n  plt.colorbar(ax_im, cax=cax)\n\n\n\nfor sample, model_name, save_name in models:\n  save_name += name_suffix\n  print(save_name + '...', end='')\n  cnfg = config.get_config(model_name, getattr(config, model_name))\n  \n  struct = cnfg['struct']\n  \n  model_fp = os.path.join(cnfg['save_to'], model_name + '.pth')\n  \n  if True:\n    model = nmt.model.Model(cnfg, load_from=model_fp).to(device)\n    tree_words = model.data_manager.parse_line(sample, True, to_ids=False)\n    words = tree_words.flatten()\n    tree = model.data_manager.parse_line(sample, True, to_ids=True)\n    toks = torch.tensor(tree.flatten(), device=device).unsqueeze(0)\n  \n    self_att_layers = model.encoder.self_atts\n    x = F.dropout(toks, p=model.encoder.dropout, training=False)\n    params = model.struct_params\n  else:\n    if os.path.exists(model_fp):\n      params = struct.get_params(cnfg) if hasattr(struct, 'get_params') else {}\n      m = torch.load(model_fp, map_location=device)['model']\n      params = {k:m[k] for k in params}\n    else:\n      params = struct.get_params(cnfg)\n  \n  \n  num_heads = cnfg['num_enc_heads']\n  att_mask, _ = struct.get_enc_mask(toks, [tree], num_heads, **params)\n  att_mask = att_mask.squeeze(0).detach().cpu()\n  \n  att_min = att_mask.min().detach().cpu().item()\n  att_max = att_mask.max().detach().cpu().item()\n  orig_range = att_min, att_max\n  #if att_max > 0 and att_min < 0:\n  #  att_max, att_min = max(att_max, -att_min), min(-att_max, att_min)\n  norm = matplotlib.colors.Normalize(vmin=att_min, vmax=att_max)\n\n  if just_strengths:\n    fig = plt.figure(figsize=(4, 3))\n    plot_mask_strength(plt.gca(), params, norm)\n  else:\n    ncols = (num_heads + plot_strengths + nrows - 1)//nrows\n    fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(3*ncols + 1, 3*nrows + 1))\n  \n    #fig.suptitle(title, size='xx-large', weight='bold', va='top')\n    \n    try: axs = sum([[x for x in row] for row in axs], [])\n    except: pass\n\n    if plot_strengths:\n      ax = axs[0]\n      plot_mask_strength(ax, params, norm)\n\n    for i, ax in enumerate(axs[int(plot_strengths):]):\n      ax.set_title(f'Attention Head {i+1}')\n      ax_im = ax.imshow(att_mask[i], cmap=chosen_cmap, norm=norm)\n      ax.set_xticks(range(len(words)))\n      ax.set_xticklabels(words, fontsize=fontsize//len(words))\n      ax.set_yticks(range(len(words)))\n      ax.set_yticklabels(words, fontsize=fontsize//len(words))\n      plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor')\n    \n  plt.tight_layout(pad=1.25, w_pad=0.6, h_pad=0.6)\n  plt.savefig(f'plots/png/{save_name}.png', dpi=dpi, transparent=False, pad_inches=0.0,)\n  plt.close('all')\n  print(f' done ({orig_range[0]:0.4f}, {orig_range[1]:0.4f})')\n  \n","sub_path":"plots/self_att.py","file_name":"self_att.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"650284657","text":"from django.db import transaction\n\nfrom rest_framework import serializers\n\nfrom .models import (\n    Exercise, Routine, Training, TrainingExercise, TrainingExerciseSet, Workout,\n    WorkoutExercise,\n)\n\n\nclass RoutineSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = Routine\n        fields = ('id', 'name', 'slug')\n\n\nclass ExerciseSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = Exercise\n        fields = ('id', 'name', 'slug', 'muscle')\n\n\nclass ExerciseWorkoutSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = WorkoutExercise\n        fields = ('id', 'exercise', 'order', 'sets', 'reps', 'rest_period')\n\n\nclass ExerciseWorkoutDetailSerializer(serializers.ModelSerializer):\n    exercise = ExerciseSerializer()\n\n    class Meta:\n        model = WorkoutExercise\n        fields = ('id', 'exercise', 'order', 'sets', 'reps', 'rest_period')\n\n\nclass WorkoutSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = Workout\n        fields = ('id', 'name', 'routine', 'workout_exercises')\n\n\n\nclass WorkoutDetailSerializer(serializers.ModelSerializer):\n    routine = RoutineSerializer()\n    workout_exercises = ExerciseWorkoutDetailSerializer(many=True)\n\n    class Meta:\n        model = Workout\n        fields = ('id', 'name', 'routine', 'workout_exercises')\n\n\nclass WorkoutSaveSerializer(serializers.ModelSerializer):\n    workout_exercises = ExerciseWorkoutSerializer(many=True)\n\n    class Meta:\n        model = Workout\n        fields = ('id', 'name', 'routine', 'workout_exercises')\n\n    def create_workout_exercises(self, instance, workout_exercises_data):\n        for workout_exercise_data in workout_exercises_data:\n            workout_exercise_data['workout'] = instance\n            WorkoutExercise.objects.create(**workout_exercise_data)\n\n    def create(self, validated_data):\n        workout_exercises_data = validated_data.pop('workout_exercises')\n        workout = super().create(validated_data)\n        self.create_workout_exercises(workout, workout_exercises_data)\n        return workout\n\n    def update(self, instance, validated_data):\n        workout_exercises_data = validated_data.pop('workout_exercises')\n        instance = super().update(instance, validated_data)\n\n        with transaction.atomic():\n            # More simple to remove all and re-add all because we need to add new\n            # exercise, remove old, update exercise with new sets and reps, etc.\n            WorkoutExercise.objects.filter(workout=instance).delete()\n            self.create_workout_exercises(instance, workout_exercises_data)\n\n        return instance\n\n\nclass TrainingExerciseSetSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = TrainingExerciseSet\n        fields = ('id', 'order', 'reps', 'weight', 'rest_period', 'tempo')\n\n\nclass TrainingExerciseSerializer(serializers.ModelSerializer):\n    training_exercise_sets = TrainingExerciseSetSerializer(many=True)\n\n    class Meta:\n        model = TrainingExercise\n        fields = ('id', 'exercise', 'training_exercise_sets')\n\n\nclass TrainingSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = Training\n        fields = ('id', 'workout', 'date')\n\n\nclass TrainingListSerializer(serializers.ModelSerializer):\n    training_exercises = TrainingExerciseSerializer(many=True)\n\n    class Meta:\n        model = Training\n        fields = (\n            'id', 'date', 'workout', 'training_exercises',\n            'sets_total', 'reps_total', 'weights_total', 'rest_avg',\n        )\n\n\nclass TrainingSaveSerializer(serializers.ModelSerializer):\n    training_exercises = TrainingExerciseSerializer(many=True)\n\n    class Meta:\n        model = Training\n        fields = ('id', 'date', 'workout', 'training_exercises')\n\n    def create_training_exercises(self, instance, training_exercises_data):\n\n        for training_exercise_data in training_exercises_data:\n            sets_data = training_exercise_data.pop('training_exercise_sets')\n\n            training_exercise_data['training'] = instance\n            training_exercise = TrainingExercise.objects.create(**training_exercise_data)\n\n            for set_data in sets_data:\n                set_data['training_exercise'] = training_exercise\n                TrainingExerciseSet.objects.create(**set_data)\n\n    def create(self, validated_data):\n        training_exercises_data = validated_data.pop('training_exercises')\n        training = super().create(validated_data)\n        self.create_training_exercises(training, training_exercises_data)\n        return training\n\n    def update(self, instance, validated_data):\n        training_exercises_data = validated_data.pop('training_exercises')\n        instance = super().update(instance, validated_data)\n\n        with transaction.atomic():\n            TrainingExercise.objects.filter(training=instance).delete()\n            # Cascade delete is also trigger with queryset.delete() method??\n            TrainingExerciseSet.objects.filter(training_exercise__training=instance).delete()\n            self.create_training_exercises(instance, training_exercises_data)\n\n        return instance\n","sub_path":"fitlog/training/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"197618462","text":"import unittest\n\ndef assign(tasks):\n\ttasks.sort()\n\tout = []\n\tfor i in range(len(tasks) / 2):\n\t\tout.append([tasks[i], tasks[~i]])\n\n\treturn out\n\n\n\n\n\n\n# Tests\n\nclass Test(unittest.TestCase):\n\n\t\tdef test_base_case(self):\n\t\t\tactual = assign([5,2,1,6,4,4])\n\t\t\texpected = [[5,2],[1,6],[4,4]]\n\t\t\tself.assertEqual(actual, expected)\n\n    \nunittest.main(verbosity=2)\n","sub_path":"src/main/py/epi-17.1-optimal-assignment.py","file_name":"epi-17.1-optimal-assignment.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"213680442","text":"\"\"\"Error categories and messages specific to the System activities.\nRead doc_string of error_handler.ErrorMsgManager for more information.\n\"\"\"\nfrom core.errors_old.err_msg_utils import *\nLOCATION = 'core'\n\nGENERIC = localkey('GENERIC',\n                   'Generic local_key for System Object.',\n                   'core.errors_old',\n                   [])\n\nGENERIC.messages = [\n    errmsg('DEFAULTMSG', 'Default key for all System errors_old.'),\n    errmsg('UNKNOWN_ERRORKEY', 'Encountered unexpected key: %s'),\n    errmsg('TEMPKEY', 'Generic System error message')\n]","sub_path":"core/errors_old/err_msg/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"277107493","text":"\"\"\"Features engineering functions\"\"\"\n\nimport numpy as np\n\n\ndef classify(Data, classifier):\n    \"\"\"\n    classifies the elements of Data in col_to_classify in 2 predefined classes \n    according to a threshold and returns the result.\n    classifier is disctionary with each column to change and the corresponding classes\n    \"\"\"\n    \n    cols_to_classify = list(classifier.keys())\n    for col in cols_to_classify:\n        class1 = classifier[col][0]\n        class2 = classifier[col][1]\n        data_classified = Data[:,col].copy()\n        threshold =  (class1 + class2)/2.0\n        data_classified[data_classified < threshold] = class1\n        data_classified[data_classified >= threshold] = class2\n        Data[:,col] = data_classified.reshape(1,-1)\n        \n    return Data\n\ndef square_root(data, col_to_sqrt):\n    \"\"\" \n    takes the square root of the elements of Data in col_to_sqrt.\n    \"\"\"\n    data_sqrted = data[:,col_to_sqrt].copy()\n    data_sqrted[data_sqrted >=  0] = np.sqrt(data_sqrted[data_sqrted >= 0])\n    data[:,col_to_sqrt] = data_sqrted\n    return data\n\ndef unif(data, col_to_unif):\n    \"\"\"\n    divides the elements of X in col_to_divide by the absolute maximum \n    to bring the values between -1 and 1.\n    \"\"\"\n    data_unif = data[:,col_to_unif].copy()\n    absolute_max = np.amax(data_unif, axis = 0)\n    data_unif = data_unif / absolute_max\n    data[:,col_to_unif] = data_unif\n    return data\n\n\ndef apply_log(data, columns):\n    \"\"\"\n    applies the log to data and returns the new transformed data set\n    \"\"\"\n    logX=data.copy()\n    for i in columns:\n        logX[:,i]=np.log(1+data[:,i])\n    return logX","sub_path":"ML Projects/HiggsBosonDetection/scripts/.ipynb_checkpoints/Feature_engineering-checkpoint.py","file_name":"Feature_engineering-checkpoint.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"468496221","text":"import logging\nfrom datetime import datetime\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom fastapi.logger import logger as fastapi_logger\nfrom pydantic import BaseModel\nimport sys\n\nsys.path.append(\"..\")\nfrom logs import models\nfrom logs import dbconf\nfrom logs import session_scope\n\n\nclass SQLALCHAMYHandler(logging.Handler):\n    \"\"\"\n    Logging handler for SqlAlchamy.\n    \"\"\"\n\n    def __init__(self):\n        logging.Handler.__init__(self)\n        # defining custom log format\n        self.LOG_FORMAT = \"%(asctime)s:%(msecs)03d %(levelname)s \" \\\n                          \"%(filename)s:%(lineno)d %(message)s | \"\n        # defining the date format for logger\n        self.LOG_DATE_FORMAT = \"%Y-%m-%d %H:%M:%S\"\n        models.Base.metadata.create_all(bind=dbconf.engine)\n\n    class ProcessLogModel(BaseModel):\n        created: datetime\n        name: str\n        loglevel: int\n        loglevelname: str\n        fileid: int\n        args: str\n        module: str\n        funcname: str\n        lineno: str\n        exception: str\n        process: int\n        thread: str\n        threadname: str\n\n    # -------------- Log data ----------------- #\n    def insert_log(self, log: ProcessLogModel):\n        try:\n            with session_scope() as session:\n                db_log = models.ProcessLog(Created=log.created,\n                                           Name=log.name,\n                                           LogLevel=log.loglevel,\n                                           LogLevelName=log.loglevelname,\n                                           FileId=log.fileid,\n                                           Args=log.args,\n                                           Module=log.module,\n                                           FuncName=log.funcname,\n                                           LineNo=log.lineno,\n                                           Except=log.exception,\n                                           Process=log.process,\n                                           Thread=log.thread,\n                                           ThreadName=log.threadname)\n                session.add(db_log)\n                session.commit()\n                # session.refresh(db_log)\n        except SQLAlchemyError as e:\n            raise e\n\n    def emit(self, record):\n        record.dbtime = datetime.utcfromtimestamp(record.created).strftime(\n            \"%Y-%m-%d %H:%M:%S\")\n        f = OneLineExceptionFormatter(self.LOG_FORMAT,\n                                      self.LOG_DATE_FORMAT)\n        if record.exc_info:\n            record.exc_text = f.formatException(record.exc_info)\n            # added for fixing quotes causing error\n            record.exc_text = record.exc_text.replace(\"'\",\n                                                      '\"')\n        else:\n            record.exc_text = \"\"\n\n        # Insert log record:\n        log_data = record.__dict__\n        log = self.ProcessLogModel(created=log_data['dbtime'],\n                                   name=str(log_data['name']),\n                                   loglevel=int(log_data['levelno']),\n                                   loglevelname=str(log_data['levelname']),\n                                   fileid=int(log_data['msg']),\n                                   args=str(log_data['args']),\n                                   module=str(log_data['module']),\n                                   funcname=str(log_data['funcName']),\n                                   lineno=str(log_data['lineno']),\n                                   exception=str(log_data['exc_text']),\n                                   process=int(log_data['process']),\n                                   thread=str(log_data['thread']),\n                                   threadname=str(log_data['threadName']))\n        # insert error log in to table\n        self.insert_log(log)\n\n\n# custom log formatter\nclass OneLineExceptionFormatter(logging.Formatter):\n    def formatException(self, exc_info):\n        result = super(OneLineExceptionFormatter, self).formatException(\n            exc_info)\n        return repr(result)  # or format into one line however you want to\n\n    def format(self, record):\n        s = super(OneLineExceptionFormatter, self).format(record)\n        if record.exc_text:\n            s = s.replace('\\n', '') + '|'\n        return s\n\n\n# defining log levels\n# LOG_LEVEL = logging.ERROR\n\n# Configuring Logs\n# db_logger = logging.getLogger()\n# db_logger.setLevel(LOG_LEVEL)\n\n# add database handler\nhandler = SQLALCHAMYHandler()\n# db_logger.addHandler(handler)\n\ngunicorn_logger = logging.getLogger(\"gunicorn.error\")\nfastapi_logger.setLevel(gunicorn_logger.level)\n# add database handler\nfastapi_logger.addHandler(handler)\n","sub_path":"BlogApp/app/logs/logutil_db.py","file_name":"logutil_db.py","file_ext":"py","file_size_in_byte":4690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"574534503","text":"import re\nfrom profiles.models import Profile, User, Follow\nfrom django.db.models.functions import Lower\nfrom twitter_project.logging import logger\nfrom django.conf import settings\nfrom django.db.models import Count\n\n\ndef get_username(name):\n    \"\"\"Generates a unique username based on the given name\n    The username will contain both parts of the name and a\n    number at the end if the name is already taken\n\n    for example:\n        get_username(\"Seweryn Kras\") -> \"SewerynKras\"\n        get_username(\"Seweryn Kras\") -> \"SewerynKras1\"\n        get_username(\"Seweryn Kras\") -> \"SewerynKras2\"\n    \"\"\"\n    # clean the name of all non letters\n    pattern = r'[^a-zA-Z]+'\n    name = re.sub(pattern, \"\", name)\n\n    if name.lower() not in settings.FORBIDDEN_NAMES:\n        # get all usernames that start with $name\n        pattern = fr'^({name})\\d*$'\n        usernames = Profile.objects.filter(username__iregex=pattern).order_by(Lower(\"username\"))\n\n        # in case the name is unique and not forbidden\n        if not usernames.exists():\n            logger.debug(f\"Name: {name} is valid\")\n            return name\n        # get the number\n        number = usernames.last().username[len(name):]\n    else:\n        number = \"\"\n\n    if number == \"\":\n        number = 1\n    else:\n        number = int(number)\n        number += 1\n    new_name = name + str(number)\n\n    logger.debug(f\"Name: {name} is not valid so the new username is {new_name}\")\n    return new_name\n\n\ndef get_single_author(id):\n    \"\"\"\n    Queries an author with the given id.\n\n    Arguments:\n        id {str}\n\n    Returns:\n        Profile\n    \"\"\"\n    return Profile.objects.get(username__iexact=id)\n\n\ndef is_email_valid(email):\n    pattern = r\"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)\"\n    matches = bool(re.match(pattern, email))\n    logger.debug(f\"Validating email: {email} verdict: {matches}\")\n    return matches\n\n\ndef is_email_unique(email):\n    unique = not User.objects.filter(email__iexact=email).exists()\n    logger.debug(f\"Checking if email: {email} is unique, verdict: {unique}\")\n    return unique\n\n\ndef check_if_user_follows(follower, following):\n    \"\"\"\n    Returns a boolean value describing wheather a Follow objects exists\n    between the follower and following\n\n    Arguments:\n        follower {Profile}\n        following {Profile}\n\n    Returns:\n        bool\n    \"\"\"\n    return Follow.objects.filter(follower=follower, following=following).exists()\n\n\ndef create_new_profile(name, email, password, sync_email, person_ads, send_news):\n    \"\"\"\n    Registers a new user by creating and saving a User and Profile instance\n\n    Arguments:\n        name {str}\n        email {str}\n        password {str}\n        sync_email {bool}\n        person_ads {bool}\n        send_news {bool}\n\n    Returns:\n        Profile\n    \"\"\"\n    username = get_username(name)\n    user = User(username=email, email=email)\n    user.set_password(password)\n    user.save()\n    profile = Profile(user=user,\n                      username=username,\n                      sync_email=sync_email,\n                      send_news=send_news,\n                      personalize_ads=person_ads,\n                      display_name=name)\n    profile.randomize_media()\n    profile.save()\n    return profile\n\n\ndef get_follow_suggestions(profile):\n    # dont suggest following someone that the user already follows\n    following = Follow.objects.filter(follower=profile)\n    profiles = Profile.objects.exclude(pk__in=following.values(\"following__pk\"))\n\n    # dont suggest following themselves\n    profiles = profiles.exclude(pk=profile.pk)\n\n    # order by number of followers\n    profiles = profiles.annotate(fl=Count(\"follow_following\"))\n    profiles = profiles.order_by(\"-fl\")\n\n    return profiles\n","sub_path":"twitter_project/profiles/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"196878190","text":"import matplotlib.pyplot as plt\nimport matplotlib.lines\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import roc_auc_score, average_precision_score\n\nfrom oolearning.converters.TwoClassConverterBase import TwoClassConverterBase\nfrom oolearning.converters.TwoClassPrecisionRecallOptimizerConverter import \\\n    TwoClassPrecisionRecallOptimizerConverter\nfrom oolearning.converters.TwoClassRocOptimizerConverter import TwoClassRocOptimizerConverter\nfrom oolearning.evaluators.TwoClassEvaluator import TwoClassEvaluator\n\n\nclass TwoClassProbabilityEvaluator(TwoClassEvaluator):\n    \"\"\"\n    Evaluates 2-class classification problems, where \"probabilities\" are supplied as well as a Converter (i.e.\n      an object that encapsulates the logic to convert the probabilities to classes.\n    \"\"\"\n    def __init__(self,\n                 converter: TwoClassConverterBase):\n        super().__init__(positive_class=converter.positive_class)\n        self._converter = converter\n        self._actual_classes = None\n        self._predicted_probabilities = None\n\n        self._auc_roc = None\n        self._auc_precision_recall = None\n\n        self._fpr = None\n        self._tpr = None\n        self._ideal_threshold_roc = None\n        self._ppv = None\n        self._ideal_threshold_ppv_tpr = None\n\n    @property\n    def auc_roc(self):\n        return self._auc_roc\n\n    @property\n    def auc_precision_recall(self):\n        return self._auc_precision_recall\n\n    def evaluate(self,\n                 actual_values: np.ndarray, predicted_values: pd.DataFrame):\n        self._actual_classes = actual_values\n        self._predicted_probabilities = predicted_values\n\n        self._auc_roc = roc_auc_score(y_true=[1 if x == self._positive_class else 0 for x in actual_values],\n                                      y_score=predicted_values[self._positive_class])\n        # according to this (), average precision is same as auc of pr curve\n        self._auc_precision_recall = average_precision_score(y_true=[1 if x == self._positive_class else 0\n                                                                     for x in actual_values],\n                                                             y_score=predicted_values[self._positive_class])\n\n        predicted_classes = self._converter.convert(values=predicted_values)\n\n        super().evaluate(actual_values=actual_values, predicted_values=predicted_classes)\n\n    def plot_roc_curve(self):\n        \"\"\"\n        :return: an ROC curve, indicating the point (threshold) that has the minimum distance to the\n            upper left corner (i.e. a perfect predictor). If a threshold is specified in the\n            class constructor, then that threshold is also annotated on the graph.\n        \"\"\"\n        if self._fpr is None or self._tpr is None or self._ideal_threshold_roc is None:\n            converter = TwoClassRocOptimizerConverter(actual_classes=self._actual_classes,\n                                                      positive_class=self._converter.positive_class)\n            converter.convert(values=self._predicted_probabilities)\n            self._fpr = converter.false_positive_rates\n            self._tpr = converter.true_positive_rates\n            self._ideal_threshold_roc = converter.ideal_threshold\n\n        self._create_curve(x_coordinates=self._fpr,\n                           y_coordinates=self._tpr,\n                           threshold=0.5,\n                           ideal_threshold=self._ideal_threshold_roc,\n                           title='ROC (AUC={0})'.format(round(self.auc_roc, 3)),\n                           x_label='False Positive Rate (1 - True Negative Rate)',\n                           y_label='True Positive Rate',\n                           corner='Left')\n        plt.tight_layout()\n\n    def plot_precision_recall_curve(self):\n        \"\"\"\n        # TODO document\n        \"\"\"\n        self.plot_ppv_tpr_curve()\n\n    def plot_ppv_tpr_curve(self):\n        \"\"\"\n        # TODO document\n        \"\"\"\n        if self._ppv is None or self._tpr is None or self._ideal_threshold_ppv_tpr is None:\n            converter = TwoClassPrecisionRecallOptimizerConverter(actual_classes=self._actual_classes,\n                                                                  positive_class=self._converter.positive_class)  # noqa\n            converter.convert(values=self._predicted_probabilities)\n            self._ppv = converter.positive_predictive_values\n            self._tpr = converter.true_positive_rates\n            self._ideal_threshold_ppv_tpr = converter.ideal_threshold\n\n        self._create_curve(x_coordinates=self._tpr,\n                           y_coordinates=self._ppv,\n                           threshold=0.5,\n                           ideal_threshold=self._ideal_threshold_ppv_tpr,\n                           title='Positive Predictive Value vs. True Positive Rate',\n                           x_label='True Positive Rate',\n                           y_label='Positive Predictive Value',\n                           corner='Right')\n\n        plt.tight_layout()\n\n    def plot_calibration(self):\n        \"\"\"\n        :return: calibration plot. Predicted probabilities are matched with the actual class and binned by\n            the prediction in intervals of 0.1. i.e. all probabilities/classes that have a prediction between\n            0 to 0.1 are grouped together, > 0.1 <= 0.2 are grouped together, and so on. For each group, the\n            percent of positive classes found is calculated. For example, in the group that has predicted\n            probabilities between 0 and 0.1, we would expect the average probability to be 0.05, and therefore\n            we would expect about 0.05 (i.e. 5%) of the group to be a positive class. The percentage of\n            positive classes for each bin is plotted. If the points fall along a 45 degree line, the model\n            has produced well-calibrated probabilities.\n        \"\"\"\n        calibration_data = pd.concat([self._predicted_probabilities[self._positive_class],\n                                      self._actual_classes], axis=1)\n        calibration_data.columns = ['probabilities', 'actual_classes']\n        bin_labels = ['[0, 0.1]', '(0.1, 0.2]', '(0.2, 0.3]', '(0.3, 0.4]', '(0.4, 0.5]', '(0.5, 0.6]',\n                      '(0.6, 0.7]', '(0.7, 0.8]', '(0.8, 0.9]', '(0.9, 1.0]']\n        # .cut maintains distribution shape\n        bins = pd.cut(calibration_data.probabilities,\n                      bins=np.arange(0.0, 1.1, 0.1),\n                      include_lowest=True,\n                      labels=bin_labels)\n        calibration_data['bins'] = bins\n        # calibration_data.bins.value_counts(ascending=True)\n        # calibration_data.head()\n        # calibration_data.sort_values(['bins', 'actual_classes'])\n\n        def calibration_grouping(x):\n            # noinspection PyTypeChecker\n            number_positive_events = sum(x.actual_classes == self._positive_class)\n            total_observations = len(x.actual_classes)\n            d = {'Positive Events Found': number_positive_events,\n                 'Total Observations': total_observations,\n                 'Actual Calibration': 0 if total_observations == 0\n                                         else number_positive_events / total_observations}\n            return pd.Series(d, index=['Positive Events Found', 'Total Observations', 'Actual Calibration'])\n\n        calibration_group_data = calibration_data.groupby('bins').apply(calibration_grouping)\n        calibration_group_data['Perfect Calibration'] = np.arange(0.05, 1.05, 0.10)\n\n        calibration_group_data[['Actual Calibration', 'Perfect Calibration']].plot(yticks=np.arange(0.0, 1.1, 0.1))  # noqa\n        ax = plt.gca()\n        ax.set_xticks(np.arange(len(bin_labels)))\n        ax.set_xticklabels(labels=bin_labels, rotation=20, ha='right', size=9)\n        ax.set_xlim(-0.5, len(bin_labels) - 0.5)\n        ax.figure.set_size_inches(8, 8)\n        ax.grid(which='major', alpha=0.1)\n        for index in range(10):\n            text = '({}/{} = {:.1%})'.format(calibration_group_data.iloc[index]['Positive Events Found'],\n                                             calibration_group_data.iloc[index]['Total Observations'],\n                                             calibration_group_data.iloc[index]['Actual Calibration'])\n            ax.annotate(text,\n                        xy=(index+0.15, calibration_group_data.iloc[index]['Actual Calibration'] - 0.005),\n                        size=7)\n        ax.scatter(x=np.arange(len(bin_labels)), y=calibration_group_data['Actual Calibration'].values, s=10)\n        ax.set(**{'title': 'Calibration Chart',\n                  'xlabel': 'Binned Probabilities',\n                  'ylabel': 'Percent of Positive (Actual) Events in Bin'})\n        plt.tight_layout()\n\n    def plot_predicted_probability_hist(self):\n        calibration_data = pd.concat([self._predicted_probabilities[self._positive_class],\n                                      self._actual_classes], axis=1)\n        calibration_data.columns = ['Predicted Probabilities', 'Actual Classes']\n\n        calibration_data['Predicted Probabilities'].hist(by=calibration_data['Actual Classes'],\n                                                         bins=20)\n        axes = plt.gcf().get_axes()\n        for ax in axes:\n            ax.set_xticks(np.arange(0.0, 1.1, 0.1))\n            ax.set(**{'xlabel': 'Predicted Probability (Positive Event)',\n                      'ylabel': 'Count'})\n        ax = plt.gca()\n        ax.figure.set_size_inches(10, 6)\n        plt.suptitle('Histogram of Predicted Probabilities, by Actual Outcome', fontsize=12)\n        plt.tight_layout()\n\n    @staticmethod\n    def _create_gain_lift_data(predicted_probabilities, actual_classes, positive_class):\n\n        raw_data = pd.concat([predicted_probabilities[positive_class],\n                              actual_classes], axis=1)\n        raw_data.columns = ['probabilities', 'actual_classes']\n        raw_data.sort_values(['probabilities'], ascending=False)\n\n        # .qcut gets percentiles\n        bins = pd.qcut(x=raw_data['probabilities'], q=10, labels=list(range(100, 0, -10)))\n\n        raw_data['percentiles'] = bins\n        # probabilities_classes.sort_values('probabilities')\n\n        def gain_grouping(x):\n            # noinspection PyTypeChecker\n            number_positive_events = sum(x.actual_classes == positive_class)\n            d = {'Number of Observations': len(x.actual_classes),\n                 'Number of Positive Events': number_positive_events\n                 }\n            return pd.Series(d, index=['Number of Observations', 'Number of Positive Events'])\n\n        # noinspection PyTypeChecker\n        number_of_positive_events = sum(actual_classes == positive_class)\n        gain_lift_data = raw_data.groupby('percentiles').apply(gain_grouping)\n\n        temp = pd.DataFrame({'Number of Observations': 0, 'Number of Positive Events': 0}, index=[0],)\n        temp.index.names = ['percentiles']\n        gain_lift_data = pd.concat([gain_lift_data, temp])\n        gain_lift_data.sort_index(ascending=True, inplace=True)\n        gain_lift_data['Cumulative Observations'] = gain_lift_data['Number of Observations'].cumsum()\n        gain_lift_data['Cumulative Positive Events'] = gain_lift_data['Number of Positive Events'].cumsum()\n        gain_lift_data['Percentage of Positive Events'] = gain_lift_data['Cumulative Positive Events'] / \\\n                                                           number_of_positive_events\n        gain_lift_data['Random Gain'] = gain_lift_data.index.values\n        gain_lift_data['Model Gain'] = gain_lift_data['Percentage of Positive Events'] * 100\n\n        total_observations = len(actual_classes)\n\n        gain_lift_data['Model Lift'] = (gain_lift_data['Model Gain'] / 100) / \\\n                                  (gain_lift_data['Cumulative Observations'] / total_observations)\n        return gain_lift_data\n\n    def plot_gain_chart(self):\n        \"\"\"\n        :return: A Gain Chart shows the % of positive events we have 'captured' i.e. located by looking at the\n            top x% of population of predictions such that the highest predictions are looked at first.\n            So we can say we've captured X% of all the positive events by searching Y% of highest predictions.\n\n            For example, if X (and the x-axis) is 20% and Y (and the y-axis) is 83%, and we are predicting\n            the probability that a customer will purchase a widget, then we can say something like:\n            \"In the case of propensity to buy, we can say we can identify and target 83% of the customers\n            who are likely to buy the product by target 20% of total customers (in the population we are\n            looking at)\". This gives us an idea of effort vs payoff in sales/marketing/etc. activities.\n        \"\"\"\n        # noinspection PyTypeChecker\n        gain_lift_group_data = self._create_gain_lift_data(predicted_probabilities=self._predicted_probabilities,  # noqa\n                                                           actual_classes=self._actual_classes,\n                                                           positive_class=self._positive_class)\n        # get the percent of positive class proportion, call it X%\n        # we want plot X%, such that ideally we've found i.e. predicted 100% of the positive events after\n        # only searching X% of the population. In other words, if we ordered our predictions by probability\n        # (in descending order) and there were e.g. 40 positive events out of a population of 100, then\n        # a model with perfect gain would have all 40 events in the top 40 spots (after ordering by\n        # probability)\n        # noinspection PyTypeChecker\n        number_of_positive_events = sum(self._actual_classes == self._positive_class)\n        positive_class_proportion = number_of_positive_events / len(self._actual_classes) * 100\n        perfect_gain_x_values = sorted(list(range(0, 110, 10)) + [positive_class_proportion])\n        perfect_gain_y_values = np.array(perfect_gain_x_values) / positive_class_proportion * 100\n        perfect_gain_y_values = [min(x, 100) for x in perfect_gain_y_values]\n\n        #####################################\n        gain_lift_group_data[['Model Gain', 'Random Gain']].plot(xticks=range(0, 110, 10),\n                                                                 yticks=range(0, 110, 10))\n\n        x_tick_labels = ['{}%'.format(x) for x in range(0, 110, 10)]\n        ax = plt.gca()\n        ax.figure.set_size_inches(8, 8)\n        ax.set_xticklabels(labels=x_tick_labels, size=9)\n        ax.set_yticklabels(labels=['{}%'.format(x) for x in range(0, 110, 10)], size=9)\n        ax.set_xlim(-5, 105)\n        ax.grid(which='major', alpha=1)\n        for index in range(10, 110, 10):\n            ax.annotate('{}%'.format(round(gain_lift_group_data.loc[index]['Model Gain'], 1)),\n                        xy=(index + 1, gain_lift_group_data.loc[index]['Model Gain'] - 1),\n                        size=10)\n\n        ax.scatter(x=range(0, 110, 10), y=gain_lift_group_data['Model Gain'].values, s=10)\n        line = matplotlib.lines.Line2D(perfect_gain_x_values,\n                                       perfect_gain_y_values,\n                                       color='green')\n        ax.scatter(x=positive_class_proportion, y=100, s=10, color='green')\n        ax.annotate('{}%'.format(round(positive_class_proportion, 1)),\n                    xy=(positive_class_proportion + 1, 100 - 2.5),\n                    size=10)\n        ax.add_line(line)\n        ax.legend(labels=['Model Gain', 'Random Gain', 'Perfect Gain'])\n        ax.set(**{'title': 'Gain Chart',\n                  'xlabel': 'Percentile (lower percentiles contain higher predicted probabilities)',\n                  'ylabel': '% of Positive Events Captured'})\n        plt.tight_layout()\n\n    def plot_lift_chart(self):\n        \"\"\"\n        :return: Lift chart shows when we are selecting the top X (x-axis) percent of the predictions such\n            that the highest predictions are looked at first, we can expected Y-times (y-axis) the total\n            number of positive events found than by randomly selecting X% of the data.\n        \"\"\"\n        gain_lift_group_data = self._create_gain_lift_data(predicted_probabilities=self._predicted_probabilities,  # noqa\n                                                           actual_classes=self._actual_classes,\n                                                           positive_class=self._positive_class)\n        # get the percent of positive class proportion, call it X%\n        # we want plot X%, such that ideally we've found i.e. predicted 100% of the positive events after\n        # only searching X% of the population. In other words, if we ordered our predictions by probability\n        # (in descending order) and there were e.g. 40 positive events out of a population of 100, then\n        # a model with perfect gain would have all 40 events in the top 40 spots (after ordering by\n        # probability)\n        # noinspection PyTypeChecker\n        #####################################\n        lift_data = gain_lift_group_data.loc[range(10, 110, 10)][['Model Lift']]\n        lift_data['Random Lift'] = [1 for _ in range(10, 110, 10)]\n        lift_data.plot(xticks=range(0, 110, 10))\n        ax = plt.gca()\n        ax.figure.set_size_inches(8, 8)\n        ax.set_xticklabels(labels=['{}%'.format(x) for x in range(0, 110, 10)], size=9)\n        ax.set_xlim(0, 105)\n        ax.grid(which='major', alpha=1)\n        for index in range(10, 110, 10):\n            ax.annotate(round(gain_lift_group_data.loc[index]['Model Lift'], 1),\n                        xy=(index - 1.5, gain_lift_group_data.loc[index]['Model Lift'] + 0.02),\n                        size=10)\n\n        ax.scatter(x=range(0, 110, 10), y=gain_lift_group_data['Model Lift'].values, s=10)\n        ax.set(**{'title': 'Lift Chart',\n                  'xlabel': 'Percentile (lower percentiles contain higher predicted probabilities)',\n                  'ylabel': 'Lift'})\n        plt.tight_layout()\n\n    @staticmethod\n    def _create_curve(x_coordinates, y_coordinates, threshold, ideal_threshold,\n                      title, x_label, y_label, corner):\n        index_of_ideal = int(round(ideal_threshold, 2) * 100)\n\n        fig = plt.figure()\n        ax = fig.add_subplot(1, 1, 1)\n        ax.axis('square')\n        ax.set_xlim(-0.01, 1.01)\n        ax.set_ylim(-0.01, 1.01)\n        ax.plot(x_coordinates, y_coordinates, drawstyle='steps-post')\n        ax.annotate('Closest to Upper {0}\\n(threshold={1})'.format(corner, str(round(ideal_threshold, 2))),\n                    xy=(x_coordinates[index_of_ideal], y_coordinates[index_of_ideal] - 0.01),\n                    xytext=(x_coordinates[index_of_ideal], y_coordinates[index_of_ideal] - 0.1),\n                    arrowprops=dict(facecolor='black', headwidth=4, width=2, headlength=4),\n                    horizontalalignment='left', verticalalignment='top')\n\n        index_of_custom_threshold = int(round(threshold, 2) * 100)\n        ax.annotate('Default threshold=' + str(round(threshold, 2)),\n                    xy=(x_coordinates[index_of_custom_threshold],\n                        y_coordinates[index_of_custom_threshold] - 0.01),\n                    xytext=(x_coordinates[index_of_custom_threshold],\n                            y_coordinates[index_of_custom_threshold] - 0.2),\n                    arrowprops=dict(facecolor='black', headwidth=4, width=2, headlength=4),\n                    horizontalalignment=corner.lower(), verticalalignment='top')\n\n        ax.set(**{'title': title,\n                  'xlabel': x_label,\n                  'ylabel': y_label})\n\n        return fig\n\n    @property\n    def all_quality_metrics(self) -> dict:\n        metrics = {'AUC ROC': self.auc_roc, 'AUC Precision/Recall': self.auc_precision_recall}\n        metrics.update(super().all_quality_metrics)\n        return metrics\n","sub_path":"oolearning/evaluators/TwoClassProbabilityEvaluator.py","file_name":"TwoClassProbabilityEvaluator.py","file_ext":"py","file_size_in_byte":19934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"167815137","text":"import pygame\nfrom os import listdir\nfrom os.path import isfile, join\nimport time\n\nclass AssetLoader:\n    def __init__(self):\n        self.status = \"carregando\"\n        self.mensagem = \"\"\n        self.imagens = []\n        self.sons = []\n        self.audios = []\n        self.fontes = []\n    \n    def carregarAssets(self):\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                pygame.quit()\n                sys.exit()\n        self.carregarImagens()\n        self.carregarFontes()\n        self.carregarAudios()\n        self.status = \"terminou\"\n        self.mensagem = \"\"\n\n    def carregarImagens(self):\n        path = \"../assets/img/\"\n        for file in listdir(path):\n            if isfile(join(path, file)):\n                self.mensagem = \"carregando imagem \" + file\n                img = {}\n                img[\"img\"] = pygame.image.load(join(path, file))\n                img[\"nome\"] = file\n                self.imagens.append(img)\n\n    def carregarFontes(self):\n        path = \"../assets/fonts/\"\n        for file in listdir(path):\n            if isfile(join(path, file)):\n                self.mensagem = \"carregando fonte \" + file\n                font = {}\n                font[\"font\"] = pygame.font.Font(join(path, file), 20)\n                font[\"nome\"] = file\n                self.fontes.append(font)\n                \n    def carregarAudios(self):\n        # path = \"../assets/audio/\"\n        # for file in listdir(path):\n        #     if isfile(join(path, file)):\n        #         self.mensagem = \"carregando fonte \" + file\n        #         font = {}\n        #         font[\"audio\"] = pygame.font.Font(join(path, file), 20)\n        #         font[\"nome\"] = file\n        #         self.audios.append(font)\n        pass\n    def procurar(self, nome, tipo):\n        if tipo == \"imagem\":    \n            for img in self.imagens:\n                if img[\"nome\"] == nome:\n                    return img[\"img\"]\n\n        if tipo == \"fonte\":    \n            for font in self.fontes:\n                if font[\"nome\"] == nome:\n                    return font[\"font\"]\n            \n        # self.status = \"next\"\n\nassetLoader = AssetLoader()","sub_path":"scripts/assetLoader.py","file_name":"assetLoader.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"202139602","text":"\"\"\"Functions to extract data from killmail JSON dicts.\"\"\"\nimport logging\nimport dateutil.parser\nimport millify\nimport collections\nimport operator\n\nfrom typing import Dict, Any, Optional, Callable\n\nfrom asyncio import gather\nfrom tornado.gen import multi\n\nfrom dataclasses import dataclass\n\nimport unchaind.util.esi as esi_util\nfrom unchaind.universe import Universe, System\nimport unchaind.static as static\n\nlog = logging.getLogger(__name__)\n\n\nasync def char_name_with_ticker(char: Dict[str, Any]) -> str:\n    \"\"\"Given a zkb attacker or victim, return character name\n       or something close.\"\"\"\n\n    try:\n        if \"character_id\" in char:\n            details, entity = await gather(\n                *[\n                    esi_util.character_details(char[\"character_id\"]),\n                    entity_ticker_for_char(char),\n                ]\n            )\n            return f\"{details['name']} [{entity}]\"\n        elif \"corporation_id\" in char:\n            # Some kills (e.g. POS modules) have no char id, but\n            # still belong to a corp/alliance\n            return await entity_ticker_for_char(char)\n        elif \"faction_id\" in char:\n            # If we have none of the above, just a faction, it was an NPC\n            return \"NPC\"\n    except Exception as e:\n        log.exception(e)\n\n    return \"?????\"\n\n\nasync def entity_ticker_for_char(char: Dict[str, Any]) -> str:\n    \"\"\"Given a zkb attacker or victim, return alliance/corp ticker\n       or something close.\"\"\"\n\n    try:\n        if \"alliance_id\" in char:\n            alliance = await esi_util.alliance_details(char[\"alliance_id\"])\n            return str(alliance[\"ticker\"])\n        elif \"corporation_id\" in char:\n            corp = await esi_util.corporation_details(char[\"corporation_id\"])\n            return str(corp[\"ticker\"])\n        elif \"faction_id\" in char:\n            return \"{NPC}\"\n    except Exception as e:\n        log.exception(e)\n\n    return \"?????\"\n\n\ndef _stringify_counter_by_popularity(c: collections.Counter) -> str:\n    \"\"\"Given a counter, give a string summary in descending popularity.\"\"\"\n    return \", \".join(\n        f\"{v} {k}\"\n        for k, v in sorted(c.items(), reverse=True, key=operator.itemgetter(1))\n    )\n\n\n@dataclass(frozen=True)\nclass KillmailStats:\n    kill_id: int\n    timestamp: int\n    victim_moniker: str\n    victim_ship: str\n    victim_ship_typeid: int\n    final_blow_moniker: str\n    top_damage_moniker: str\n    attacker_entities_summary: str\n    attacker_ships_summary: str\n    isk_value: int\n    solar_system_id: int\n    solar_system_name: str\n\n    def zkb_url(self) -> str:\n        return f\"https://zkillboard.com/kill/{self.kill_id}/\"\n\n    def victim_ship_thumb_url(self) -> str:\n        return f\"https://imageserver.eveonline.com/Render/{self.victim_ship_typeid}_128.png\"\n\n    def pretty_isk_value(self) -> str:\n        return str(millify.millify(self.isk_value, precision=2))\n\n\nasync def stats_for_killmail(\n    package: Dict[str, Any], universe: Universe\n) -> Optional[KillmailStats]:\n\n    try:\n        victim_ship_typeid: int = int(\n            package[\"killmail\"][\"victim\"][\"ship_type_id\"]\n        )\n        solar_system_id: int = int(package[\"killmail\"][\"solar_system_id\"])\n\n        d = {\n            \"victim_moniker\": char_name_with_ticker(\n                package[\"killmail\"][\"victim\"]\n            ),\n            \"victim_ship\": {\"name\": static.items[victim_ship_typeid].name},\n            \"final_blow_moniker\": char_name_with_ticker(\n                next(\n                    filter(\n                        lambda x: x[\"final_blow\"],\n                        package[\"killmail\"][\"attackers\"],\n                    )\n                )\n            ),\n            \"top_damage_moniker\": char_name_with_ticker(\n                max(\n                    package[\"killmail\"][\"attackers\"],\n                    key=lambda x: x[\"damage_done\"],\n                )\n            ),\n            \"attacker_entities\": gather(\n                *[\n                    entity_ticker_for_char(x)\n                    for x in package[\"killmail\"][\"attackers\"]\n                ]\n            ),\n            \"attacker_ships\": gather(\n                *[\n                    (esi_util.type_details(x[\"ship_type_id\"]))\n                    for x in package[\"killmail\"][\"attackers\"]\n                ]\n            ),\n            \"solar_system_name\": universe.system_name(System(solar_system_id)),\n        }\n\n        d = await multi(d)  # type: ignore\n\n        d[\"victim_ship\"] = d[\"victim_ship\"][\"name\"]  # type: ignore\n        d[\"attacker_entities_summary\"] = _stringify_counter_by_popularity(\n            collections.Counter(d[\"attacker_entities\"])  # type: ignore\n        )\n        d[\"attacker_ships_summary\"] = _stringify_counter_by_popularity(\n            collections.Counter(\n                map(  # type: ignore\n                    operator.itemgetter(\"name\"), d[\"attacker_ships\"]\n                )\n            )\n        )\n\n        d.pop(\"attacker_entities\", None)\n        d.pop(\"attacker_ships\", None)\n\n        d[\"timestamp\"] = int(\n            dateutil.parser.parse(\n                package[\"killmail\"][\"killmail_time\"]\n            ).timestamp()\n        )\n        d[\"victim_ship_typeid\"] = victim_ship_typeid\n        d[\"kill_id\"] = package[\"killID\"]\n        d[\"isk_value\"] = package[\"zkb\"][\"totalValue\"]\n        d[\"solar_system_id\"] = solar_system_id\n\n        return KillmailStats(**d)  # type: ignore\n    except Exception as e:\n        log.exception(e)\n\n    return None\n\n\nasync def _slack_payload_for_killmail(\n    notifier: Dict[str, Any], package: Dict[str, Any], universe: Universe\n) -> Optional[Dict[str, Any]]:\n\n    stats = await stats_for_killmail(package, universe)\n\n    if not stats:\n        log.warn(\"_slack_payload_for_killmail: failed to aquire stats\")\n        return None\n\n    text = f\"{stats.victim_moniker} lost a {stats.victim_ship} \"\n    text += f\"worth {stats.pretty_isk_value()} ISK \"\n    text += f\"\\nin *{stats.solar_system_name}* \"\n\n    rv = {\n        \"attachments\": [\n            {\n                \"fallback\": text,\n                \"text\": text,\n                \"footer\": stats.zkb_url(),\n                \"footer_icon\": \"https://zkillboard.com/img/wreck.png\",\n                \"ts\": stats.timestamp,\n                \"thumb_url\": stats.victim_ship_thumb_url(),\n                \"fields\": [\n                    {\n                        \"short\": True,\n                        \"title\": \"The attackers\",\n                        \"value\": stats.attacker_entities_summary,\n                    },\n                    {\n                        \"short\": True,\n                        \"title\": \"were flying\",\n                        \"value\": stats.attacker_ships_summary,\n                    },\n                ],\n            }\n        ]\n    }\n\n    if notifier.get(\"output\", None) and notifier[\"output\"].get(\n        \"include_vanity_stats\", False\n    ):\n        rv[\"attachments\"][0][\"fields\"].extend(  # type: ignore\n            [\n                {\n                    \"short\": True,\n                    \"title\": \"Final blow\",\n                    \"value\": stats.final_blow_moniker,\n                },\n                {\n                    \"short\": True,\n                    \"title\": \"Top damage\",\n                    \"value\": stats.top_damage_moniker,\n                },\n            ]\n        )\n\n    return rv\n\n\nasync def _discord_payload_for_killmail(\n    notifier: Dict[str, Any], package: Dict[str, Any], universe: Universe\n) -> Optional[Dict[str, Any]]:\n\n    stats = await stats_for_killmail(package, universe)\n\n    if not stats:\n        log.warn(\"_discord_payload_for_killmail: failed to aquire stats\")\n        return None\n\n    text = f\"{stats.victim_moniker} lost a {stats.victim_ship} \"\n    text += f\"worth {stats.pretty_isk_value()} ISK \"\n    text += f\"\\nin *{stats.solar_system_name}* \"\n\n    rv = {\n        \"embeds\": [\n            {\n                \"title\": text,\n                \"description\": f\"[zKill]({stats.zkb_url()})\",\n                \"color\": 7_471_618,\n                \"thumbnail\": {\"url\": stats.victim_ship_thumb_url()},\n                \"footer\": {\n                    \"icon_url\": \"https://zkillboard.com/img/wreck.png\",\n                    \"text\": stats.zkb_url(),\n                },\n                \"fields\": [\n                    {\n                        \"inline\": True,\n                        \"name\": \"The attackers\",\n                        \"value\": stats.attacker_entities_summary,\n                    },\n                    {\n                        \"inline\": True,\n                        \"name\": \"were flying\",\n                        \"value\": stats.attacker_ships_summary,\n                    },\n                ],\n            }\n        ]\n    }\n\n    return rv\n\n\npayload_for_killmail: Dict[str, Callable] = {\n    \"slack\": _slack_payload_for_killmail,\n    \"discord\": _discord_payload_for_killmail,\n}\n","sub_path":"unchaind/util/kill.py","file_name":"kill.py","file_ext":"py","file_size_in_byte":8833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"60271683","text":"import os\n\nimport stat\n\nfrom flask import Flask, Response, url_for, render_template\n\nfrom PIL import Image\n\nimport glob\n\napp = Flask(__name__)\napp.config['DEBUG'] = True  # TODO: disable before deploying on production server\n\nDATA_DIR = 'data'\nFOTO_DATA_DIR = 'data/foto'\n\n@app.route('//')\ndef album(gallery):\n    fotky = []\n    if not os.path.exists('%s/nahledy/%s' % (DATA_DIR, gallery)):\n        os.mkdir('%s/nahledy/%s' % (DATA_DIR, gallery))\n    cesty = glob.glob('%s/%s/*' % (FOTO_DATA_DIR, gallery))\n    cesty.sort()\n    for cesta in cesty:\n        try:\n            im = Image.open(cesta)\n        except Exception:\n            continue\n        foto = cesta.split('/')[-1]\n        thumbnail = '%s/nahledy/%s/%s' % (DATA_DIR, gallery, foto)\n        if not os.path.exists(thumbnail) or os.stat(cesta)[stat.ST_CTIME] > os.stat(thumbnail)[stat.ST_CTIME]:\n            if im.size[0] > im.size[1]:\n                box = (\n                    (im.size[0] - im.size[1]) / 2 , 0,\n                    (im.size[0] - im.size[1]) / 2 + im.size[1], im.size[1]\n                )\n            else:\n                box = (\n                    0, (im.size[1] - im.size[0]) / 2 ,\n                    im.size[0], (im.size[1] - im.size[0]) / 2 + im.size[0],\n                )\n            reg = im.crop(box)\n            reg.thumbnail((120,120))\n            reg.save(thumbnail, \"JPEG\")\n        fotky.append(\n            (url_for('stranka', gallery=gallery, foto=foto ),\n            url_for('nahled', gallery=gallery, foto=foto ))\n        )\n    return render_template(\n        'album.html', fotky=fotky, galerie=gallery,\n    )\n\n\n@app.route('/stranka//')\ndef stranka(gallery, foto):\n    fotky = glob.glob('%s/%s/*' % (FOTO_DATA_DIR, gallery))\n    fotky.sort()\n\n    foto_url = (\n        url_for('stranka', gallery=gallery, foto=foto ),\n        url_for('nahled', gallery=gallery, foto=foto ),\n        url_for('foto', gallery=gallery, foto=foto )\n    )\n\n    foto_prev = fotky[0].split('/')[-1]\n    foto_prev_url = (\n        url_for('stranka', gallery=gallery, foto=foto_prev ),\n        url_for('nahled', gallery=gallery, foto=foto_prev )\n    )\n    foto_next = fotky[-1].split('/')[-1]\n    foto_next_url = (\n        url_for('stranka', gallery=gallery, foto=foto_next ),\n        url_for('nahled', gallery=gallery, foto=foto_next )\n    )\n    i = 0\n    while i < len(fotky):\n        if fotky[i].split('/')[-1] == foto:\n            if i > 0:\n                foto_prev = fotky[i - 1].split('/')[-1]\n                foto_prev_url = (\n                    url_for('stranka', gallery=gallery, foto=foto_prev ),\n                    url_for('nahled', gallery=gallery, foto=foto_prev )\n                )\n            if i < len(fotky) - 1:\n                foto_next = fotky[i + 1].split('/')[-1]\n                foto_next_url = (\n                    url_for('stranka', gallery=gallery, foto=foto_next ),\n                    url_for('nahled', gallery=gallery, foto=foto_next )\n                )\n        i = i + 1\n    return render_template(\n        'stranka.html', foto=foto_url, galerie=gallery,\n        foto_prev=foto_prev_url, foto_next=foto_next_url\n    )\n\n\n@app.route('/nahled//')\ndef nahled(gallery, foto):\n    with open('%s/nahledy/%s/%s' % (DATA_DIR, gallery, foto), 'rb') as f:\n        response = f.read()\n    return Response(response=response, status=200, headers={ 'Content-Type': 'image/jpeg'} )\n\n\n@app.route('/foto//')\ndef foto(gallery, foto):\n    with open('%s/%s/%s' % (FOTO_DATA_DIR, gallery, foto), 'rb') as f:\n        response = f.read()\n    return Response(response=response, status=200, headers={ 'Content-Type': 'image/jpeg'} )\n\n\n\n","sub_path":"album/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"337467020","text":"import bpy, re\nfrom .renaming_utilities import getRenamingList, callInfoPopup\n\nclass VIEW3D_OT_Vallidate(bpy.types.Operator):\n    bl_idname = \"renaming.vallidate\"\n    bl_label = \"Vallidate Names\"\n    bl_description = \"replaces parts in the object names\"\n    bl_options = {'REGISTER', 'UNDO'}\n\n    def execute(self, context):\n        wm = context.scene\n\n        prefs = bpy.context.preferences.addons[__package__].preferences\n        regex = prefs.regex_Mesh\n        compiledRegex = re.compile(regex)\n\n        renamingList = []\n        renamingList = getRenamingList(self, context)\n\n        if len(renamingList) > 0:\n            for entity in renamingList:\n                if entity is not None:\n                    if regex is not '':\n                        match = bool(compiledRegex.match(entity.name))\n\n                    # if wm.naming_vallidate is not '':\n                    #     pattern = re.compile(re.escape(wm.naming_vallidate))\n                    #     match = re.match(pattern, entity.name)\n\n                        if match:\n                            wm.renaming_messages.addMessage(\"Vallid\", entity.name)\n                        else:\n                            wm.renaming_messages.addMessage(\"Not\", entity.name)\n\n        callInfoPopup(context)\n        return {'FINISHED'}\n\n\n# addon Panel\nclass VIEW3D_PT_vallidation(bpy.types.Panel):\n    \"\"\"Creates a renaming Panel\"\"\"\n    bl_label = \"Vallidation\"\n    bl_space_type = \"VIEW_3D\"\n    bl_region_type = \"UI\"\n    bl_category = \"Vallidation\"\n\n    def draw(self, context):\n\n        layout = self.layout\n        scene = context.scene\n\n        prefs = bpy.context.preferences.addons[__package__].preferences\n        regex = prefs.regex_Mesh\n\n        row = layout.row()\n        row.label(text = prefs.regex_Mesh)\n        row = layout.row()\n        row.operator(\"renaming.vallidate\")\n","sub_path":"renaming_vallidate.py","file_name":"renaming_vallidate.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"621673150","text":"import os\nimport logging\nimport gzip\nimport shutil\nimport pandas as pd\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\nbeam_param_map = {'beam_sample': 'beam.agentsim.agentSampleSizeAsFractionOfPopulation',\n                  'beam_replanning_portion': 'beam.agentsim.agents.plans.merge.fraction',\n                  'max_plans_memory': 'beam.replanning.maxAgentPlanMemorySize'\n                  }\n\n\ndef update_beam_config(settings, param, valueOverride=None):\n    if param in settings:\n        config_header = beam_param_map[param]\n        if valueOverride is None:\n            config_value = settings[param]\n        else:\n            config_value = valueOverride\n        beam_config_path = os.path.join(\n            settings['beam_local_input_folder'],\n            settings['region'],\n            settings['beam_config'])\n        modified = False\n        with open(beam_config_path, 'r') as file:\n            data = file.readlines()\n        with open(beam_config_path, 'w') as file:\n            for line in data:\n                if config_header in line:\n                    if ~modified:\n                        file.writelines(config_header + \" = \" + str(config_value) + \"\\n\")\n                    modified = True\n                else:\n                    file.writelines(line)\n            if not modified:\n                file.writelines(\"\\n\" + config_header + \" = \" + str(config_value) + \"\\n\")\n    else:\n        logger.warning(\"Tried to modify parameter {0} but couldn't find it in settings.yaml\".format(param))\n\n\ndef make_archive(source, destination):\n    \"\"\"\n    From https://stackoverflow.com/questions/32640053/compressing-directory-using-shutil-make-archive-while-preserving-directory-str\n    \"\"\"\n    base = os.path.basename(destination)\n    name = base.split('.')[0]\n    fmt = base.split('.')[1]\n    archive_from = os.path.dirname(source)\n    archive_to = os.path.basename(source.strip(os.sep))\n    shutil.make_archive(name, fmt, archive_from, archive_to)\n    shutil.move('%s.%s' % (name, fmt), destination)\n\n\ndef copy_plans_from_asim(settings, year, replanning_iteration_number=0):\n    asim_output_data_dir = settings['asim_local_output_folder']\n    beam_scenario_folder = os.path.join(\n        settings['beam_local_input_folder'],\n        settings['region'],\n        settings['beam_scenario_folder'])\n\n    def copy_with_compression_asim_file_to_beam(asim_file_name, beam_file_name):\n        asim_file_path = os.path.join(asim_output_data_dir, asim_file_name)\n        beam_file_path = os.path.join(beam_scenario_folder, beam_file_name)\n        logger.info(\"Copying asim file %s to beam input scenario file %s\", asim_file_path, beam_file_path)\n\n        if os.path.exists(asim_file_path):\n            pd.read_csv(asim_file_path, dtype={\"household_id\": pd.Int64Dtype(),\n                                               \"person_id\": pd.Int64Dtype(),\n                                               \"trip_id\": pd.Int64Dtype(),\n                                               \"VEHICL\": pd.Int64Dtype(),\n                                               \"age\": pd.Int64Dtype(),\n                                               \"sex\": pd.Int64Dtype()}\n                        ).rename(columns={\"VEHICL\": \"cars\"}).to_csv(\n                beam_file_path, compression=\"gzip\")\n            # with open(asim_file_path, 'rb') as f_in, gzip.open(\n            #         beam_file_path, 'wb') as f_out:\n            #     f_out.writelines(f_in)\n\n    def copy_with_compression_asim_file_to_asim_archive(file_path, file_name, year, replanning_iteration_number):\n        iteration_folder_name = \"year-{0}-iteration-{1}\".format(year, replanning_iteration_number)\n        iteration_folder_path = os.path.join(asim_output_data_dir, iteration_folder_name)\n        if ~os.path.exists(os.path.abspath(iteration_folder_path)):\n            os.makedirs(iteration_folder_path, exist_ok=True)\n        input_file_path = os.path.join(file_path, file_name)\n        target_file_path = os.path.join(iteration_folder_path, file_name)\n        if target_file_path.endswith('.csv'):\n            target_file_path += '.gz'\n            if os.path.exists(file_path):\n                with open(input_file_path, 'rb') as f_in, gzip.open(\n                        target_file_path, 'wb') as f_out:\n                    f_out.writelines(f_in)\n        elif os.path.isdir(os.path.abspath(input_file_path)):\n            make_archive(input_file_path, target_file_path + \".zip\")\n        else:\n            shutil.copy(input_file_path, target_file_path)\n\n    def merge_only_updated_households():\n        asim_plans_path = os.path.join(asim_output_data_dir, 'final_plans.csv')\n        asim_households_path = os.path.join(asim_output_data_dir, 'final_households.csv')\n        asim_persons_path = os.path.join(asim_output_data_dir, 'final_persons.csv')\n        beam_plans_path = os.path.join(beam_scenario_folder, 'plans.csv.gz')\n        beam_households_path = os.path.join(beam_scenario_folder, 'households.csv.gz')\n        beam_persons_path = os.path.join(beam_scenario_folder, 'persons.csv.gz')\n        if os.path.exists(beam_plans_path):\n            logger.info(\"Merging asim outputs with existing beam input scenario files\")\n            original_households = pd.read_csv(beam_households_path)\n            updated_households = pd.read_csv(asim_households_path)\n            original_persons = pd.read_csv(beam_persons_path)\n            updated_persons = pd.read_csv(asim_persons_path)\n\n            per_o = original_persons.person_id.unique()\n            per_u = updated_persons.person_id.unique()\n            overlap = np.in1d(per_u, per_o).sum()\n            logger.info(\"There were %s persons replanned out of %s originally, and %s of them existed before\",\n                        len(per_u), len(per_o), overlap)\n\n            hh_o = (original_persons.household_id.unique())\n            hh_u = (updated_persons.household_id.unique())\n            overlap = np.in1d(hh_u, hh_o).sum()\n            logger.info(\"There were %s households replanned out of %s originally, and %s of them existed before\",\n                        len(hh_u), len(hh_o), overlap)\n\n            persons_final = pd.concat([updated_persons, original_persons.loc[\n                                                        ~original_persons.person_id.isin(per_u), :]])\n            persons_final.to_csv(beam_persons_path, index=False, compression='gzip')\n            households_final = pd.concat([updated_households, original_households.loc[\n                                                              ~original_households.household_id.isin(hh_u), :]])\n            households_final.to_csv(beam_households_path, index=False, compression='gzip')\n\n            original_plans = pd.read_csv(beam_plans_path).rename(columns={'tripId': 'trip_id'})\n            updated_plans = pd.read_csv(asim_plans_path)\n            unchanged_plans = original_plans.loc[~original_plans.person_id.isin(per_u), :]\n            logger.info(\"Adding %s new plan elements after and keeping %s from previous iteration\",\n                        len(updated_plans), len(unchanged_plans))\n            plans_final = pd.concat([updated_plans, unchanged_plans])\n            persons_with_plans = np.in1d(persons_final.person_id.unique(), plans_final.person_id.unique()).sum()\n            logger.info(\"Of %s persons, %s of them have plans\", len(persons_final), persons_with_plans)\n            plans_final.to_csv(beam_plans_path, compression='gzip', index=False)\n        else:\n            logger.info(\"No plans existed already so copying them directly. THIS IS BAD\")\n            pd.read_csv(asim_plans_path).to_csv(beam_plans_path, compression='gzip')\n\n    if replanning_iteration_number < 0:\n        copy_with_compression_asim_file_to_beam('final_plans.csv', 'plans.csv.gz')\n        copy_with_compression_asim_file_to_beam('final_households.csv', 'households.csv.gz')\n        copy_with_compression_asim_file_to_beam('final_persons.csv', 'persons.csv.gz')\n        copy_with_compression_asim_file_to_beam('final_land_use.csv', 'land_use.csv.gz')\n        copy_with_compression_asim_file_to_beam('final_tours.csv', 'tours.csv.gz')\n        copy_with_compression_asim_file_to_beam('final_trips.csv', 'trips.csv.gz')\n        copy_with_compression_asim_file_to_beam('final_joint_tour_participants.csv', 'joint_tour_participants.csv.gz')\n    else:\n        merge_only_updated_households()\n\n    if settings.get('final_asim_plans_folder', False):\n        # This first one not currently necessary when asim-lite is replanning all households\n        # copy_with_compression_asim_file_to_asim_archive(asim_output_data_dir, 'final_plans.csv', year,\n        #                                                 replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(beam_scenario_folder, 'plans.csv.gz', year,\n                                                        replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(beam_scenario_folder, 'households.csv.gz', year,\n                                                        replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(beam_scenario_folder, 'persons.csv.gz', year,\n                                                        replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(asim_output_data_dir, 'final_land_use.csv', year,\n                                                        replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(asim_output_data_dir, 'final_tours.csv', year,\n                                                        replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(asim_output_data_dir, 'final_trips.csv', year,\n                                                        replanning_iteration_number)\n        copy_with_compression_asim_file_to_asim_archive(asim_output_data_dir, 'trip_mode_choice', year,\n                                                        replanning_iteration_number)\n    return\n","sub_path":"pilates/beam/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":10027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"596974550","text":"from django.shortcuts import render,HttpResponse\nfrom django.http import JsonResponse\nimport csv\nfrom ss.models import Emp,Emp1\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n# Create your views here.\n\n\n\ndef wscrap(request):\n    res=requests.get(\"https://www.moviebuff.com/vinaya-vidheya-rama-2019-tamil\").content\n    jsoup=BeautifulSoup(res)\n    div=jsoup.find('div',attrs={'id':'cast'})\n    result=div.find_all('div',attrs={'class':'col-xs-6 col-sm-4 credit'})\n    list = []\n    list2=[]\n    for k in result:\n        p=k.find('div',attrs={'name'}).text\n        r=k.img['src']\n        list.append(p)\n        list2.append(r)\n    mylist = zip(list, list2)\n    #return render(request, \"wscrap.html\", {'res': list,'img':list2})\n    return render(request, \"wscrap.html\", {'res': mylist})\n        #break\n\ndef wscrapJsonResponse(request):\n    res=requests.get(\"https://www.moviebuff.com/vinaya-vidheya-rama-2019-tamil\").content\n    jsoup=BeautifulSoup(res)\n    div=jsoup.find('div',attrs={'id':'cast'})\n    result=div.find_all('div',attrs={'class':'col-xs-6 col-sm-4 credit'})\n    list = []\n    for k in result:\n        dummy_dic=dict()\n        dummy_dic['Name']=k.find('div',attrs={'name'}).text\n        dummy_dic['image']=k.img['src']\n        list.append(dummy_dic)\n    return JsonResponse(dummy_dic)\n\n\ndef weather(request):\n    res=requests.get(\"http://www.ratingdada.com/1558/prema-pipasi-movie-review-rating\").content\n    jsoup=BeautifulSoup(res)\n    city1=jsoup.find('div', attrs={'class':'main-content-div'})\n    city=city1\n    return render(request,'weather.html',{'res': city1})\n\n\n\n\n\n\n\n\n\n\n\n#webscraping is above\n\n\n\n\n\n\n\ndef test(request):\n    if request.method=='GET':\n        name=request.GET['name']\n        dob = request.GET['dob']\n        emp1=Emp1(name1=name,dob=dob)\n        emp1.save()\n        emp = Emp1.objects.all()\n        return render(request, \"test.html\", {'emp': emp})\n    else:\n        emp = Emp1.objects.all()\n        return render(request,\"test.html\",{'emp':emp})\n\ndef download_csv(request):\n    response=HttpResponse(content_type='text/csv')\n    response['Content-Description'] = 'attachment; filename=\"users.csv\"'\n    writer=csv.writer(response)\n    writer.writerow(['Name','Age'])\n    users=Emp.objects.all().values_list('name','age')\n\n    for user in users:\n        writer.writerow(user)\n\n        return response\n\n\n\n\n\n#========================Class Based Views========================================================\nfrom rest_framework.views import APIView, View\nfrom .serializer import MoviesSerializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.shortcuts import render, HttpResponse, get_object_or_404\n\nclass MovieApi(APIView):\n    def get(self, request, **kwargs):\n        if kwargs.get('pk'):\n            pk = kwargs.get('pk')\n            saved_movie = get_object_or_404(Emp.objects.all(), pk=pk)\n            serializer = MoviesSerializer(saved_movie)\n            return Response({\"Movie\": serializer.data})\n\n        movies = Emp.objects.all()\n        movies = MoviesSerializer(movies, many=True)\n        return Response({'Movies': movies.data})\n        # return HttpResponse({'Movies': movies.data})\n\n    def post(self, request):\n\n        serializer = MoviesSerializer(data=request.data)\n\n        if serializer.is_valid():\n            serializer.save()\n            return Response(serializer.data, status=status.HTTP_201_CREATED)\n        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n    def put(self, request, pk):\n        movie = get_object_or_404(Emp.objects.all(), pk=pk)\n        serializer = MoviesSerializer(instance=movie, data=request.data, partial=True)\n        if serializer.is_valid(raise_exception=True):\n            movie_saved = serializer.save()\n        return Response({\"success\": \"Article '{}' updated successfully\".format(movie_saved.movie_name)})\n\n    def delete(self, request, pk):\n        # Get object with this pk\n        movie = get_object_or_404(Emp.objects.all(), pk=pk)\n        movie.delete()\n        return Response({\"message\": \"Article with id `{}` has been deleted.\".format(pk)}, status=204)\n\n\n\nclass Demo():\n    name=\"hello python\"\n    age=25\n    def __init__(self):\n        self.village=\"peddampet\"\n    @classmethod\n    def setage(self,sage):\n        self.name=sage\nobj=Demo()\nobj.setage(\"peddampet\")\nname1=obj.name\nfrom ss.views2 import name\nimport json\ndef home(request):\n\n\n    # a Python object (dict):\n    x = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},\n          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}\n\n    # convert into JSON:\n    y = json.dumps(x)\n\n    # the result is a JSON string:\n    return render(request,'home.html',{'name1':y})\n\ndef home1(request):\n    return HttpResponse(\"welcome :\"+name)\n\n\n\n#social media app\n\nfrom ss.models import Hotel\nfrom django.shortcuts import redirect\nfrom ss.models import Gallery\n\ndef hotel(request):\n    if request.method=='POST':\n        name=request.POST['name']\n        file = request.FILES['file']\n        stu=Hotel(name=name,file=file)\n        stu.save()\n        return render(request, 'image.html')\n    else:\n        return render(request, 'image.html')\n\ndef socialapp(request):\n    user=Hotel.objects.all().order_by('name')\n    return render(request,'socialapp.html',{'user':user})\n\ndef delete(request,id):\n    user=Hotel.objects.get(id=id)\n    user.delete()\n    return redirect('socialapp')\n\n\ndef update(request,id):\n    user = Hotel.objects.get(id=id)\n    if request.method=='POST':\n        user.name=request.POST['name']\n        user.file=request.FILES['file']\n        user.save()\n        return redirect('socialapp')\n    else:\n        return render(request, 'update.html')\n\n\n\ndef insertgallery(request,id):\n    user = Hotel.objects.get(id=id)\n    if request.method=='POST':\n        gimage=request.FILES['gimage']\n        Gallery(gimage=gimage,progallery=user).save()\n        return render(request, 'uploadgallery.html',{'user':user})\n    elif request.method=='GET':\n        return render(request, 'uploadgallery.html',{'user':user})\n    return redirect('socialapp')\n\ndef deleteimage(request,id):\n     user1=Gallery.objects.get(id=id)\n     user1.delete()\n     return redirect(\"socialapp\")\n\n\ndef updateimage(request,id):\n    user=Gallery.objects.get(id=id)\n    if request.method=='POST':\n        user.gimage=request.FILES['gimage']\n        user.save()\n        return redirect(\"socialapp\")\n    else:\n        return render(request, 'insergallery.html')\n\ndef testurls(request,id):\n    return render(request,\"weather.html\",{'num':id})\n","sub_path":"ss/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"505534449","text":"#! /usr/bin/python3\n\nimport collections\nimport os\nimport sys\nimport time\n\nimport psycopg2\nimport requests\nimport word_seg\n\n##\n## Utility\n##\n\ndef fmt_interval(interval):\n    m, s = divmod(interval, 60)\n    h, m = divmod(m, 60)\n    return \"{}:{:>02}:{:>05.2f}\".format(int(h), int(m), s)\n\nstart = None\ndef elapsed():\n    stop = time.monotonic()\n    global start\n    if start is None:\n        start = stop\n    return fmt_interval(stop - start)\n\n# This can't be done with defaultdict, but __missing__ is a feature of\n# dict in general!\nclass default_identity_dict(dict):\n    def __missing__(self, key): return key\n\n# Map CLD2's names for a few things to Google Translate's names.\nCLD2_TO_GOOGLE = default_identity_dict({\n    \"zh-Hant\" : \"zh-TW\"\n})\nGOOGLE_TO_CLD2 = default_identity_dict({\n    \"zh-TW\" : \"zh-Hant\"\n})\n\n\n##\n## Modified version of\n## http://thomassileo.com/blog/2012/03/26/using-google-translation-api-v2-with-python/\n##\n\n# Maximum number of characters per POST request.  The documentation is\n# a little vague about exactly how you structure this, but I *think*\n# it means to say that if you use POST then you don't have to count\n# the other parameters and repeated &q= constructs toward the limit.\nCHARS_PER_POST = 5000\n\n# There is also a completely undocumented limit of 128 q= segments per\n# translation request.\nWORDS_PER_POST = 128\n\n# Words longer than this are liable to (a) actually be some sort of\n# HTML spew, and (b) cause Postgres to complain about not being able\n# to index things larger than \"1/3 of a buffer page\".  Because of (a),\n# we set the limit well below the threshold that triggers (b).\nWORD_LENGTH_LIMIT = 750\n\nwith open(os.path.join(os.environ[\"HOME\"], \".google-api-key\"), \"rt\") as f:\n    API_KEY = f.read().strip()\n\nTRANSLATE_URL = \\\n    \"https://www.googleapis.com/language/translate/v2\"\nGET_LANGUAGES_URL = \\\n    \"https://www.googleapis.com/language/translate/v2/languages\"\n\nSESSION = requests.Session()\n\ndef do_GET(url, params):\n    return SESSION.get(url, params=params).json()\n\ndef do_POST(url, postdata):\n    while True:\n        try:\n            resp = SESSION.post(url, data=postdata, headers={\n                'Content-Type':\n                'application/x-www-form-urlencoded;charset=utf-8',\n                'X-HTTP-Method-Override': 'GET'\n            })\n            resp.raise_for_status()\n            return resp.json()\n        except Exception:\n            sys.stdout.write('.')\n            sys.stdout.flush()\n            time.sleep(15)\n            continue\n\ndef get_translations(source, target, words):\n    blob = do_POST(TRANSLATE_URL, {\n        'key': API_KEY,\n        'source': source,\n        'target': target,\n        'q': words\n    })\n    return list(zip(words,\n                    (x[\"translatedText\"]\n                     for x in blob[\"data\"][\"translations\"])))\n\ndef get_google_languages():\n    blob = do_GET(GET_LANGUAGES_URL, {'key' : API_KEY})\n    # Don't bother translating English into English.\n    return frozenset(lc for lc in (\n            GOOGLE_TO_CLD2[x[\"language\"]] for x in blob[\"data\"][\"languages\"]\n        ) if lc != \"en\")\n\ndef translate_block(lc, wordlist):\n    if not wordlist:\n        return []\n\n    translations = []\n    i = 0\n    skipped = 0\n    nwords = len(wordlist)\n    nchars = 0\n    this_block = []\n\n    while i < nwords and len(this_block) < WORDS_PER_POST:\n        x = wordlist[i]\n        i += 1\n\n        l = len(x)\n        if l > WORD_LENGTH_LIMIT:\n            sys.stdout.write(\"{}: word too long, skipping: {}\\n\"\n                             .format(lc, x))\n            skipped += 1\n            continue\n\n        if word_seg.is_nonword(x):\n            translations.append((x, x))\n            continue\n\n        u = word_seg.is_url(x)\n        if u:\n            translations.append((x, u))\n            continue\n\n        if nchars + l > CHARS_PER_POST:\n            i -= 1\n            break\n\n        this_block.append(x)\n        nchars += l\n\n    sys.stdout.write(\"{} {}: translating {} words {} chars, \"\n                     \"{} passthru, {} left...\"\n                     .format(elapsed(), lc, len(this_block), nchars,\n                             len(translations), nwords - i))\n    sys.stdout.flush()\n\n    if this_block:\n        translations.extend(get_translations(CLD2_TO_GOOGLE[lc], 'en',\n                                             this_block))\n    assert len(translations) + skipped == i\n    sys.stdout.write(\"ok\\n\")\n    sys.stdout.flush()\n\n    del wordlist[:i]\n    return translations\n\n##\n## Database interaction\n##\n\ndef load_todo(cur, can_translate):\n    todo = collections.defaultdict(list)\n    cur.execute(\"SELECT w.lang, w.word FROM (\"\n                \"  SELECT DISTINCT chunk->>'l' AS lang,\"\n                \"                  jsonb_array_elements_text(chunk->'t') AS word\"\n                \"    FROM (SELECT jsonb_array_elements(segmented) AS chunk\"\n                \"            FROM extracted_plaintext \"\n                \"           WHERE segmented is not null) _\"\n                \"   WHERE chunk->>'l' = ANY(%s)) w\"\n                \" LEFT JOIN translations t\"\n                \"        ON w.lang = t.lang AND w.word = t.word\"\n                \"     WHERE t.word IS NULL\",\n                (sorted(can_translate),))\n    for row in cur:\n        todo[row[0]].append(row[1])\n    return todo\n\ndef record_translations(cur, lc, translations):\n    cur.executemany(\"INSERT INTO translations VALUES (%s, %s, %s)\",\n                    ( (lc, word, engl) for word, engl in translations ))\n\ndef todo_report(todo):\n    words = 0\n    chars = 0\n    langs = 0\n    for lang, wordlist in todo.items():\n        if wordlist:\n            langs += 1\n            words += len(wordlist)\n            chars += sum(len(w) for w in wordlist)\n\n    sys.stdout.write(\"{}: todo {} words, {} chars in {} languages\\n\"\n                     .format(elapsed(), words, chars, langs))\n\ndef main():\n    sys.stdout.write(\"{}: getting translatable languages...\"\n                     .format(elapsed()))\n    sys.stdout.flush()\n    can_translate = get_google_languages()\n    sys.stdout.write(\"ok, {}\\n\".format(len(can_translate)))\n    db = psycopg2.connect(dbname=sys.argv[1])\n    cur = db.cursor()\n    sys.stdout.write(\"{}: getting words to translate...\\n\".format(elapsed()))\n    todo = load_todo(cur, can_translate)\n    done = False\n    while not done:\n        done = True\n        language_order = sorted(todo.keys(), key=lambda lc: (len(todo[lc]),lc))\n        todo_report(todo)\n        for lc in language_order:\n            wordlist = todo[lc]\n            if wordlist:\n                done = False\n                record_translations(cur, lc, translate_block(lc, wordlist))\n                time.sleep(0.05)\n            else:\n                del todo[lc]\n        db.commit()\n\nmain()\n","sub_path":"analysis/update_translation_database.py","file_name":"update_translation_database.py","file_ext":"py","file_size_in_byte":6733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"114601269","text":"\nimport sqlite3\n\nfrom os.path import split, join\n\n\n\ndef get_all_areas():\n    \"\"\"\n    Returns a list of tuples representing all the rows in the\n    area table.\n    \"\"\"\n    this_dir = split(__file__)[0]\n    fname = join(this_dir, 'measures.sqlite')\n    conn = sqlite3.connect(fname)\n    my_tuple = ()\n\n\n    try:\n        crs = conn.cursor()\n        cmd1 = \"select * from area\"\n        crs.execute(cmd1)\n        my_tuple =  crs.fetchall()\n        #print(my_tuple)\n        return my_tuple\n\n    finally:\n        conn.close()\n\n\ndef get_locations_for_area(area_id):\n    \"\"\"\n    Return a list of tuples giving the locations for the given area.\n    \"\"\"\n\n    this_dir = split(__file__)[0]\n    fname = join(this_dir, 'measures.sqlite')\n    conn = sqlite3.connect(fname)\n    my_tuple = ()\n\n    try:\n        crs = conn.cursor()\n        cmd1 = \"select * from  location where location_area = ?\"\n        crs.execute(cmd1, [area_id])\n        my_tuple = crs.fetchall()\n        #print(my_tuple)\n\n        for row in my_tuple:\n            #print('{0} : {1}, {2}'.format(row[0], row[1], row[2]))\n            #print row[1]\n\n            loc = row[1]\n            #print loc\n\n        return my_tuple\n\n    finally:\n        conn.close()\n\ndef get_measurements_for_location(location_id):\n    \"\"\"\n    Return a list of tuples giving the measurement rows for the given location.\n    \"\"\"\n    this_dir = split(__file__)[0]\n    fname = join(this_dir, 'measures.sqlite')\n    conn = sqlite3.connect(fname)\n    my_tuple = ()\n\n    try:\n        crs = conn.cursor()\n        cmd1 = \"select * from  measurement where measurement_location = ?\"\n        crs.execute(cmd1, [location_id])\n        my_tuple = crs.fetchall()\n        #print(my_tuple)\n\n        return my_tuple\n\n    finally:\n        conn.close()\n\n\ndef get_categories_for_area(area_id):\n    \"\"\"\n    Return a list of rows from the category table that all contain the given area.\n    \"\"\"\n    this_dir = split(__file__)[0]\n    fname = join(this_dir, 'measures.sqlite')\n    conn = sqlite3.connect(fname)\n    my_tuple = []\n    my_tuple2 = []\n    categories = []\n    try:\n        crs = conn.cursor()\n        cmd1 = \"select * from  category_area where area_id = ?\"\n        crs.execute(cmd1, [area_id])\n        my_tuple = crs.fetchall()\n        #print(my_tuple)\n\n        for row in my_tuple:\n            crs2 = conn.cursor()\n            #print row[0]\n            cmd2 = \"select * from  category where category_id = ?\"\n            crs2.execute(cmd2, [row[0]])\n            my_tuple2 = crs2.fetchall()\n            for category_row in my_tuple2:\n                categories.append(category_row)\n\n\n        #print my_tuple\n        #print (categories)\n        return categories\n\n    finally:\n        conn.close()\n        conn.close()","sub_path":"assignment-2/db_access.py","file_name":"db_access.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"588272025","text":"import requests\nimport eyed3\nimport os\n\ni = 1\n\nprint(\"Bem vindo!! Aqui você pode baixar áudios.\")\nprint()\n\nprint(\"=============== Menu ===============\")\nprint(\"1 - Baixar áudio\")\nprint(\"2 - Sair\")\nopcao = int(input(\"Informe a opção: \"))\n\nwhile(opcao == 1):\n    # Consultar URL\n    url = input(\"Informe a URL: \")\n    request = requests.get(url, allow_redirects=True)\n\n    # Baixar o arquivo e nomear com o valor \"1\"\n    file_name = \"arquivo.mp3\"\n    open(file_name, \"wb\").write(request.content)\n\n    # Variável para receber o titulo do arquivo\n    audiofile = eyed3.load(\"arquivo.mp3\")\n\n    # Variavel recebendo o nome do arquivo.\n    file_name = audiofile.tag.title\n\n    os.rename(r'arquivo.mp3',r'{} -  {}.mp3'.format(i, file_name))\n    i = i + 1","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"267050409","text":"\"\"\"\n\n\"Memory saver\" for limited resources.\nAlso does some base transformations for Konstantin's FE.\n\n\"\"\"\n\nimport datetime\nimport json\nimport warnings\n\nimport math\nimport numpy as np\nimport pandas as pd\n\nimport ieee_utils.helpers as helpers\n\nwarnings.filterwarnings('ignore')\n\n\ndef minify_data():\n    # VARS\n    #################################################################################\n    with open('./settings.json', 'r') as f:\n        config = json.load(f)\n\n    start_date = datetime.datetime.strptime('2017-11-30', '%Y-%m-%d')\n\n    # DATA LOAD\n    #################################################################################\n    train_df = pd.read_csv(config['RAW_PATH'] + 'train_transaction.csv')\n    test_df = pd.read_csv(config['RAW_PATH'] + 'test_transaction.csv')\n    test_df['isFraud'] = -1\n\n    train_identity = pd.read_csv(config['RAW_PATH'] + 'train_identity.csv')\n    test_identity = pd.read_csv(config['RAW_PATH'] + 'test_identity.csv')\n\n    # TransactionDT\n    #################################################################################\n    for df in [train_df, test_df]:\n        df['DT'] = df['TransactionDT'].apply(lambda x: (start_date + datetime.timedelta(seconds=x)))\n        df['DT_M'] = ((df['DT'].dt.year - 2017) * 12 + df['DT'].dt.month).astype(np.int8)\n        df['DT_W'] = ((df['DT'].dt.year - 2017) * 52 + df['DT'].dt.weekofyear).astype(np.int8)\n        df['DT_D'] = ((df['DT'].dt.year - 2017) * 365 + df['DT'].dt.dayofyear).astype(np.int16)\n\n        df['DT_hour'] = df['DT'].dt.hour.astype(np.int8)\n        df['DT_week_month'] = df['DT'].dt.day / 7\n        df['DT_week_month'] = df['DT_week_month'].apply(lambda x: math.ceil(x))\n\n    for col in ['DT_M', 'DT_W', 'DT_D']:\n        temp_df = pd.concat([train_df[[col]], test_df[[col]]])\n        fq_encode = temp_df[col].value_counts().to_dict()\n\n        train_df[col + '_total'] = train_df[col].map(fq_encode)\n        test_df[col + '_total'] = test_df[col].map(fq_encode)\n\n    # card4, card6, ProductCD\n    #################################################################################\n    for col in ['card4', 'card6', 'ProductCD']:\n        temp_df = pd.concat([train_df[[col]], test_df[[col]]])\n        col_encoded = temp_df[col].value_counts().to_dict()\n        train_df[col] = train_df[col].map(col_encoded)\n        test_df[col] = test_df[col].map(col_encoded)\n\n    outliers = train_df['card6'].value_counts()\n    outliers = outliers[outliers < 10000]\n\n    if len(outliers) > 0:\n        for fix_val in list(outliers.index):\n            train_df['card6'] = np.where(train_df['card6'] == fix_val, np.nan, train_df['card6'])\n            test_df['card6'] = np.where(test_df['card6'] == fix_val, np.nan, test_df['card6'])\n\n    # M columns\n    #################################################################################\n    for col in ['M1', 'M2', 'M3', 'M5', 'M6', 'M7', 'M8', 'M9']:\n        train_df[col] = train_df[col].map({'T': 1, 'F': 0})\n        test_df[col] = test_df[col].map({'T': 1, 'F': 0})\n\n    for col in ['M4']:\n        temp_df = pd.concat([train_df[[col]], test_df[[col]]])\n        col_encoded = temp_df[col].value_counts().to_dict()\n        train_df[col] = train_df[col].map(col_encoded)\n        test_df[col] = test_df[col].map(col_encoded)\n\n    # Identity columns\n    #################################################################################\n    def minify_identity_df(df):\n        df['id_12'] = df['id_12'].map({'Found': 1, 'NotFound': 0})\n        df['id_15'] = df['id_15'].map({'New': 2, 'Found': 1, 'Unknown': 0})\n        df['id_16'] = df['id_16'].map({'Found': 1, 'NotFound': 0})\n\n        df['id_23'] = df['id_23'].map({'TRANSPARENT': 4, 'IP_PROXY': 3, 'IP_PROXY:ANONYMOUS': 2, 'IP_PROXY:HIDDEN': 1})\n\n        df['id_27'] = df['id_27'].map({'Found': 1, 'NotFound': 0})\n        df['id_28'] = df['id_28'].map({'New': 2, 'Found': 1})\n\n        df['id_29'] = df['id_29'].map({'Found': 1, 'NotFound': 0})\n\n        df['id_35'] = df['id_35'].map({'T': 1, 'F': 0})\n        df['id_36'] = df['id_36'].map({'T': 1, 'F': 0})\n        df['id_37'] = df['id_37'].map({'T': 1, 'F': 0})\n        df['id_38'] = df['id_38'].map({'T': 1, 'F': 0})\n\n        df['id_34'] = df['id_34'].fillna(':0')\n        df['id_34'] = df['id_34'].apply(lambda x: x.split(':')[1]).astype(np.int8)\n        df['id_34'] = np.where(df['id_34'] == 0, np.nan, df['id_34'])\n\n        df['id_33'] = df['id_33'].fillna('0x0')\n        df['id_33_0'] = df['id_33'].apply(lambda x: x.split('x')[0]).astype(int)\n        df['id_33_1'] = df['id_33'].apply(lambda x: x.split('x')[1]).astype(int)\n        df['id_33'] = np.where(df['id_33'] == '0x0', np.nan, df['id_33'])\n\n        df['DeviceType'].map({'desktop': 1, 'mobile': 0})\n        return df\n\n    train_identity = minify_identity_df(train_identity)\n    test_identity = minify_identity_df(test_identity)\n\n    # Data sets minification\n    #################################################################################\n    for df in [train_df, test_df, train_identity, test_identity]:\n        original = df.copy()\n        df = helpers.reduce_mem_usage(df)\n\n        for col in list(df):\n            if df[col].dtype != 'O':\n                if (df[col] - original[col]).sum() != 0:\n                    df[col] = original[col]\n\n    # Export\n    #################################################################################\n    train_df.to_pickle(config['PROCESSED_PATH'] + 'train_transaction.pkl')\n    test_df.to_pickle(config['PROCESSED_PATH'] + 'test_transaction.pkl')\n\n    train_identity.to_pickle(config['PROCESSED_PATH'] + 'train_identity.pkl')\n    test_identity.to_pickle(config['PROCESSED_PATH'] + 'test_identity.pkl')\n","sub_path":"code/data/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}
+{"seq_id":"448561721","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep  5 16:25:18 2017\r\n\r\n@author: jyothsna\r\n\"\"\"\r\nfrom functools import reduce\r\na = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\r\nb = []\r\nn= int(input(\"enter a number\"))\r\n\r\nfor i in a:\r\n    if i  {tmp_dir}/{destination}\")\n            result = Host.scp(source, f\"{tmp_dir}/{destination}-{name}\", dryrun)\n\n        with open(path_expand(destination), 'a') as file:\n            for filename in glob(tmp_dir):\n                content = readfile(filename)\n                file.write(content)\n\n\n    @staticmethod\n    def scatter(user,\n                names,\n                source,\n                destinaton=\"~/.ssh/authorized_keys\",\n                dryrun=False):\n\n        if type(names) != list:\n            _names = Parameter.expand(names)\n\n        for name in _names:\n            directory = os.path.dirname(destination)\n            Host.ssh(f\"{user}@{name}\", f\"mkdir -p directory\", dryrun)\n\n            destination = f\"{user}@{name}:{destination}\"\n            print (f\"{source} -> {destination}\")\n            Host.scp(source, destination, dryrun)\n\n    # cat ~/.ssh/id_rsa.pub | ssh {user}@{ip} \"mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >>  ~/.ssh/authorized_keys\"\n\n    @staticmethod\n    def scp(source, destinations, output=\"lines\", dryrun=False):\n        \"\"\"\n\n        :param names:\n        :param command:\n        :param output:\n        :return:\n        \"\"\"\n\n        results = []\n        for destination in destinations:\n            command = (f\"scp  {source} {destination}\")\n            # result = command.format(name=name)\n\n            print(command)\n\n            if not dryrun:\n                result = Shell.run(command)\n\n                if output == \"lines\":\n                    lines = result.splitlines()\n                    results.append((destination, lines))\n                elif output == \"string\":\n                    results.append((destination, result))\n\n        return results\n\n    @staticmethod\n    def concatenate_keys(results):\n        result = \"\"\n        for entry in results:\n            name, key = entry\n            key = ''.join(key)\n            result += str(key) + '\\n'\n        result = result.strip()\n        return result\n\n    @staticmethod\n    def fix_keys_file(filename):\n        # concatenate ~/.ssh/id_rsa.pub\n        lines = readfile(filename)\n        key = readfile(path_expand(\"~/.ssh/id_rsa.pub\"))\n\n        authorized_keys = lines + key\n        keys = ''.join(authorized_keys)\n\n        # remove duplicates and empty lines\n        keys_list = [x for x in list(set(keys.splitlines())) if x != '\\n']\n        keys = ('\\n'.join(keys_list) + '\\n')\n\n        writefile(filename, str(keys))\n","sub_path":"cloudmesh/host/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"334625574","text":"from cpu_element import CPU_element\n\n\nclass Instruction_pointer(CPU_element):\n    def write_outputs(self):\n        input_name = self.input_names[0]\n        result = self.output_names[0]\n        self.outputs[result] = self.inputs[input_name]\n\n    def status(self):\n        \"\"\" Returns the current instruction address as a printable string.\"\"\"\n        address = self.outputs[self.output_names[0]]\n        outputs = [\"---Instruction pointer---\"]\n        outputs.append(\"Hex value: 0x{:08x}\".format(address))\n        outputs.append(\"Value: {}\".format(address))\n        return \"\\n\".join(outputs)\n\n\nclass Adder(CPU_element):\n    def write_outputs(self):\n        result = self.output_names[0]\n        self.outputs[result] = sum(self.inputs.values()) & 0xffffffff\n\n\nclass Mux(CPU_element):\n    def write_outputs(self):\n        control = self.inputs[self.input_names[0]]\n        result = self.output_names[0]\n        if control == 0:\n            self.outputs[result] = self.inputs[self.input_names[1]]\n        else:\n            self.outputs[result] = self.inputs[self.input_names[2]]\n\n\nclass Constant(CPU_element):\n    def __init__(self, output_name, value):\n        if not isinstance(value, int):\n            raise TypeError(\"value should be a int.\")\n        super().__init__([], [output_name])\n        self.value = value\n\n    def write_outputs(self):\n        result = self.output_names[0]\n        self.outputs[result] = self.value\n","sub_path":"src/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"381216756","text":"import csv\nimport os\nimport tarfile\nimport logging\nimport datetime\nimport sys\nimport shutil\nimport subprocess\nfrom collections import OrderedDict\n\nimport pyrob.common\nimport pyrob.loads.utils as lutils\n\nlog = logging.getLogger(__name__)\n\n\ndef extractfn(filename):\n    \"\"\"\n    A basic date/timestamp extraction routine used in the archive operator.\n\n    :param filename: the full path to the file name to extract from\n    :type filename: str\n    :returns: the datetime coalesced to year-month-day\n    :rtype: datetime.datetime\n    \"\"\"\n    return datetime.datetime.strptime(\n        os.path.basename(filename).split('.')[0][1:],\n        '%Y%m%d')\n\n\ndef _xml2csv(filename, staging_directory):\n    \"\"\"\n    Wrapper to call the legacy data-converter package for MME files.\n\n    This is a little hacky - copies the xml file to xml2 (so the legacy\n    data-converters file type matching logic can kick in) prior to conversion.\n\n    :param filename: the filename to convert\n    :type filename: str\n    :param staging_directory: the directory to stage/output the file to\n    :type staging_directory: str\n    :returns: a list of all resulting output files\n    :rtype: list\n    \"\"\"\n    files = []\n    file_basename = os.path.basename(filename)\n    convert = ['/usr/bin/python3',\n               '/opt/data-converters/xml2csv.py',\n               '--template',\n               'ericsson_mwave_oss_rc_v2',\n               '--csv', staging_directory, '--xml']\n    convert.append('{0}/{1}.xml2'.format(staging_directory, file_basename))\n    log.info(' '.join(convert))\n    try:\n        shutil.copy(filename,\n                    '{0}/{1}.xml2'.format(staging_directory, file_basename))\n        output = subprocess.check_output(convert)\n        for line in output.decode('utf-8').splitlines():\n            log.info(line)\n            if line.startswith('Written'):\n                files.append(line.split(' ')[-1])\n    finally:\n        os.remove('{0}/{1}.xml2'.format(staging_directory, file_basename))\n    return files\n\n\ndef stage_files(file_list, staging_directory):\n    \"\"\"\n    Wrapper to stage/convert a list of MME files.\n\n    :param file_list: a list of files to convert\n    :type filename: list\n    :param staging_directory: the directory to stage/output the file to\n    :type staging_directory: str\n    :returns: a list of all resulting output files\n    :rtype: list\n    \"\"\"\n    files = []\n    for filename in file_list:\n        files.extend(_xml2csv(filename, staging_directory))\n    return files\n","sub_path":"pyrob/loads/fixed_wireless/mme.py","file_name":"mme.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"119865525","text":"from __future__ import print_function\nimport argparse\nfrom experiment import *\n\n\nparser = argparse.ArgumentParser(description='VLAE')\nparser.add_argument('--checkpoint', type=str, default=None,\n                    help='path to the model checkpoint')\nparser.add_argument('--model', type=str, default='VAE',\n                    help='[VAE, VLAE, SAVAE, HF, IAF]')\nparser.add_argument('--dataset', type=str, default='MNIST',\n                    help='[SVHN, MNIST, OMNIGLOT, FashionMNIST, CIFAR10]')\nparser.add_argument('--logit_transform', type=bool, default=False,\n                    help='wheter to apply logit transform to data for \\\n                    continuous output distributions')\nparser.add_argument('--batch_size', type=int, default=128,\n                    help='input batch size for training (default: 128)')\nparser.add_argument('--n_epochs', type=int, default=2000,\n                    help='number of epochs to train')\nparser.add_argument('--seed', type=int, default=None,\n                    help='random seed')\nparser.add_argument('--log_interval', type=int, default=100,\n                    help='how many batches to wait before logging training status')\nparser.add_argument('--base_dir', type=str, default='./checkpoints/',\n                    help='(relative) base dir')\n\nparser.add_argument('--z_dim', type=int, default=50,\n                    help='latent space dimension')\nparser.add_argument('--output_dist', type=str, default='gaussian',\n                    help='One of [gaussian, bernoulli]')\nparser.add_argument('--hidden_dim', type=int, default=500,\n                    help='hidden unit dimension for encoder and decoder')\nparser.add_argument('--learning_rate', type=float, default=5e-4,\n                    help='Learning rate for ADAM optimizer')\nparser.add_argument('--weight_decay', type=float, default=0.0,\n                    help='L2 weight decay')\n\n# SAVAE parameters\nparser.add_argument('--svi_lr', type=float, default=5e-4,\n                    help='SVI lr. MNIST:0.1, CIFAR10:1e-3, ')\nparser.add_argument('--n_svi_step', type=int, default=4,\n                    help='SVI number of steps')\n\n# VLAE parameters\nparser.add_argument('--n_update', type=int, default=4,\n                    help='number of updates')\nparser.add_argument('--update_lr', type=float, default=0.5,\n                    help='update learning rate')\n\n# HouseholderFlow/IAF parameters\nparser.add_argument('--n_flow', type=int, default=4,\n                    help='number of householder flows to apply')\nparser.add_argument('--iaf_dim', type=int, default=500,\n                    help='dim for iaf layers')\n\nargs = parser.parse_args()\n\n\nif __name__ == \"__main__\":\n    exp = Experiment(model=args.model,\n                     dataset=args.dataset,\n                     logit_transform=args.logit_transform,\n                     batch_size=args.batch_size,\n                     n_epochs=args.n_epochs,\n                     log_interval=args.log_interval,\n                     z_dim=args.z_dim,\n                     output_dist=args.output_dist,\n                     hidden_dim=args.hidden_dim,\n                     learning_rate=args.learning_rate,\n                     svi_lr=args.svi_lr,\n                     n_svi_step=args.n_svi_step,\n                     n_update=args.n_update,\n                     update_lr=args.update_lr,\n                     n_flow=args.n_flow,\n                     seed=args.seed,\n                     base_dir=args.base_dir,\n                     iaf_dim=args.iaf_dim,\n                     weight_decay=args.weight_decay)\n\n    exp.importance_sample(args.checkpoint)\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"379772093","text":"r\"\"\"\n\nSummary\n-------\nThe CalSim Toolkit Python module is developed for in house querying,\nprocessing, and visualization of CalSim data from DSS files. Use of this module\nrequires the `usbr_py3dss.zip` python module.\n\nMain tasks\n----------\n1. Query\n2. Process\n3. Run\n4. Write\n5. Visualize\n\nExamples\n--------\nImporting the module.\n\n>>> import calsim_toolkit as cs\n\nExecute the following code to run a CalSim3 study with Python.\n\n>>> from calsim_toolkit.apps import run_CalSim\n>>> lf = 'CalSim3/Existing.launch'\n>>> run_CalSim.run_CalSim(lf)\n\nUse the variable dependency tool to understand linear program definitions in a\nCalSim study.\n\n>>> from calsim_toolkit.apps import variable_dependencies as vard\n>>> _ = vard.main('CalSim3', 'S_SHSTA')\n>>> run_CalSim.run_CalSim(lf)\nVariable Dependency Results for S_SHSTA in study diretory CalSim3...\n\nFuture Development\n------------------\nBelow are a list of tasks for future development:\n\n    1. Change plot styling to reflect Data-To-Ink ratio best practices [1_].\n    2. Directory reorganization.\n    3. Inclusion of `plotly` and `pyviz` in addition to`matplotlib`.\n    4. Add file configuration for connection to `usbr_py3dss`.\n    5. Add capability to read different data sources (e.g. DSS, SQLite).\n    6. Add `__init__.py`, `requirements.txt`, & `setup.py` to directory.\n    7. Refine \"Header\" meta-data for module.\n    8. Add option to see differences from baseline, where appropriate.\n    9. Updated PlotPD() to address depreciation warning.\n    10. Add error catching for y-axis range (Nan and Inf cases).\n    11. Add option to present table data with chart.\n    12. Modify library to incorporate \"pyviz\" environment workflow.\n    13. Modify pd.DataFrame specifications to allow for MultiIndex or single\n        level column index.\n    14. Incorporate terminology of \"tidy data\" and \"wide data.\"\n    15. Incorporate `drop_input` option for conversion between TAF and CFS.\n    16. Review capabilities of other unit variables (i.e. Not TAF or CFS).\n    17. Produce a table of exceedence plots where the values are replaced by\n        their respective time steps.\n    18. Separate module into query, process, and visualization tools.\n    19. Modify query tools to read from file as well as a list.\n    20. Create tool to convert DSS to SQLite (or any DB file via SQALalchemy?).\n    21. Should I rethink the name of this module?\n    22. Include data query from DSS into excel.\n\nReferences\n----------\nThe references listed below are formatted according to Chicago Manual of Style,\n16th Edition.\n\n.. [1] \"Customizing Matplotlib with Style Sheets and RcParams¶.\" Matplotlib:\n   Python Plotting - Matplotlib 2.2.3 Documentation. Accessed February 01,\n   2019. https://matplotlib.org/tutorials/introductory/customizing.html.\n\n.. [2] \"Plotly.\" Modern Visualization for the Data Era - Plotly. Accessed\n   February 01, 2019. https://plot.ly/matplotlib/.\n\n.. [3] \"Plotly.\" Modern Visualization for the Data Era - Plotly. Accessed\n   February 01, 2019. https://plot.ly/matplotlib/bar-charts/.\n\n\"\"\"\n# %% Import libraries.\n# Import standard libraries.\nimport os\nimport sys\nimport datetime as dt\n# Import third party libraries.\nimport dateutil.relativedelta as rd\nimport matplotlib.pyplot as plt\n# TODO: Created separate libraries for `matplotlib', `pyviz`, and `plotly`.\n# \nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import r2_score\n# Import module libraries.\nfrom .tools.io import *\nfrom .tools import plots, selection, transform, validation, variables\n# Import custom libraries.\nimport dss3_functions_reference as dss\n\n\n# %% Define functions.\ndef _run_CalSim_():\n    pass\n\n\n# %% Establish classes.\n# NOTE: For extending pandas DataFrames, see\n# https://pandas.pydata.org/pandas-docs/stable/development/extending.html\n# \n@pd.api.extensions.register_dataframe_accessor(\"cs\")\nclass CalSimAccessor(object):\n    def __init__(self, pandas_obj):\n        self._validate(pandas_obj)\n        self._obj = pandas_obj\n\n    @staticmethod\n    def _validate(obj):\n        if not (validation.is_tidy(obj) or validation.is_wide(obj)\n                or validation.is_condense(obj)):\n            validation.is_tidy(obj, verbose=True)\n            validation.is_wide(obj, verbose=True)\n            validation.is_condense(obj, verbose=True)\n            msg = 'DataFrame does not meet calsim_toolkit specifications.'\n            raise TypeError(msg)\n\n    @property\n    def no_property(self):\n        msg = 'This would return a property.'\n        return msg\n\n    def tidy(self, verbose=True, **kwargs):\n        # Initialize DataFrame.\n        df = self._obj.copy()\n        # Transform DataFrame, based on DataFrame type.\n        if validation.is_wide(df):\n            df = transform.wide_to_tidy(df)\n        elif validation.is_condense(df):\n            df = transform.condense_to_tidy(df, **kwargs)\n        elif validation.is_tidy(df):\n            msg = 'DataFrame is already in tidy format.'\n            if verbose: print(msg)\n        else:\n            msg = 'Unable to transform DataFrame to tidy data format.'\n            raise TypeError(msg)\n        # Return the transformed DataFrame.\n        return df\n\n    def wide(self, verbose=True, **kwargs):\n        # Initialize DataFrame.\n        df = self._obj.copy()\n        # Transform DataFrame, based on DataFrame type.\n        if validation.is_tidy(df):\n            df = transform.tidy_to_wide(df)\n        elif validation.is_condense(df):\n            df = transform.condense_to_tidy(df, **kwargs)\n            df = transform.tidy_to_wide(df)\n        elif validation.is_wide(df):\n            msg = 'DataFrame is already in wide format.'\n            if verbose: print(msg)\n        else:\n            msg = 'Unable to transform DataFrame to wide data format.'\n            raise TypeError(msg)\n        # Return the transformed DataFrame.\n        return df\n\n    def condense(self, verbose=True):\n        # Initialize DataFrame.\n        df = self._obj.copy()\n        # Transform DataFrame, based on DataFrame type.\n        if validation.is_tidy(df):\n            df = transform.tidy_to_condense(df)\n        elif validation.is_wide(df):\n            df = transform.wide_to_tidy(df)\n            df = transform.tidy_to_condense(df)\n        elif validation.is_condense(df):\n            msg = 'DataFrame is already in condense format.'\n            if verbose: print(msg)\n        else:\n            msg = 'Unable to transform DataFrame to wide data format.'\n            raise TypeError(msg)\n        # Return the transformed DataFrame.\n        return df\n\n    def compress(self, verbose=True):\n        pass\n\n    def to_dss(self, file_path, **kwargs):\n        # Initialize DataFrame.\n        df = self._obj.copy()\n        # Transform DataFrame to tidy format, if necessary.\n        df = df.cs.tidy(verbose=False, **kwargs)\n        # Write the DataFrame to a DSS file\n        write_dss(file_path, df)\n        # Return success indicator.\n        return 0\n\n    def to_excel():\n        pass\n\n    def plot(self, plot_type='', **kwargs):\n        # Initialize DataFrame.\n        df = self._obj.copy()\n        # Transform to wide format.\n        df = df.cs.wide(verbose=False)\n        # Initialize methods.\n        if plot_type:\n            plot_type = plot_type.upper()\n        else:\n            plot_type = 'TS'\n        plot_types = {'AA': plots.PlotAA,\n                      'EX': plots.PlotEX,\n                      'MA': plots.PlotMA,\n                      'SP': plots.PlotSP,\n                      'TS': plots.PlotTS}\n        # Obtain plot.\n        fig, ax = plot_types[plot_type](df, **kwargs)\n        # Return plot.\n        return fig, ax\n\n    def b(self, b, match=True):\n        # Initialize DataFrame.\n        df = self._obj.copy()\n        # Pass variables to selection function.\n        df_filtered = selection.PartB(df, b, match=match)\n        # Return filtered DataFrame.\n        return df_filtered\n\n    def wyt(self, indicator, idx='SACindex'):\n        # Initialize DataFrame and parameters.\n        df = self._obj.copy()\n        rtn_tidy = False\n        # Check DataFrame is in tidy format.\n        if validation.is_tidy(df):\n            rtn_tidy = True\n            df = df.cs.wide(verbose=False)\n        # Obtain water year type Series based on `idx`.\n        s_wyt = variables.water_year_types(idx)\n        # Transform index from years to annual February dates.\n        s_wyt.index = pd.to_datetime(s_wyt.index, format='%Y')\n        s_wyt = s_wyt.shift(2, freq='M')\n        # Reindex Series based on DataFrame Index.\n        s_wyt_dtype = s_wyt.dtype\n        s_date = s_wyt.index.min()\n        e_date = df.index.max()\n        new_idx = pd.date_range(start=s_date, end=e_date, freq='M')\n        s_wyt = s_wyt.reindex(new_idx)\n        s_wyt.fillna(method='ffill', inplace=True)\n        s_wyt = s_wyt.reindex(df.index).astype(s_wyt_dtype)\n        # Filter Series by provided `indicator`.\n        s_wyt = s_wyt.loc[s_wyt == indicator]\n        # Reindex DataFrame with filtered Series index.\n        df = df.reindex(s_wyt.index)\n        # Transform to tidy format, if applicable.\n        if rtn_tidy:\n            df = df.cs.tidy(verbose=False)\n        # Return DataFrame.\n        return df\n\n\n# %% Execute code.\n# Define attributes.\nplot_lib = 'matplotlib'\n# Prevent execution as __main__.\nif __name__ == '__main__':\n    msg = ('This module is intended to be imported for use into another'\n           ' module. It is not intended to be run as a __main__ file.')\n    raise RuntimeError(msg)\n","sub_path":"calsim_toolkit.py","file_name":"calsim_toolkit.py","file_ext":"py","file_size_in_byte":9486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"612617867","text":"from django.urls import path\nfrom app1 import views\n\napp_name = 'app1'\n\nurlpatterns = [\n    path('relative/', views.relative, name='relative'),\n    path('other/', views.other, name='other'),\n    path('register/', views.register, name=\"register\"),\n    path('index2/', views.index2, name='index2'),\n    ]\n\n    ","sub_path":"app1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}
+{"seq_id":"163634959","text":"import os\nimport subprocess\nimport sys\nimport time\nfrom pathlib import Path\nfrom threading import Thread, Timer\n\nfrom PySide2 import QtCore, QtGui, QtWidgets\nfrom PySide2.QtCore import QDir, QObject, QSize, Slot\nfrom PySide2.QtGui import QIcon, QImage, QImageReader, QPixmap, QTransform\nfrom PySide2.QtWidgets import (QApplication, QComboBox, QDialog,\n                               QDoubleSpinBox, QGridLayout, QGroupBox,\n                               QHBoxLayout, QInputDialog, QLabel, QLineEdit,\n                               QListWidget, QListWidgetItem, QMessageBox,\n                               QProgressBar, QPushButton, QRadioButton, QCheckBox,\n                               QSplashScreen, QVBoxLayout, QMenuBar, QMainWindow, QMenu, QAction)\n\nimport anim_player\nimport playtest\nimport settings\nfrom lj_input import LJInput\n\nclass MainWindow(QMainWindow):\n    def __init__(self, parent=None):\n        super(MainWindow, self).__init__()\n        self.cent = VisStimManager()\n        self.setCentralWidget(self.cent)\n        \n\nclass VisStimManager(QtWidgets.QWidget):\n    def __init__(self, parent=MainWindow):\n        super().__init__()\n\n        # Create layouts\n        layout = QVBoxLayout()\n\n        saveLoadLayout = QHBoxLayout()\n        GoLayout = QHBoxLayout()\n        GoSubLayout = QVBoxLayout()\n        NoGoLayout = QHBoxLayout()\n        NoGoSubLayout = QVBoxLayout()\n        TimingLayout = QVBoxLayout()\n\n        saveLoadBox = QGroupBox(\"Save this parameters or Load an old one\")\n        GoWithRadios = QGroupBox(\"Go Stimulus\")\n        NoGoWithGoRadios = QGroupBox(\"NoGo Stimulus\")\n        paramBox = QGroupBox(\"Timing parameters\")\n\n        # Define variables\n        # self.parametersToSave\n        self.GoPic = \"media\\\\squareVert.png\"\n        self.NoGoPic = \"media\\\\squareVert.png\"\n        self.GoArrow = \"media\\\\rightRedArrow.png\"\n        self.NoGoArrow = \"media\\\\rightRedArrow.png\"\n\n        # Create widgets\n        self.saveParametersButton = QPushButton(\"Save actual parameters\")\n        self.loadParametersButton = QPushButton(\"Load parameters\")\n        self.saveDialog = QInputDialog()\n        self.GoList = QComboBox()\n        self.NoGoList = QComboBox()\n        self.GoList.addItems(\n            [\"0°\", \"45°\", \"90°\", \"135°\", \"180°\", \"225°\", \"270°\", \"315°\"])\n        self.NoGoList.addItems(\n            [\"0°\", \"45°\", \"90°\", \"135°\", \"180°\", \"225°\", \"270°\", \"315°\"])\n        self.startButton = QPushButton(\"Start visual discrimination task\")\n        self.stopButton = QPushButton(\"Stop task\")\n        self.goRadioSin = QRadioButton(\"Sin\")\n        self.noGoRadioSin = QRadioButton(\"Sin\")\n        self.goRadioSquare = QRadioButton(\"Square\")\n        self.noGoRadioSquare = QRadioButton(\"Square\")\n        self.waitBeforeAnimation = QDoubleSpinBox()\n        self.firstAnimationLength = QDoubleSpinBox()\n        self.waitBetweenAnimations = QDoubleSpinBox()\n        self.secondAnimationLength = QDoubleSpinBox()\n        self.waitAfterAnimation = QDoubleSpinBox()\n        self.waitBeforeAnimationLabel = QLabel(\"Wait before animation\")\n        self.firstAnimationLengthLabel = QLabel(\"First animation length\")\n        self.waitBetweenAnimationsLabel = QLabel(\"Wait between animations\")\n        self.secondAnimationLengthLabel = QLabel(\"second animation length\")\n        self.waitAfterAnimationLabel = QLabel(\"Wait after second animation\")\n        self.goCurrentImage = QLabel()\n        self.goCurrentImage.setPixmap(\n            QPixmap(self.GoPic).scaled(50, 50, QtCore.Qt.KeepAspectRatio))\n        self.goArrowImage = QLabel()\n        self.goArrowImage.setPixmap(QPixmap(self.GoArrow).scaled(\n            50, 50, QtCore.Qt.KeepAspectRatio))\n        self.noGoArrowImage = QLabel()\n        self.noGoArrowImage.setPixmap(\n            QPixmap(self.NoGoArrow).scaled(50, 50, QtCore.Qt.KeepAspectRatio))\n        self.noGoCurrentImage = QLabel()\n        self.noGoCurrentImage.setPixmap(\n            QPixmap(self.NoGoPic).scaled(50, 50, QtCore.Qt.KeepAspectRatio))\n\n        self.testMode = QCheckBox(\"TestMode\", self)\n        \n        # Widget settings\n        self.goRadioSquare.setChecked(True)\n        self.noGoRadioSquare.setChecked(True)\n\n        self.waitBeforeAnimation.setSuffix(' sec')\n        self.firstAnimationLength.setSuffix(' sec')\n        self.waitBetweenAnimations.setSuffix(' sec')\n        self.secondAnimationLength.setSuffix(' sec')\n        self.waitAfterAnimation.setSuffix(' sec')\n\n        # Add widgets to Layouts\n        saveLoadLayout.addWidget(self.saveParametersButton)\n        saveLoadLayout.addWidget(self.loadParametersButton)\n        saveLoadBox.setLayout(saveLoadLayout)\n\n        GoLayout.addWidget(self.GoList)\n        GoLayout.addWidget(self.goRadioSquare)\n        GoLayout.addWidget(self.goRadioSin)\n        GoSubLayout.addWidget(self.goCurrentImage)\n        GoSubLayout.addWidget(self.goArrowImage)\n        GoLayout.addLayout(GoSubLayout)\n\n        NoGoLayout.addWidget(self.NoGoList)\n        NoGoLayout.addWidget(self.noGoRadioSquare)\n        NoGoLayout.addWidget(self.noGoRadioSin)\n        NoGoSubLayout.addWidget(self.noGoCurrentImage)\n        NoGoSubLayout.addWidget(self.noGoArrowImage)\n        NoGoLayout.addLayout(NoGoSubLayout)\n\n        TimingLayout.addWidget(self.waitBeforeAnimationLabel)\n        TimingLayout.addWidget(self.waitBeforeAnimation)\n        TimingLayout.addWidget(self.firstAnimationLengthLabel)\n        TimingLayout.addWidget(self.firstAnimationLength)\n        TimingLayout.addWidget(self.waitBetweenAnimationsLabel)\n        TimingLayout.addWidget(self.waitBetweenAnimations)\n        TimingLayout.addWidget(self.secondAnimationLengthLabel)\n        TimingLayout.addWidget(self.secondAnimationLength)\n        TimingLayout.addWidget(self.waitAfterAnimationLabel)\n        TimingLayout.addWidget(self.waitAfterAnimation)\n\n        # Set dialog layout\n        GoWithRadios.setLayout(GoLayout)\n        NoGoWithGoRadios.setLayout(NoGoLayout)\n        paramBox.setLayout(TimingLayout)\n        layout.addWidget(saveLoadBox)\n        layout.addWidget(GoWithRadios)\n        layout.addWidget(NoGoWithGoRadios)\n        layout.addWidget(paramBox)\n        layout.addWidget(self.testMode)\n        layout.addWidget(self.startButton)\n        layout.addWidget(self.stopButton)\n        self.setLayout(layout)\n\n        # Add Signals\n        self.saveParametersButton.clicked.connect(self.save)\n        self.loadParametersButton.clicked.connect(self.openLoadDialog)\n        self.startButton.clicked.connect(self.passdata)\n        self.stopButton.clicked.connect(self.close_stim)\n        self.GoList.currentTextChanged.connect(self.updateGoPic)\n        self.NoGoList.currentTextChanged.connect(self.updateNoGoPic)\n        self.goRadioSin.toggled.connect(self.updateGoPic)\n        self.goRadioSquare.toggled.connect(self.updateGoPic)\n        self.noGoRadioSin.toggled.connect(self.updateNoGoPic)\n        self.noGoRadioSquare.toggled.connect(self.updateNoGoPic)\n\n    @Slot()\n    def openLoadDialog(self):\n        self.loadDialog = LoadDialog()\n        self.loadDialog.show()\n\n    def save(self):\n        currentParameters = list()\n        listOfFiles = os.listdir(str(Path().absolute()) + \"\\\\sessionData\\\\\")\n        text = QInputDialog.getText(self, self.tr(\"Save parameters\"),\n                                    self.tr(\n                                        \"Please give mouse name:\"), QLineEdit.Normal,\n                                    self.tr(\"\"))\n        if text[1] == True and text[0] != '' and listOfFiles.count(text[0] + \".txt\") == 0:\n            currentParameters.append(text[0])\n\n            if self.goRadioSin.isChecked() == True:\n                goWtype = \"Sin\"\n            else:\n                goWtype = \"Square\"\n            currentParameters.append(goWtype)\n            currentParameters.append(self.GoList.currentText())\n            if self.noGoRadioSin.isChecked() == True:\n                noGoWtype = \"Sin\"\n            else:\n                noGoWtype = \"Square\"\n            currentParameters.append(noGoWtype)\n            currentParameters.append(self.NoGoList.currentText())\n\n            currentParameters.append(float(self.waitBeforeAnimation.value()))\n            currentParameters.append(float(self.firstAnimationLength.value()))\n            currentParameters.append(float(self.waitBetweenAnimations.value()))\n            currentParameters.append(float(self.secondAnimationLength.value()))\n            currentParameters.append(float(self.waitAfterAnimation.value()))\n\n            fh = open(str(Path().absolute()) +\n                      \"\\\\sessionData\\\\\" + text[0] + \".txt\", \"w\")\n            fh.write(str(currentParameters)[1:-1])\n            fh.write(\"\\n\")\n            fh.close\n\n        elif text[1] == True and text[0] == '':\n            nameNullError = QMessageBox().warning(self, self.tr(\n                \"Error\"), self.tr(\"Name cannot be empty!\"), QMessageBox.Cancel)\n            if nameNullError == QMessageBox.Cancel:\n                self.save()\n        elif text[1] == True and listOfFiles.count(text[0] + \".txt\") > 0:\n            alreadyExistsError = QMessageBox().warning(self, self.tr(\n                \"Error\"), self.tr(\"This name already exists!\"), QMessageBox.Cancel)\n            if alreadyExistsError == QMessageBox.Cancel:\n                self.save()\n\n    def updateGoPic(self):\n\n        if self.goRadioSin.isChecked() == True:\n            goWtype = \"Sin\"\n        else:\n            goWtype = \"Square\"\n\n        if (int(self.GoList.currentText()[:-1]) == 0):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"Vert.png\"\n            self.GoArrow = \"media\\\\rightRedArrow.png\"\n        elif (int(self.GoList.currentText()[:-1]) == 45):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"Diag.png\"\n            self.GoArrow = \"media\\\\rightRedArrow.png\"\n        elif (int(self.GoList.currentText()[:-1]) == 225):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"Diag.png\"\n            self.GoArrow = \"media\\\\leftRedArrow.png\"\n        elif (int(self.GoList.currentText()[:-1]) == 135):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"InvDiag.png\"\n            self.GoArrow = \"media\\\\leftRedArrow.png\"\n        elif (int(self.GoList.currentText()[:-1]) == 180):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"Vert.png\"\n            self.GoArrow = \"media\\\\leftRedArrow.png\"\n        elif (int(self.GoList.currentText()[:-1]) == 90):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"Horiz.png\"\n            self.GoArrow = \"media\\\\downRedArrow.png\"\n        elif (int(self.GoList.currentText()[:-1]) == 270):\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"Horiz.png\"\n            self.GoArrow = \"media\\\\upRedArrow.png\"\n        else:\n            self.GoPic = \"media\\\\\" + goWtype.lower() + \"InvDiag.png\"\n            self.GoArrow = \"media\\\\rightRedArrow.png\"\n        self.goCurrentImage.setPixmap(\n            QPixmap(self.GoPic).scaled(50, 50, QtCore.Qt.KeepAspectRatio))\n        self.goArrowImage.setPixmap(QPixmap(self.GoArrow).scaled(\n            50, 50, QtCore.Qt.KeepAspectRatio))\n\n    def updateNoGoPic(self):\n\n        if self.noGoRadioSin.isChecked() == True:\n            noGoWtype = \"Sin\"\n        else:\n            noGoWtype = \"Square\"\n\n        if (int(self.NoGoList.currentText()[:-1]) == 0):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"Vert.png\"\n            self.NoGoArrow = \"media\\\\rightRedArrow.png\"\n        elif (int(self.NoGoList.currentText()[:-1]) == 45):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"Diag.png\"\n            self.NoGoArrow = \"media\\\\rightRedArrow.png\"\n        elif (int(self.NoGoList.currentText()[:-1]) == 225):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"Diag.png\"\n            self.NoGoArrow = \"media\\\\leftRedArrow.png\"\n        elif (int(self.NoGoList.currentText()[:-1]) == 135):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"InvDiag.png\"\n            self.NoGoArrow = \"media\\\\leftRedArrow.png\"\n        elif (int(self.NoGoList.currentText()[:-1]) == 180):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"Vert.png\"\n            self.NoGoArrow = \"media\\\\leftRedArrow.png\"\n        elif (int(self.NoGoList.currentText()[:-1]) == 90):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"Horiz.png\"\n            self.NoGoArrow = \"media\\\\downRedArrow.png\"\n        elif (int(self.NoGoList.currentText()[:-1]) == 270):\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"Horiz.png\"\n            self.NoGoArrow = \"media\\\\upRedArrow.png\"\n        else:\n            self.NoGoPic = \"media\\\\\" + noGoWtype.lower() + \"InvDiag.png\"\n            self.NoGoArrow = \"media\\\\rightRedArrow.png\"\n        self.noGoCurrentImage.setPixmap(\n            QPixmap(self.NoGoPic).scaled(50, 50, QtCore.Qt.KeepAspectRatio))\n        self.noGoArrowImage.setPixmap(\n            QPixmap(self.NoGoArrow).scaled(50, 50, QtCore.Qt.KeepAspectRatio))\n\n    def close_stim(self):\n        anim_player.closeByGui()\n\n    def passdata(self):\n        # Passes data set to anim_player and start the task\n        # globvar: [Gostimfilename, Nogostimfilename, waitBeforeAnimation\n        #          firstAnimationLength, waitBetweenAnimations, secondAnimationLength, waitAfterAnimation]\n\n        if self.goRadioSin.isChecked() == True:\n            goWtype = \"Sin\"\n        else:\n            goWtype = \"Square\"\n        settings.globvar.append(\n            goWtype + self.GoList.currentText()[:-1] + \".ani\")\n        if self.noGoRadioSin.isChecked() == True:\n            noGoWtype = \"Sin\"\n        else:\n            noGoWtype = \"Square\"\n        settings.globvar.append(\n            noGoWtype + self.NoGoList.currentText()[:-1] + \".ani\")\n\n        settings.globvar.append(float(self.waitBeforeAnimation.value()))\n        settings.globvar.append(float(self.firstAnimationLength.value()))\n        settings.globvar.append(float(self.waitBetweenAnimations.value()))\n        settings.globvar.append(float(self.secondAnimationLength.value()))\n        settings.globvar.append(float(self.waitAfterAnimation.value()))\n\n        if (int(self.GoList.currentText()[:-1]) == 0 or int(self.GoList.currentText()[:-1]) == 180):\n            settings.globvar.append(goWtype.lower() + \"Vert.png\")\n        elif (int(self.GoList.currentText()[:-1]) == 45 or int(self.GoList.currentText()[:-1]) == 225):\n            settings.globvar.append(goWtype.lower() + \"Diag.png\")\n        elif (int(self.GoList.currentText()[:-1]) == 90 or int(self.GoList.currentText()[:-1]) == 270):\n            settings.globvar.append(goWtype.lower() + \"Horiz.png\")\n        else:\n            settings.globvar.append(goWtype.lower() + \"InvDiag.png\")\n\n        if (int(self.NoGoList.currentText()[:-1]) == 0 or int(self.NoGoList.currentText()[:-1]) == 180):\n            settings.globvar.append(noGoWtype.lower() + \"Vert.png\")\n        elif (int(self.NoGoList.currentText()[:-1]) == 45 or int(self.NoGoList.currentText()[:-1]) == 225):\n            settings.globvar.append(noGoWtype.lower() + \"Diag.png\")\n        elif (int(self.NoGoList.currentText()[:-1]) == 90 or int(self.NoGoList.currentText()[:-1]) == 270):\n            settings.globvar.append(noGoWtype.lower() + \"Horiz.png\")\n        else:\n            settings.globvar.append(noGoWtype.lower() + \"InvDiag.png\")\n\n        # print(settings.globvar)\n        if (self.testMode.isChecked()):\n            playtest.run()\n        else:\n            anim_player.run()\n\nclass LoadDialog(QtWidgets.QDialog):\n    def __init__(self, parent=None):\n        super().__init__()\n\n        def fillList(self):\n            listOfFiles = os.listdir(\n                str(Path().absolute()) + \"\\\\sessionData\\\\\")\n            for i in range(len(listOfFiles)):\n                QListWidgetItem(listOfFiles[i][:-4], self.chooseBox)\n\n        # Create Layouts\n        loadLayout = QVBoxLayout()\n        buttonLayout = QHBoxLayout()\n\n        # Create Widgets\n        self.chooseBox = QListWidget()\n        self.loadButton = QPushButton(\"Load\")\n        self.deleteButton = QPushButton(\"Delete\")\n        self.cancelButton = QPushButton(\"Cancel\")\n\n        # Configure widgets\n        self.chooseBox.setSortingEnabled(True)\n\n        # Configure Layouts\n        loadLayout.addWidget(self.chooseBox)\n        loadLayout.addWidget(self.loadButton)\n        buttonLayout.addWidget(self.deleteButton)\n        buttonLayout.addWidget(self.cancelButton)\n        loadLayout.addLayout(buttonLayout)\n\n        self.setLayout(loadLayout)\n        fillList(self)\n\n        # Sgnals\n        self.cancelButton.clicked.connect(self.onClose)\n        self.loadButton.clicked.connect(self.onLoad)\n        self.deleteButton.clicked.connect(self.onDelete)\n\n    @Slot()\n    def onClose(self):\n        self.close()\n\n    def onDelete(self):\n        deleteMsg = QMessageBox.warning(self, self.tr(\"Delete\"), self.tr(\n            \"Are you sure?\\n\" + \"This will delete the file that belongs to this mouse.\"), QMessageBox.Yes | QMessageBox.Cancel)\n\n        if deleteMsg == QMessageBox.Yes:\n            os.remove(str(Path().absolute()) + \"\\\\sessionData\\\\\" +\n                      self.chooseBox.currentItem().text() + \".txt\")\n            self.chooseBox.takeItem(self.chooseBox.currentRow())\n\n    def onLoad(self):\n\n        # print(self.chooseBox.currentItem().text())\n        with open(str(Path().absolute()) + \"\\\\sessionData\\\\\" + self.chooseBox.currentItem().text() + \".txt\") as openfileobject:\n            settingsLine = openfileobject.readline().split(', ')\n\n            lineInList = list()\n            lineInList.append(settingsLine[0][1:-1])\n            lineInList.append(settingsLine[1][1:-1])\n            lineInList.append(settingsLine[2][1:-1])\n            lineInList.append(settingsLine[3][1:-1])\n            lineInList.append(settingsLine[4][1:-1])\n            lineInList.append(settingsLine[5])\n            lineInList.append(settingsLine[6])\n            lineInList.append(settingsLine[7])\n            lineInList.append(settingsLine[8])\n            lineInList.append(settingsLine[9])\n\n        if (lineInList[1] == \"Sin\"):\n            window.goRadioSin.setChecked(True)\n        else:\n            window.goRadioSquare.setChecked(True)\n\n        window.GoList.setCurrentText(lineInList[2])\n\n        if (lineInList[3] == \"Sin\"):\n            window.noGoRadioSin.setChecked(True)\n        else:\n            window.noGoRadioSquare.setChecked(True)\n\n        window.NoGoList.setCurrentText(lineInList[4])\n\n        window.waitBeforeAnimation.setValue(float(lineInList[5]))\n        window.firstAnimationLength.setValue(float(lineInList[6]))\n        window.waitBetweenAnimations.setValue(float(lineInList[7]))\n        window.secondAnimationLength.setValue(float(lineInList[8]))\n        window.waitAfterAnimation.setValue(float(lineInList[9]))\n        self.close()\n\n\nif __name__ == '__main__':\n    app = QtWidgets.QApplication([])\n    splashimg = QPixmap(\"media\\\\splash.jpg\")\n    splash = QSplashScreen(splashimg)\n    progressBar = QProgressBar(splash)\n    progressBar.setMaximum(10)\n    progressBar.setGeometry(0, splashimg.height() - 15, splashimg.width(), 15)\n    splash.show()\n    splash.showMessage(\"

Femto VisStimManager

\")\n\n for i in range(1, 11):\n progressBar.setValue(i)\n t = time.time()\n while time.time() < t + 0.1:\n app.processEvents()\n\n time.sleep(1)\n\n # Create the Qt Application\n settings.init()\n window = MainWindow()\n window.setWindowIcon(QIcon(\"icon.ico\"))\n\n # Create and show the form\n window.setWindowTitle(\"VisStimManager\")\n window.resize(250, 150)\n window.show()\n splash.finish(window)\n\n # Run the main Qt loop\n sys.exit(app.exec_())\n","sub_path":"VisStimManager.py","file_name":"VisStimManager.py","file_ext":"py","file_size_in_byte":19570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"510873900","text":"from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom . import views\n\napp_name = 'browsing'\n\nurlpatterns = [\n url(r'archivaltnames/$', views.AltNameListView.as_view(), name='browse_archivaltnames'),\n url(r'places/$', views.PlaceListView.as_view(), name='browse_places'),\n url(r'places-rdf/$', views.PlaceRDFView.as_view(), name='rdf_places'),\n url(r'altnames/$', views.AlternativeNameListView.as_view(), name='browse_altnames'),\n url(r'persons/$', views.PersonListView.as_view(), name='browse_persons'),\n url(r'persons-rdf/$', views.PersonRDFView.as_view(), name='rdf_persons'),\n url(r'institutions/$', views.InstitutionListView.as_view(), name='browse_institutions'),\n url(r'institutions-rdf/$', views.InstitutionRDFView.as_view(), name='rdf_institutions'),\n url(r'periods/$', views.PeriodListView.as_view(), name='browse_periods'),\n url(r'researchevents/$', views.ResearchEventListView.as_view(), name='browse_researchevents'),\n url(r'download/researchevent/$', views.ResearchEventDl.as_view(), name='dl_researchevent'),\n url(\n r'researchquestions/$', views.ResearchQuestionListView.as_view(),\n name='browse_researchquestions'\n ),\n url(r'sites/$', views.SiteListView.as_view(), name='browse_sites'),\n url(r'download/site/$', views.SiteDl.as_view(), name='dl_sites'),\n url(r'archents/$', views.ArchEntListView.as_view(), name='browse_archents'),\n url(r'download/archent/$', views.ArchEntDl.as_view(), name='dl_archent'),\n url(\n r'monumentprotections/$', views.MonumentProtectionListView.as_view(),\n name='browse_monumentprotections'\n ),\n url(\n r'download/monumentprotection/$',\n views.MonumentProtectionDl.as_view(),\n name='dl_monumentprotection'\n ),\n url(\n r'references/$', views.ReferenceListView.as_view(),\n name='browse_references'\n ),\n url(r'map/$', views.MapView.as_view(), name='map'),\n]\n","sub_path":"browsing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"505209203","text":"'''\n生产者-消费者\n'''\n\nimport threading\nimport time\n\n# python2\n#from Queue import Queue\n\n# ptyhon3\nimport queue\n\n# 继承threading.Thread\nclass Producer(threading.Thread):\n # 重写 run 方法\n def run(self):\n global queue\n count = 0\n while True:\n # qsize 返回 queue 内容长度\n if queue.qsize() < 1000:\n for i in range(1000):\n count +=1\n msg = \"生成产品\" + str(count)\n # put 向 queue 中放入一个值\n queue.put(msg)\n print(msg)\n time.sleep(0.5)\n\n\nclass Consumer(threading.Thread):\n def run(self):\n global queue\n while True:\n if queue.qsize() > 100:\n for i in range(3):\n # get 从 queue 中取出一个值\n msg = self.name + \"消费了\" + queue.get()\n print(msg)\n time.sleep(1)\n\nif __name__ == '__main__':\n queue = queue.Queue()\n\n for i in range(500):\n queue.put(\"初始产品\"+str(i))\n # 两个生产者\n for i in range(2):\n p = Producer()\n p.start()\n # 五个消费者\n for i in range(5):\n c = Consumer()\n c.start()","sub_path":"09-多线程/case1.py","file_name":"case1.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"106096659","text":"#!/usr/bin/python3\nimport importlib\nimport io\nimport math\nimport os\nimport sys\nimport zipfile\n\nimport car\nimport student\n\n\ndef main(args):\n sys.path.append(args[1])\n deductions = 0\n try:\n deductions += grade_q1()\n except Exception as e:\n print('Exception occurred grading Question 1', e)\n\n print('****\\n')\n try:\n deductions += grade_q2()\n except Exception as e:\n print('Exception occurred grading Question 2', e)\n\n print('****\\n')\n try:\n deductions += grade_q3()\n except Exception as e:\n print('Exception occurred grading Question 3', e)\n \n print('****\\n')\n try:\n deductions += grade_q4()\n except Exception as e:\n print('Exception occurred grading Question 4', e) \n\n print('Score: %i of 100' % (100 + deductions))\n \n\ndef grade_q1():\n print('-- Grading Question 1 --')\n deductions = 0\n car.Car.clear_calls()\n\n try:\n q1_main = importlib.import_module('q1_main')\n\n # Constructor\n for c in (\n {'args': ('Ford', 'F-150', 2010, 15999.99), 'method': '__init__'},\n {'args': ('Jeep', 'Wrangler', 2001, 7500.99), 'method': '__init__'},\n {'args': ('Honda', 'Accord', 2016, 31299.00), 'method': '__init__'},\n {'args': ('Chevrolet', 'Corvette', 1969, 89950.79), \n 'method': '__init__'}):\n try:\n assert c in car.Car.CALLS\n except:\n deductions -= 1\n print('-1: %s not found in calls' % c)\n\n # 4 calls to __str__\n calls = 0\n for c in car.Car.CALLS:\n if c['method'] == '__str__':\n calls += 1\n try:\n assert calls == 4\n except:\n deductions -= abs(4 - calls)\n print('-%i: %i calls to __str__' % (4 - calls, calls))\n\n # Calls to set_price\n call = {'method': 'set_price', 'args': (7500.99 * 0.9,)}\n try:\n assert call in car.Car.CALLS\n except:\n deductions -= 2\n print('-2: set_price not called correctly for Jeep Wrangler')\n call = {'method': 'set_price', 'args': (89950.79 * 0.9,)}\n try:\n assert call in car.Car.CALLS\n except:\n deductions -= 2\n print('-2: set_price not called correctly for Chevrolet Corvette')\n\n # Calls to set_quantity\n call = {'method': 'set_year', 'args': (2002,)}\n try:\n assert call in car.Car.CALLS\n except:\n deductions -= 5\n print('-2: set_quantity not called correctly for Jeep Wrangler')\n except Exception as e:\n deductions -= 20\n print('-20: q1_main.py does not run', e)\n\n return deductions\n\n\ndef grade_q2():\n print('-- Grading Question 2 --')\n deductions = 0\n try:\n q2_device = importlib.import_module('q2_device')\n\n # Presence of methods\n for m in ('__init__', '__str__', 'get_device_type', 'get_memory',\n 'get_screen_size', 'set_device_type', 'set_memory',\n 'set_screen_size'):\n try:\n assert (hasattr(q2_device.Device, m) and\n callable(getattr(q2_device.Device, m)))\n except:\n deductions -= 1\n print('-1: Method %s not available' % m)\n\n # Build an object\n try:\n d = q2_device.Device('PC', 8, 5.5)\n except Exception as e:\n deductions -= 3\n print('-3: Device cannot be created', e)\n\n # __str__\n try:\n assert 'PC has 8 GB of memory and its screen is 5.5 inches' in str(d)\n except:\n deductions -= 2\n print('-2: __str__() return value \"%s\" is incorrect' % str(d))\n\n # Getters\n try:\n assert d.get_device_type() == 'PC'\n except:\n deductions -= 1\n print('-1: get_device_type() return value \"%s\" is incorrect' %\n d.get_device_type())\n try:\n assert d.get_memory() == 8\n except:\n deductions -= 1\n print('-1: get_memory() return value is \"%s\" incorrect' % d.get_memory())\n try:\n assert d.get_screen_size() == 5.5\n except:\n deductions -= 1\n print('-1: get_screen_size() return value is \"%s\" incorrect' %\n d.get_screen_size())\n\n # Setters\n try:\n d.set_device_type('PC1')\n assert d.get_device_type() == 'PC1'\n except:\n deductions -= 1\n print('-1: set_device_type() does not work correctly')\n try:\n d.set_memory(0)\n assert d.get_memory() == 1\n d.set_memory(24)\n assert d.get_memory() == 16\n except:\n deductions -= 1\n print('-1: set_memory() does not work correctly')\n try:\n d.set_screen_size(10.0)\n assert d.get_screen_size() == 10.0\n except:\n deductions -= 1\n print('-1: set_screen_size() does not work correctly')\n except Exception as e:\n deductions -= 20\n print('-20: q2_device.py cannot be imported', e)\n\n return deductions\n\n\ndef grade_q3():\n print('-- Grading Question 3 --')\n deductions = 0\n try:\n q3_credit_card = importlib.import_module('q3_credit_card')\n\n # Presence of methods\n for m in ('__init__', '__str__', 'get_card_type', 'get_card_holder',\n 'get_interest_rate', 'get_balance', 'set_card_holder',\n 'set_interest_rate'):\n try:\n assert (hasattr(q3_credit_card.CreditCard, m) and\n callable(getattr(q3_credit_card.CreditCard, m)))\n except:\n deductions -= 1\n print('-1: Method %s not available' % m)\n\n # Build an object\n try:\n cc = q3_credit_card.CreditCard('Discover', 'Sally Student', 0.0675)\n except Exception as e:\n deductions -= 3\n print('-3: CreditCard cannot be created', e)\n\n # __str__\n try:\n responses = [\n (\"Sally Student's Discover card has an interest rate of 6.75% \"\n \"and a balance of $0.00\"),\n (\"Sally Student's Discover card has an interest rate of 7% \"\n \"and a balance of $0.00\"),\n (\"Sally Student's Discover card has an interest rate of 6.75% \"\n \"and a balance of $0.00.\"),\n (\"Sally Student's Discover card has an interest rate of 7% \"\n \"and a balance of $0.00.\")\n ]\n assert str(cc) in responses\n except:\n deductions -= 2\n print('-2: __str__() return value \"%s\" is incorrect' % str(cc))\n\n # Getters\n try:\n assert cc.get_card_type() == 'Discover'\n except:\n deductions -= 1\n print('-1: get_card_type() return value \"%s\" is incorrect' %\n cc.get_card_type())\n try:\n assert cc.get_card_holder() == 'Sally Student'\n except:\n deductions -= 1\n print('-1: get_card_holder() return value \"%s\" is incorrect' %\n cc.get_card_holder())\n try:\n assert cc.get_interest_rate() == 0.0675\n except:\n deductions -= 1\n print('-1: get_interest_rate() return value \"%s\" is incorrect' %\n cc.get_interest_rate())\n try:\n assert cc.get_balance() == 0.0\n except:\n deductions -= 1\n print('-1: get_balance() return value \"%s\" is incorrect' %\n cc.get_balance())\n\n # Setters\n try:\n cc.set_card_holder('Billy Jean')\n assert cc.get_card_holder() == 'Billy Jean'\n except:\n deductions -= 1\n print('-1: set_card_holder() does not work correctly')\n try:\n cc.set_interest_rate(0.1)\n assert cc.get_interest_rate() == 0.1\n except:\n deductions -= 1\n print('-1: set_interest_rate() does not work correctly')\n\n # charge\n try:\n cc.charge(100)\n assert cc.get_balance() == 100.0\n cc.charge(-10)\n assert cc.get_balance() == 100.0\n except:\n deductions -= 3\n print('-3: charge() does not work correctly')\n\n # bill\n try:\n old_print = __builtins__.print\n print_output = []\n def new_print(output):\n print_output.append(output)\n __builtins__.print = new_print\n cc.bill()\n __builtins__.print = old_print\n assert print_output[0] == 'Please pay $110.00'\n except:\n __builtins__.print = old_print\n deductions -= 3\n output = '' \n if print_output:\n output = print_output[0]\n print('-3: bill() output \"%s\" is incorrect' % output)\n\n except Exception as e:\n deductions -= 20\n print('-20: q3_credit_card.py cannot be imported', e)\n\n return deductions\n\n\ndef grade_q4():\n print('-- Grading Question 4 --')\n deductions = 0\n \n # Replace references to Building with building.Building\n with open('q4_graduate_student.py') as f:\n source = f.read() \n with open('q4_graduate_student.py', 'w') as f:\n if 'import student' not in source:\n source = 'import student\\n\\n' + source.replace(\n 'Student', 'student.Student')\n f.write(source)\n \n # Try to import the q4_graduate_student module in various ways before failing \n try: \n q4_graduate_student = importlib.import_module('q4_graduate_student')\n\n # Presence of methods\n for m in ('__init__', '__str__', 'get_thesis_title', 'get_advisor'):\n try:\n assert (hasattr(q4_graduate_student.GraduateStudent, m) and\n callable(getattr(q4_graduate_student.GraduateStudent, m)))\n except:\n deductions -= 1\n print('-1: Method %s not available' % m)\n\n # Build an object\n try:\n h = q4_graduate_student.GraduateStudent('John Doe', 2018, 'CS', \n 'Really Confusing Research on Hard Stuff', 'Mary Poppins')\n except Exception as e:\n deductions -= 7\n print('-7: GraduateStudent cannot be created', e)\n\n # Inherit from Student\n try:\n assert isinstance(h, student.Student)\n except Exception as e:\n deductions -= 5\n print('-5: GraduateStudent does not inherit from Student', e)\n\n # __str__\n try:\n response = (\n 'John Doe will graduate in 2018 with a degree in CS is advised by '\n 'Mary Poppins and is researching Really Confusing Research on Hard '\n 'Stuff')\n assert response == str(h)\n except:\n deductions -= 2\n print('-2: __str__() return value \"%s\" is incorrect' % str(h))\n\n # Getters\n try:\n assert h.get_thesis_title() == 'Really Confusing Research on Hard Stuff'\n except:\n deductions -= 2\n print('-2: get_thesis_title() return value \"%s\" is incorrect' %\n h.get_thesis_title())\n try:\n assert h.get_advisor() == 'Mary Poppins'\n except:\n deductions -= 2\n print('-2: get_advisor() return value \"%s\" is incorrect' %\n h.get_advisor())\n\n except Exception as e:\n deductions -= 20\n print('-20: q4_graduate_student.py cannot be imported', e)\n\n return deductions\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"exam3/grader.py","file_name":"grader.py","file_ext":"py","file_size_in_byte":10347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174667597","text":"import airsim\nimport argparse\nfrom flyDroneService import FlyDroneService\nimport time\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-u', '--level', help='Game Level', type=int, default=1)\n args = parser.parse_args()\n \n # connect to the AirSim simulator\n client = airsim.MultirotorClient()\n FlyDroneService.initializeAirSimClient(client)\n\n gameLevel = args.level\n print(gameLevel)\n # set the coordinates to set up the path for drone to travel\n if gameLevel == 3:\n print('Level 3')\n client.simEnableWeather(True)\n FlyDroneService.setFlyingCoordsForDroneAtThirdLevel(client)\n elif gameLevel == 2:\n print('Level 2')\n client.simEnableWeather(True)\n FlyDroneService.setFlyingCoordsForDroneAtSecondLevel(client)\n else:\n print('Level 1')\n client.simEnableWeather(True)\n client.simSetWeatherParameter(airsim.WeatherParameter.Rain, 1)\n FlyDroneService.setFlyingCoordsForDroneAtFirstLevel(client)\n \n #stop and return the simulator to initial state\n FlyDroneService.resetAirSimClient(client)\n\n","sub_path":"Redis_Airsim/airsim/flyDrone.py","file_name":"flyDrone.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"513533011","text":"#!/usr/bin/env python\n# -*- encoding: utf8 -*-\n\"\"\"\nCentral interfaces for ``Pyadjoint``.\n\n:copyright:\n Lion Krischer (krischer@geophysik.uni-muenchen.de), 2015\n:license:\n BSD 3-Clause (\"BSD New\" or \"BSD Simplified\")\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport inspect\nimport matplotlib.pylab as plt\nimport numpy as np\nimport obspy\nimport os\nimport pkgutil\nimport warnings\n\nfrom . import PyadjointError, PyadjointWarning\n\n\nclass AdjointSource(object):\n # Dictionary of available adjoint source. The key is the name, the value\n # a tuple of function, verbose name, and description.\n _ad_srcs = {}\n\n def __init__(self, adj_src_type, misfit, dt, min_period, max_period,\n component, adjoint_source=None, network=None, station=None,\n location=None, starttime=None):\n \"\"\"\n Class representing an already calculated adjoint source.\n\n :param adj_src_type: The type of adjoint source.\n :type adj_src_type: str\n :param misfit: The misfit value.\n :type misfit: float\n :param dt: The sampling rate of the adjoint source.\n :type dt: float\n :param min_period: The minimum period of the spectral content\n of the data.\n :type min_period: float\n :param max_period: The maximum period of the spectral content\n of the data.\n :type max_period: float\n :param component: The adjoint source component, usually ``\"Z\"``,\n ``\"N\"``, ``\"E\"``, ``\"R\"``, or ``\"T\"``.\n :type component: str\n :param adjoint_source: The actual adjoint source.\n :type adjoint_source: :class:`numpy.ndarray`\n :param network: The network code of the station.\n :type network: str\n :param station: The station code of the station.\n :type station: str\n :param location: The location code of the station.\n :type location: str\n :param starttime: starttime of adjoint source\n :type starttime: obspy.UTCDateTime\n \"\"\"\n if adj_src_type not in self._ad_srcs:\n raise ValueError(\"Unknown adjoint source type '%s'.\" %\n adj_src_type)\n self.adj_src_type = adj_src_type\n self.adj_src_name = self._ad_srcs[adj_src_type][1]\n self.misfit = misfit\n self.dt = dt\n self.min_period = min_period\n self.max_period = max_period\n self.component = component\n self.network = network\n self.station = station\n self.location = location\n self.starttime = starttime\n self.adjoint_source = adjoint_source\n\n def __str__(self):\n if self.network and self.station:\n station = \" at station %s.%s\" % (self.network, self.station)\n else:\n station = \"\"\n\n if self.adjoint_source is not None:\n adj_src_status = \"available with %i samples\" % (len(\n self.adjoint_source))\n else:\n adj_src_status = \"has not been calculated\"\n\n return (\n \"{name} Adjoint Source for component {component}{station}\\n\"\n \" Misfit: {misfit:.4g}\\n\"\n \" Adjoint source {adj_src_status}\"\n ).format(\n name=self.adj_src_name,\n component=self.component,\n station=station,\n misfit=self.misfit,\n adj_src_status=adj_src_status\n )\n\n def write(self, filename, format, **kwargs):\n \"\"\"\n Write the adjoint source to a file.\n\n :param filename: Determines where the adjoint source is saved.\n :type filename: str, open file, or file-like object\n :param format: The format of the adjoint source. Currently available\n are: ``\"SPECFEM\"``\n :type format: str\n\n .. rubric:: SPECFEM\n\n SPECFEM requires one additional parameter: the temporal offset of the\n first sample in seconds. The following example sets the time of the\n first sample in the adjoint source to ``-10``.\n\n >>> adj_src.write(\"NET.STA.CHAN.adj\", format=\"SPECFEM\",\n ... time_offset=-10) # doctest: +SKIP\n \"\"\"\n if self.adjoint_source is None:\n raise ValueError(\"Can only write adjoint sources if the adjoint \"\n \"source has been calculated.\")\n\n format = format.upper()\n available_formats = [\"SPECFEM\"]\n if format not in available_formats:\n raise ValueError(\"format '%s' not known. Available formats: %s\" %\n (format, \", \".join(available_formats)))\n\n if not hasattr(filename, \"write\"):\n with open(filename, \"wb\") as fh:\n self._write(fh, format=format, **kwargs)\n else:\n self._write(filename, format=format, **kwargs)\n\n def _write(self, buf, format, **kwargs):\n if format == \"SPECFEM\":\n self._write_specfem(buf=buf, time_offset=kwargs[\"time_offset\"])\n else:\n raise NotImplementedError\n\n def _write_specfem(self, buf, time_offset):\n \"\"\"\n Write the adjoint source for SPECFEM.\n \"\"\"\n l = len(self.adjoint_source)\n\n to_write = np.empty((l, 2))\n\n to_write[:, 0] = np.linspace(0, (l - 1) * self.dt, l)\n to_write[:, 0] += time_offset\n # SPECFEM expects non-time reversed adjoint sources.\n to_write[:, 1] = self.adjoint_source[::-1]\n\n np.savetxt(buf, to_write)\n\n def write_to_asdf(self, ds, time_offset, coordinates=None, **kwargs):\n \"\"\"\n Writes the adjoint source to an ASDF file.\n Note: For now it is assumed SPECFEM will be using the adjoint source\n\n :param ds: The ASDF data structure read in using pyasdf.\n :type ds: str\n :param time_offset: The temporal offset of the first sample in seconds.\n This is required if using the adjoint source as input to SPECFEM.\n :type time_offset: float\n :param coordinates: If given, the coordinates of the adjoint source.\n The 'latitude', 'longitude', and 'elevation_in_m' of the adjoint\n source must be defined.\n :type coordinates: list\n\n .. rubric:: SPECFEM\n\n SPECFEM requires one additional parameter: the temporal offset of the\n first sample in seconds. The following example sets the time of the\n first sample in the adjoint source to ``-10``.\n\n >>> adj_src.write_to_asdf(ds, time_offset=-10,\n ... coordinates={'latitude':19.2,\n ... 'longitude':13.4,\n ... 'elevation_in_m':2.0})\n \"\"\"\n # Import here to not have a global dependency on pyasdf\n from pyasdf.exceptions import NoStationXMLForStation\n\n # Convert the adjoint source to SPECFEM format\n l = len(self.adjoint_source)\n specfem_adj_source = np.empty((l, 2))\n specfem_adj_source[:, 0] = np.linspace(0, (l - 1) * self.dt, l)\n specfem_adj_source[:, 1] = time_offset\n specfem_adj_source[:, 1] = self.adjoint_source[::-1]\n\n tag = \"%s_%s_%s\" % (self.network, self.station, self.component)\n min_period = self.min_period\n max_period = self.max_period\n component = self.component\n station_id = \"%s.%s\" % (self.network, self.station)\n\n if coordinates:\n # If given, all three coordinates must be present\n if {\"latitude\", \"longitude\", \"elevation_in_m\"}.difference(\n set(coordinates.keys())):\n raise ValueError(\n \"'latitude', 'longitude', and 'elevation_in_m'\"\n \" must be given\")\n else:\n try:\n coordinates = ds.waveforms[\n \"%s.%s\" % (self.network, self.station)].coordinates\n except NoStationXMLForStation:\n raise ValueError(\"Coordinates must either be given \"\n \"directly or already be part of the \"\n \"ASDF file\")\n\n # Safeguard against funny types in the coordinates dictionary\n latitude = float(coordinates[\"latitude\"])\n longitude = float(coordinates[\"longitude\"])\n elevation_in_m = float(coordinates[\"elevation_in_m\"])\n\n parameters = {\"dt\": self.dt, \"misfit_value\": self.misfit,\n \"adjoint_source_type\": self.adj_src_type,\n \"min_period\": min_period, \"max_period\": max_period,\n \"latitude\": latitude, \"longitude\": longitude,\n \"elevation_in_m\": elevation_in_m,\n \"station_id\": station_id, \"component\": component,\n \"units\": \"m\"}\n\n # Use pyasdf to add auxiliary data to the ASDF file\n ds.add_auxiliary_data(data=specfem_adj_source,\n data_type=\"AdjointSource\", path=tag,\n parameters=parameters)\n\n\ndef calculate_adjoint_source(adj_src_type, observed, synthetic, config,\n window, adjoint_src=True,\n plot=False, plot_filename=None, **kwargs):\n \"\"\"\n Central function of Pyadjoint used to calculate adjoint sources and misfit.\n\n This function uses the notion of observed and synthetic data to offer a\n nomenclature most users are familiar with. Please note that it is\n nonetheless independent of what the two data arrays actually represent.\n\n The function tapers the data from ``left_window_border`` to\n ``right_window_border``, both in seconds since the first sample in the\n data arrays.\n\n :param adj_src_type: The type of adjoint source to calculate.\n :type adj_src_type: str\n :param observed: The observed data.\n :type observed: :class:`obspy.core.trace.Trace`\n :param synthetic: The synthetic data.\n :type synthetic: :class:`obspy.core.trace.Trace`\n :param min_period: The minimum period of the spectral content of the data.\n :type min_period: float\n :param max_period: The maximum period of the spectral content of the data.\n :type max_period: float\n :param left_window_border: Left border of the window to be tapered in\n seconds since the first sample in the data arrays.\n :type left_window_border: float\n :param right_window_border: Right border of the window to be tapered in\n seconds since the first sample in the data arrays.\n :type right_window_border: float\n :param adjoint_src: Only calculate the misfit or also derive\n the adjoint source.\n :type adjoint_src: bool\n :param plot: Also produce a plot of the adjoint source. This will force\n the adjoint source to be calculated regardless of the value of\n ``adjoint_src``.\n :type plot: bool or empty :class:`matplotlib.figure.Figure` instance\n :param plot_filename: If given, the plot of the adjoint source will be\n saved there. Only used if ``plot`` is ``True``.\n :type plot_filename: str\n \"\"\"\n observed, synthetic = _sanity_checks(observed, synthetic)\n\n # Get number of samples now as the adjoint source calculation function\n # are allowed to mess with the trace objects.\n npts = observed.stats.npts\n\n if adj_src_type not in AdjointSource._ad_srcs:\n raise PyadjointError(\n \"Adjoint Source type '%s' is unknown. Available types: %s\" % (\n adj_src_type, \", \".join(\n sorted(AdjointSource._ad_srcs.keys()))))\n\n fct = AdjointSource._ad_srcs[adj_src_type][0]\n\n if plot:\n # The plot kwargs overwrites the adjoint_src kwarg.\n adjoint_src = True\n if plot is True:\n figure = plt.figure(figsize=(12, 6))\n else:\n # Assume plot is a preexisting figure instance\n figure = plot\n else:\n figure = None\n try:\n ret_val = fct(observed=observed, synthetic=synthetic,\n config=config, window=window,\n adjoint_src=adjoint_src, figure=figure, **kwargs)\n\n if plot and plot_filename:\n figure.savefig(plot_filename)\n elif plot is True:\n plt.show()\n\n finally:\n # Assure the figure is closed. Otherwise matplotlib will leak\n # memory. If the figure has been created outside of Pyadjoint,\n # it will not be closed.\n if plot is True:\n plt.close()\n\n # Get misfit an warn for a negative one.\n misfit = float(ret_val[\"misfit\"])\n if misfit < 0.0:\n warnings.warn(\"The misfit value is negative. Be cautious!\",\n PyadjointWarning)\n\n if adjoint_src and \"adjoint_source\" not in ret_val:\n raise PyadjointError(\"The actual adjoint source was not calculated \"\n \"by the underlying function although it was \"\n \"requested.\")\n\n # Be very defensive. This assures future adjoint source types can be\n # integrated smoothly.\n if adjoint_src:\n adjoint_source = ret_val[\"adjoint_source\"]\n # Raise if wrong type.\n if not isinstance(adjoint_source, np.ndarray) or \\\n adjoint_source.dtype != np.float64:\n raise PyadjointError(\"The adjoint source calculated by the \"\n \"underlying function is no numpy array with \"\n \"a `float64` dtype.\")\n if len(adjoint_source.shape) != 1:\n raise PyadjointError(\n \"The underlying function returned at adjoint source with \"\n \"shape %s. It must return a one-dimensional array.\" % str(\n adjoint_source.shape))\n if len(adjoint_source) != npts:\n raise PyadjointError(\n \"The underlying function returned an adjoint source with %i \"\n \"samples. It must return a function with %i samples which is \"\n \"the sample count of the input data.\" % (\n len(adjoint_source), npts))\n # Make sure the data returned has no infs or NaNs.\n if not np.isfinite(adjoint_source).all():\n raise PyadjointError(\n \"The underlying function returned an adjoint source with \"\n \"either NaNs or Inf values. This must not be.\")\n else:\n adjoint_source = None\n\n return AdjointSource(adj_src_type, misfit=misfit,\n adjoint_source=adjoint_source,\n dt=observed.stats.delta,\n min_period=config.min_period,\n max_period=config.max_period,\n network=observed.stats.network,\n station=observed.stats.station,\n component=observed.stats.channel,\n location=observed.stats.location,\n starttime=observed.stats.starttime)\n\n\ndef _sanity_checks(observed, synthetic):\n \"\"\"\n Perform a number of basic sanity checks to assure the data is valid\n in a certain sense.\n\n It checks the types of both, the start time, sampling rate, number of\n samples, ...\n\n :param observed: The observed data.\n :type observed: :class:`obspy.core.trace.Trace`\n :param synthetic: The synthetic data.\n :type synthetic: :class:`obspy.core.trace.Trace`\n\n :raises: :class:`~pyadjoint.PyadjointError`\n \"\"\"\n if not isinstance(observed, obspy.Trace):\n # Also accept Stream objects.\n if isinstance(observed, obspy.Stream) and \\\n len(observed) == 1:\n observed = observed[0]\n else:\n raise PyadjointError(\n \"Observed data must be an ObsPy Trace object.\")\n if not isinstance(synthetic, obspy.Trace):\n if isinstance(synthetic, obspy.Stream) and \\\n len(synthetic) == 1:\n synthetic = synthetic[0]\n else:\n raise PyadjointError(\n \"Synthetic data must be an ObsPy Trace object.\")\n\n if observed.stats.npts != synthetic.stats.npts:\n raise PyadjointError(\"Observed and synthetic data must have the same \"\n \"number of samples.\")\n\n sr1 = observed.stats.sampling_rate\n sr2 = synthetic.stats.sampling_rate\n\n if abs(sr1 - sr2) / sr1 >= 1E-5:\n raise PyadjointError(\"Observed and synthetic data must have the same \"\n \"sampling rate.\")\n\n # Make sure data and synthetics start within half a sample interval.\n if abs(observed.stats.starttime - synthetic.stats.starttime) > \\\n observed.stats.delta * 0.5:\n raise PyadjointError(\"Observed and synthetic data must have the same \"\n \"starttime.\")\n\n ptp = sorted([observed.data.ptp(), synthetic.data.ptp()])\n if ptp[1] / ptp[0] >= 5:\n warnings.warn(\"The amplitude difference between data and \"\n \"synthetic is fairly large.\", PyadjointWarning)\n\n # Also check the components of the data to avoid silly mistakes of\n # users.\n if len(set([observed.stats.channel[-1].upper(),\n synthetic.stats.channel[-1].upper()])) != 1:\n warnings.warn(\"The orientation code of synthetic and observed \"\n \"data is not equal.\")\n\n observed = observed.copy()\n synthetic = synthetic.copy()\n observed.data = np.require(observed.data, dtype=np.float64,\n requirements=[\"C\"])\n synthetic.data = np.require(synthetic.data, dtype=np.float64,\n requirements=[\"C\"])\n\n return observed, synthetic\n\n\ndef _discover_adjoint_sources():\n \"\"\"\n Discovers the available adjoint sources. This should work no matter if\n pyadjoint is checked out from git, packaged as .egg or for any other\n possibility.\n \"\"\"\n from . import adjoint_source_types\n\n AdjointSource._ad_srcs = {}\n\n fct_name = \"calculate_adjoint_source\"\n name_attr = \"VERBOSE_NAME\"\n desc_attr = \"DESCRIPTION\"\n add_attr = \"ADDITIONAL_PARAMETERS\"\n\n path = os.path.join(\n os.path.dirname(inspect.getfile(inspect.currentframe())),\n \"adjoint_source_types\")\n for importer, modname, _ in pkgutil.iter_modules(\n [path], prefix=adjoint_source_types.__name__ + \".\"):\n m = importer.find_module(modname).load_module(modname)\n if not hasattr(m, fct_name):\n continue\n fct = getattr(m, fct_name)\n if not callable(fct):\n continue\n\n name = modname.split('.')[-1]\n\n if not hasattr(m, name_attr):\n raise PyadjointError(\n \"Adjoint source '%s' does not have a variable named %s.\" %\n (name, name_attr))\n\n if not hasattr(m, desc_attr):\n raise PyadjointError(\n \"Adjoint source '%s' does not have a variable named %s.\" %\n (name, desc_attr))\n\n # Add tuple of name, verbose name, and description.\n AdjointSource._ad_srcs[name] = (\n fct,\n getattr(m, name_attr),\n getattr(m, desc_attr),\n getattr(m, add_attr) if hasattr(m, add_attr) else None)\n\n\n_discover_adjoint_sources()\n","sub_path":"src/pyadjoint/adjoint_source.py","file_name":"adjoint_source.py","file_ext":"py","file_size_in_byte":19169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"120090416","text":"from aip import AipSpeech\r\n\r\ndef audio_discern(audio_path = \"./audio/test.wav\",audio_type = \"wav\"):\r\n\r\n \"\"\" 你的 APPID AK SK \"\"\"\r\n APP_ID = '15857495' #''你的 App ID'\r\n API_KEY = '8oNWudGhOexb09KW8X2M2YLX' #'你的 Api Key'\r\n SECRET_KEY = 'F79btl1tnxfG4R8nMqRIRRAYdGznkfhH' #'你的 Secret Key'\r\n\r\n client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\r\n\r\n # 读取文件\r\n def get_file_content(filePath):\r\n with open(filePath, 'rb') as fp:\r\n return fp.read()\r\n # 识别本地文件\r\n text = client.asr(get_file_content(audio_path), audio_type, 16000, {'dev_pid': 1536,})\r\n return text\r\n\r\n","sub_path":"语音识别/audioDiscern.py","file_name":"audioDiscern.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"362958602","text":"\n# pylint: disable=I0011,W0232,E1101,F0401,C0103,C0325,C0301\n\nimport sys\n\nfrom django.conf import settings\nfrom django.db import connections, migrations\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.utils import ConnectionDoesNotExist\nfrom django.utils import timezone\n\n\ndef setup_cursor():\n try:\n cursor = connections['legacy'].cursor()\n except ConnectionDoesNotExist:\n print(\"Legacy database is not configured\")\n sys.exit(1)\n else:\n return cursor\n\n\ndef fix_legacy_exp_app_ids(apps, schea_editor):\n \"\"\"appIds were allowed to be null in legacy db.\n set all to rimac app prior to importing any legacy data\n \"\"\"\n cursor = setup_cursor()\n cursor.execute(\"UPDATE Experiments SET ApplicationId = 1\")\n\n\n\ndef import_apps(apps, schema_editor):\n cursor = setup_cursor()\n if cursor is None:\n return\n App = apps.get_model(\"tutalk_experiment_admin\", \"App\")\n ## it's important selecting the id field, for foreign key relationships\n sql = \"\"\"\nSELECT id, name, description, createdAt, updatedAt\nFROM Applications\n\"\"\"\n cursor.execute(sql)\n for row in cursor.fetchall():\n (app_id, name, desc, created_at, updated_at) = row\n app = App(id=app_id,\n name=name,\n description=desc,\n created=created_at,\n modified=updated_at)\n app.save()\n\n\ndef import_experimenters(apps, schema_editor):\n cursor = setup_cursor()\n if cursor is None:\n return\n Experimenter = apps.get_model(\"tutalk_experiment_admin\", \"Experimenter\")\n ## it's important selecting the id field, for foreign key relationships\n sql = \"\"\"\nSELECT id, name, description, createdAt, updatedAt\nFROM Experimenters\n\"\"\"\n cursor.execute(sql)\n for row in cursor.fetchall():\n (exptr_id, name, desc, created_at, updated_at) = row\n exptr = Experimenter(id=exptr_id,\n name=name,\n description=desc,\n created=created_at,\n modified=updated_at)\n exptr.save()\n\n\ndef import_experiments(apps, schema_editor):\n cursor = setup_cursor()\n if cursor is None:\n return\n Experimenter = apps.get_model(\"tutalk_experiment_admin\", \"Experimenter\")\n Experiment = apps.get_model(\"tutalk_experiment_admin\", \"Experiment\")\n App = apps.get_model(\"tutalk_experiment_admin\", \"App\")\n ## it's important selecting the id field, for foreign key relationships\n sql = \"\"\"\nSELECT id, name, description, tutalk_host, ExperimenterId, createdAt,\n updatedAt, ApplicationId\nFROM Experiments\n\"\"\"\n cursor.execute(sql)\n for row in cursor.fetchall():\n (exp_id, name, desc, tutalk_host, exptr_id, created_at, updated_at,\n app_id) = row\n try:\n exptr = Experimenter.objects.get(pk=exptr_id)\n except ObjectDoesNotExist:\n print(\"Experimenter not found with id %s\" % exptr_id)\n sys.exit(1)\n\n try:\n app = App.objects.get(pk=app_id)\n except ObjectDoesNotExist:\n print(\"App not found with id %s\" % app_id)\n sys.exit(1)\n\n exp = Experiment(id=exp_id,\n name=name,\n description=desc,\n tutalk_host=tutalk_host,\n experimenter=exptr,\n app=app,\n created=created_at,\n modified=updated_at)\n exp.save()\n\n\ndef import_conditions(apps, schema_editor):\n cursor = setup_cursor()\n if cursor is None:\n return\n Experiment = apps.get_model(\"tutalk_experiment_admin\", \"Experiment\")\n Condition = apps.get_model(\"tutalk_experiment_admin\", \"Condition\")\n ## it's important selecting the id field, for foreign key relationships\n sql = \"\"\"\nSELECT id, name, description, scenario, ExperimentId, createdAt, updatedAt\nFROM Conditions\n\"\"\"\n cursor.execute(sql)\n for row in cursor.fetchall():\n (cond_id, name, desc, scen, exp_id, created_at, updated_at) = row\n try:\n exp = Experiment.objects.get(pk=exp_id)\n except ObjectDoesNotExist:\n print(\"Experiment not found with id %s\" % exp_id)\n sys.exit(1)\n cond = Condition(id=cond_id,\n name=name,\n description=desc,\n scenario_name=scen,\n experiment=exp,\n created=created_at,\n modified=updated_at)\n cond.save()\n\n\ndef import_sites(apps, schema_editor):\n cursor = setup_cursor()\n if cursor is None:\n return\n Experiment = apps.get_model(\"tutalk_experiment_admin\", \"Experiment\")\n Site = apps.get_model(\"tutalk_experiment_admin\", \"Site\")\n ## it's important selecting the id field, for foreign key relationships\n sql = \"\"\"\nSELECT id, name, description, ExperimentId, createdAt, updatedAt\nFROM Sites\n\"\"\"\n cursor.execute(sql)\n for row in cursor.fetchall():\n (site_id, name, desc, exp_id, created_at, updated_at) = row\n try:\n exp = Experiment.objects.get(pk=exp_id)\n except ObjectDoesNotExist:\n print(\"Experiment not found with id %s\" % exp_id)\n sys.exit(1)\n site = Site(id=site_id,\n name=name,\n description=desc,\n experiment=exp,\n created=created_at,\n modified=updated_at)\n site.save()\n\n\ndef import_participants(apps, schema_editor):\n cursor = setup_cursor()\n if cursor is None:\n return\n Site = apps.get_model(\"tutalk_experiment_admin\", \"Site\")\n Condition = apps.get_model(\"tutalk_experiment_admin\", \"Condition\")\n Participant = apps.get_model(\"tutalk_experiment_admin\", \"Participant\")\n sql = \"\"\"\nSELECT id, uid, SiteId, ConditionId, createdAt, updatedAt\nFROM Participants\n\"\"\"\n cursor.execute(sql)\n for row in cursor.fetchall():\n (part_id, uid, site_id, cond_id, created_at, updated_at) = row\n try:\n site = Site.objects.get(pk=site_id)\n except ObjectDoesNotExist:\n print(\"Site not found with id %s\" % site_id)\n sys.exit(1)\n try:\n cond = Condition.objects.get(pk=cond_id)\n except ObjectDoesNotExist:\n print(\"Condition not found with id %s\" % cond_id)\n sys.exit(1)\n\n part = Participant(id=part_id,\n uid=uid,\n site=site,\n condition=cond,\n created=created_at,\n modified=updated_at)\n part.save()\n\n\ndef insert_staff_promo_code(apps, schema_editor):\n PromoCode = apps.get_model(\"tutalk_experiment_admin\", \"PromoCode\")\n pc = PromoCode(name=\"staff\",\n description=\"staff members\",\n is_active=True,\n is_superuser=True,\n registration_requires_password=True,\n registration_password=settings.STAFF_PASSWORD,\n registration_requires_email=True,\n registration_requires_uid=False,\n login_requires_password=False,\n login_password=None,\n site=None,\n created=timezone.now(),\n modified=timezone.now())\n pc.save()\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"tutalk_experiment_admin\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.RunPython(fix_legacy_exp_app_ids),\n migrations.RunPython(import_apps),\n migrations.RunPython(import_experimenters),\n migrations.RunPython(import_experiments),\n migrations.RunPython(import_conditions),\n migrations.RunPython(import_sites),\n migrations.RunPython(import_participants),\n migrations.RunPython(insert_staff_promo_code)\n ]\n","sub_path":"tutalk_experiment_admin/migrations/0002_import_legacy_data.py","file_name":"0002_import_legacy_data.py","file_ext":"py","file_size_in_byte":8028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"385406173","text":"# coding=utf8\n\"\"\"\n@author: Yantong Lai\n@date: 2019.5.5\n\nMIT License\n\nCopyright (c) 2019 Yantong Lai\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport os\nimport shutil\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\n\nindex_url = \"http://onestop.ucas.edu.cn/\"\nDownload_path = \"Download\"\nDir_str = \"项\"\n\n\ndef login():\n \"\"\"\n It is a function to log in the UCAS onestop system.\n \"\"\"\n try:\n print(\"1. Login.\\n\")\n # Wait for login.\n wait.until(EC.presence_of_element_located((By.CLASS_NAME, \"neirong\")))\n # Send username and password to log in.\n input_user = browser.find_element_by_id(\"menhuusername\")\n input_user.send_keys(username)\n input_pwd = browser.find_element_by_id(\"menhupassword\")\n input_pwd.send_keys(password)\n input_pwd.send_keys(Keys.ENTER)\n except Exception as e:\n print(e)\n\ndef gotoCourseWeb():\n \"\"\"\n It is a function to go to 'Course Website'.\n \"\"\"\n try:\n print(\"2. Go to Course Website.\\n\")\n course_web = wait.until(EC.element_to_be_clickable((By.XPATH, \"//a[@href='/portal/site/16/801']\")))\n course_web.click()\n\n # 2.1 Go to 'My Course'.\n my_course = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id=\"toolMenu\"]/ul/li[4]/a')))\n my_course.click()\n except Exception as e:\n print(e)\n\ndef listAllCourse():\n \"\"\"\n It is a function to list all the courses.\n \"\"\"\n try:\n print(\"3. List all the courses.\\n\")\n # Wait for loading.\n wait.until(EC.presence_of_element_located((By.ID, \"worksite\")))\n soup = BeautifulSoup(browser.page_source, features=\"lxml\")\n allcourses = soup.find_all(\"th\", {\"headers\":\"worksite\"})\n\n AllCoursesName = []\n AllCoursesUrl = []\n for item in allcourses:\n course_url = item.a.get(\"href\")\n AllCoursesUrl.append(course_url)\n course_name = item.a.text\n AllCoursesName.append(course_name)\n AllCoursesIndex = list(range(len(AllCoursesName)))\n AllCoursesVal = zip(AllCoursesName, AllCoursesUrl)\n AllCoursesDict = dict(zip(AllCoursesIndex, AllCoursesVal))\n return AllCoursesDict\n except Exception as e:\n print(e)\n\ndef chooseCourse(CourseIdx):\n \"\"\"\n It is a function to choose Course and go to that couse..\n :param CourseIdx:\n \"\"\"\n try:\n print(\"4. Choose course and go to that course.\\n\")\n # Open a new tab\n browser.execute_script(\"window.open('');\")\n browser.switch_to.window(window_name=browser.window_handles[1])\n browser.get(AllCourses[CourseIdx][1])\n browser.implicitly_wait(5)\n\n courseID = AllCourses[CourseIdx][1].split(\"/\")[-1]\n\n # Click My Resource\n courseSrc = browser.find_element_by_xpath('//*[@id=\"toolMenu\"]/ul/li[5]/a')\n courseSrc.click()\n browser.implicitly_wait(5)\n\n soup = BeautifulSoup(browser.page_source, features=\"lxml\")\n FileItems = soup.find_all(\"span\", {\"class\": \"hidden-sm hidden-xs\"})\n\n # Create the Course Directory at the Download_path\n course_path = Download_path + \"/\" + AllCourses[CourseIdx][0]\n if not os.path.exists(course_path):\n os.mkdir(course_path)\n print(\"Create %s dir successfully.\\n\" %course_path)\n\n FileLists = []\n for item in FileItems:\n FileLists.append(item.text)\n\n FileLists.pop(0)\n FileListsIdx = range(len(FileLists))\n FileDict = dict(zip(FileListsIdx, FileLists))\n print(\"Sources list is as follow: \\n\")\n return FileDict\n\n # If only file in the FileLists, download all the files.\n # If there are some directories in FileLists, input the index of specific directory and download\n except Exception as e:\n print(e)\n\ndef checkDir(srcIndex):\n \"\"\"\n It is a function to check whether it's a directory or file.\n :return: If it's a dir, return 1; else return 0\n \"\"\"\n soup = BeautifulSoup(browser.page_source, features=\"lxml\")\n allsrc = soup.find_all(\"td\", {\"headers\": \"size\"})\n if Dir_str in allsrc[srcIndex].text:\n return 1\n else:\n return 0\n\ndef every_downloads_chrome(browser):\n \"\"\"\n It is a function to check whether downloading task is completed.\n :param driver: Chrome Webdriver\n \"\"\"\n if not browser.current_url.startswith(\"chrome://downloads\"):\n browser.get(\"chrome://downloads/\")\n return browser.execute_script(\"\"\"\n var items = downloads.Manager.get().items_;\n if (items.every(e => e.state === \"COMPLETE\"))\n return items.map(e => e.fileUrl);\n \"\"\")\n\ndef move_file(dst_path):\n \"\"\"\n It is a function to put the downloaded file into corresponding directory.\n @:param dst_path: It is the path of destination.\n \"\"\"\n for file in os.listdir(Download_path):\n if file.endswith(\".crdownload\"):\n time.sleep(5)\n continue\n elif file.endswith(\".pdf\") or file.endswith(\".pptx\") or file.endswith(\".ppt\") or file.endswith(\".docx\") or file.endswith(\".doc\") or file.endswith(\".zip\") or file.endswith(\".xlsx\") or file.endswith(\".rar\"):\n print(\"### Move %s ### \\n\" %file)\n shutil.move(Download_path + \"/\" + file, dst_path)\n else:\n continue\n\ndef downloadCourse(srcIndex, courseIndex):\n \"\"\"\n It is a function to download course resources.\n @:param srcIndex: It is the index of which resource you want to download at the specific course path.\n @:param courseIndex: It is the index of course you want to download.\n \"\"\"\n # At most, each course include 2 child directories.\n try:\n if checkDir(srcIndex) == 1:\n chooseDir = CourseResource[srcIndex]\n print(\"chooseDir = \", chooseDir)\n\n # It is a directory, go into the directory\n srcDir_path = Download_path + \"/\" + AllCourses[courseIndex][0] + \"/\" + chooseDir\n print(\"(1) os.getcwd() = \", os.getcwd())\n print(\"srcDir_path = \", srcDir_path)\n\n if not os.path.exists(srcDir_path):\n os.mkdir(srcDir_path)\n\n # FileScript = \"document.getElementById('sakai_action').value='doExpand_collection';document.getElementById('collectionId').value='/group/\" + CourseID + \"/\" + \\\n # CourseResource[int(srcIndex)] + \"/';document.getElementById('navRoot').value='';document.getElementById('showForm').submit();\"\n browser.find_element_by_xpath('//*[@id=\"showForm\"]/table/tbody/tr[' + str(3 + srcIndex) + ']/td[3]/a[2]').click()\n # //*[@id=\"showForm\"]/table/tbody/tr[6]/td[3]/a[2]\n browser.implicitly_wait(5)\n\n soup = BeautifulSoup(browser.page_source, features=\"lxml\")\n items = soup.find_all(\"span\", {\"class\": \"hidden-sm hidden-xs\"})\n\n chooseDirTree = []\n for item in items:\n # print(item.text)\n if item.text == chooseDir:\n continue\n chooseDirTree.append(item.text)\n print(\"chooseDirTree = \", chooseDirTree)\n print(\"len(chooseDirTree) = \", len(chooseDirTree))\n\n chooseDirType = []\n for idx in range(len(chooseDirTree)):\n # print(checkDir(idx))\n print(\"chooseDirTree[idx] = \", chooseDirTree[idx])\n chooseDirType.append(checkDir(idx))\n if checkDir(idx) == 1:\n # @treePath is the param of item path of the specific source.\n treePath = srcDir_path + \"/\" + chooseDirTree[idx]\n print(\"Now, treePath = \", treePath)\n if not os.path.exists(treePath):\n os.mkdir(treePath)\n\n # Get into the tree dir.\n browser.find_element_by_xpath('//*[@id=\"showForm\"]/table/tbody/tr[' + str(3 + idx) + ']/td[3]/a[2]').click()\n browser.implicitly_wait(5)\n\n # os.chdir(\"..\")\n print(\"(2) os.getcwd() = \", os.getcwd())\n\n ### Download #####\n soup = BeautifulSoup(browser.page_source, features=\"lxml\")\n src = soup.find_all(\"td\", {\"class\": \"specialLink title\"})\n\n FileLists = []\n FileUrl = []\n print(\"Start Downloading.\\n\")\n for item in src:\n url = item.a.get(\"href\")\n if url != \"#\":\n # Click .pptx/pdf/ppt/docx/doc/xls/csv/zip url\n file = browser.find_element_by_xpath('//a[@href=\"' + url + '\"]')\n file.click()\n\n try:\n paths = WebDriverWait(browser, 240, 1).until(every_downloads_chrome)\n print(\"Save Successfully!\\n\")\n\n except Exception as e:\n print(e)\n\n print(\"Move file to Dst path.\\n\")\n # print(\"checkDir(idx) = \", checkDir(idx))\n # if checkDir(idx) == 1:\n # move_file(Download_path + \"/\" + AllCourses[courseIndex][0] + \"/\" + chooseDir + \"/\" + chooseDirTree[idx])\n # elif checkDir(idx) == 0:\n # move_file(Download_path + \"/\" + AllCourses[courseIndex][0] + \"/\" + chooseDir)\n move_file(Download_path + \"/\" + AllCourses[courseIndex][0] + \"/\" + chooseDir)\n # srcDir_path = Download_path + \"/\" + AllCourses[courseIndex][0] + \"/\" + chooseDir\n print(\"Move Successfully.\\n\")\n\n # Go back to specific Source\n browser.back()\n\n if idx == len(chooseDirTree):\n browser.find_element_by_xpath('//*[@id=\"showForm\"]/ol/li[2]/a').click()\n else:\n browser.find_element_by_xpath('//*[@id=\"showForm\"]/ol/li[3]/a').click()\n else:\n ### Download #####\n soup = BeautifulSoup(browser.page_source, features=\"lxml\")\n src = soup.find_all(\"td\", {\"class\": \"specialLink title\"})\n\n print(\"Start Downloading.\\n\")\n for item in src:\n url = item.a.get(\"href\")\n if url != \"#\":\n # Click .pptx/pdf/ppt/docx/doc/xls/csv/zip file\n file = browser.find_element_by_xpath('//a[@href=\"' + url + '\"]')\n file.click()\n try:\n paths = WebDriverWait(browser, 240, 1).until(every_downloads_chrome)\n print(\"Save Successfully!\\n\")\n except Exception as e:\n print(e)\n\n print(\"Move file to Dst path.\\n\")\n move_file(Download_path + \"/\" + AllCourses[courseIndex][0])\n print(\"Move Successfully.\\n\")\n\n browser.back()\n\n except Exception as e:\n print(e)\n\ndef logout():\n \"\"\"\n It is a function to log out UCAS onestop system.\n \"\"\"\n try:\n browser.close()\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n\n print(\"Please input your UCAS onestop username: \")\n username = input()\n\n print(\"Please input your password: \")\n password = input()\n\n # 0.1 Create a Dir named \"Download\";\n if not os.path.exists(Download_path):\n os.mkdir(Download_path)\n\n # 0.2 Open a Chrome browser\n options = Options()\n options.add_experimental_option(\"prefs\", {\n \"download.default_directory\": Download_path,\n \"download.prompt_for_download\": False,\n \"download.directory_upgrade\": True,\n \"safebrowsing.enabled\": True,\n \"plugins.always_open_pdf_externally\": True\n })\n\n browser = webdriver.Chrome(options=options)\n browser.get(index_url)\n\n # Define wait for loading\n wait = WebDriverWait(browser, 10)\n\n # 1. Login\n login()\n\n # 2. Go to course website.\n gotoCourseWeb()\n\n # 3. List all the courses.\n AllCourses = listAllCourse()\n print(AllCourses)\n\n # 4. Choose Course and go to the course you chose.\n # Create a directory under Download_path and name the directory as the course name.\n print(\"Please input the index of which course you want to choose.\\n\")\n CourseIndex = int(input())\n CourseID = AllCourses[CourseIndex][1].split(\"/\")[-1]\n\n CourseResource = chooseCourse(CourseIndex)\n print(CourseResource)\n\n # 5. If only file in the FileLists, download all the files.\n # If there are some directories in FileLists, input the index of specific directory and download\n print(\"5. Please input the index of directory/file\\n\")\n SrcIndex = int(input())\n downloadCourse(SrcIndex, CourseIndex)\n\n # 6. Logout\n print(\"6. Logout.\\n\")\n logout()\n","sub_path":"Download_Chrome.py","file_name":"Download_Chrome.py","file_ext":"py","file_size_in_byte":13969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"631908721","text":"import argparse\nimport os\nimport re\nimport numpy as np\nimport math\n\nparser = argparse.ArgumentParser(description='remove reads that map to contigs that arent part of cycles')\nparser.add_argument('in_dir', metavar='', type=str, help='dir')\nparser.add_argument('med_cov_table', metavar='', type=str, help='removed cycles')\nargs = parser.parse_args()\n\ndirs = os.listdir(args.in_dir)\n\nprint('In dir:',args.in_dir)\n\nsubject_dirs = []\nfor dir in dirs:\n if re.match('s[0-9]+_',dir):\n subject_dirs.append(dir)\n \nsubj_dirs_ordered = []\nfor i in range(0,2*len(subject_dirs)):\n print('hello')\n for j in range(1,3):\n for dirs in subject_dirs:\n dirs_test = dirs.split('_')\n if int(dirs_test[0][1:]) == i and int(dirs_test[1][1:]) == j:\n subj_dirs_ordered.append(dirs)\n print('hello')\nfor i in range(0,len(subject_dirs)):\n subject_dirs[i] = subj_dirs_ordered[i]\n print(subj_dirs_ordered[i])\n\nfor dir in subject_dirs:\n cyc_count = 0\n file = args.in_dir + '/' + dir + '/stats'\n with open(file) as stats:\n for line in stats:\n if cyc_count == 0:\n index = 0\n col_htable = {}\n line = line.split()\n for col in line:\n col_htable[col] = index\n index += 1\n cyc_count += 1\n cov_table = np.zeros((len(subject_dirs), cyc_count-1), dtype=int)\n break\n\n\nsubject_num=0\nfor dir in subject_dirs:\n file = args.in_dir + '/' + dir + '/stats' \n with open(file) as stats:\n next(stats)\n cyc_count = 0\n for line in stats: \n line = line.split()\n med_cov = float(line[col_htable['Med_cov']])\n med_cov = math.floor(med_cov)\n cov_table[subject_num][cyc_count] = med_cov\n cyc_count += 1\n subject_num += 1\n\nofile = open(args.med_cov_table,'w+')\nfor sub in subject_dirs:\n ofile.write(sub + '\\t')\nofile.write('\\n')\n\n\n# for subj_count in range(0,len(subject_dirs)):\n# print(cov_table[subj_count])\n\nfor cyc_count in range(0,len(cov_table[0])): \n for subj_count in range(0,len(subject_dirs)):\n cyc_counter = 0\n for cov in cov_table[subj_count]:\n if cyc_counter == cyc_count:\n ofile.write(str(cov) + '\\t')\n cyc_counter += 1\n ofile.write('\\n')\n \n \n ","sub_path":"md/Python/make_cov_table.py","file_name":"make_cov_table.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"271287437","text":"# flake8: noqa\r\nimport os\r\nimport sys\r\n\r\n# vnpy_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))\r\n# if vnpy_root not in sys.path:\r\n# sys.path.append(vnpy_root)\r\n\r\nos.environ[\"VNPY_TESTING\"] = \"1\"\r\n\r\nfrom vnpy.data.tdx.tdx_common import FakeStrategy\r\nfrom vnpy.data.tdx.tdx_stock_data import *\r\n\r\nos.environ[\"VNPY_TESTING\"] = \"1\"\r\n\r\nimport json\r\n\r\nt1 = FakeStrategy()\r\nt2 = FakeStrategy()\r\n# 创建API对象\r\napi_01 = TdxStockData(t1)\r\n\r\n# 获取市场下股票\r\nfor market_id in range(2):\r\n print('get market_id:{}'.format(market_id))\r\n security_list = api_01.get_security_list(market_id)\r\n if len(security_list) == 0:\r\n continue\r\n for security in security_list:\r\n if security.get('code', '').startswith('12') or u'转债' in security.get('name', ''):\r\n str_security = json.dumps(security, indent=1, ensure_ascii=False)\r\n print('market_id:{},{}'.format(market_id, str_security))\r\n\r\n str_markets = json.dumps(security_list, indent=1, ensure_ascii=False)\r\n print(u'{}'.format(str_markets))\r\n\r\n# 获取历史分钟线\r\napi_01.get_bars('002024', period='1hour', callback=t1.display_bar)\r\n\r\n# api.get_bars(symbol, period='5min', callback=display_bar)\r\n# api.get_bars(symbol, period='1day', callback=display_bar)\r\n# api_02 = TdxData(t2)\r\n# api_02.get_bars('601390', period='1day', callback=t1.display_bar)\r\n\r\n# 获取历史分时数据\r\n# ret,result = api_01.get_history_transaction_data('RB99', '20190909')\r\n# for r in result[0:10] + result[-10:]:\r\n# print(r)\r\n\r\n# 获取历史分时数据\r\nret, result = api_01.get_history_transaction_data('600410', '20190925')\r\nfor r in result[0:10] + result[-10:]:\r\n print(r)\r\n","sub_path":"tdxdata/tdx_stock_ex.py","file_name":"tdx_stock_ex.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"578488966","text":"import kivy\nkivy.require ( '1.8.0 ' )\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.core.window import WindowBase\nfrom kivy.core.window import Window\nfrom kivy.graphics import Canvas, Translate, Fbo, ClearColor, ClearBuffers\n\n\n'''\nTrying to understand this hint\nhttp://stackoverflow.com/questions/22755619/screenshot-gives-importerror-cannot-import-name-glreadpixels-error-in-kivy\n'''\n\ndef export_to_png(self, filename, *args):\n '''Saves an image of the widget and its children in png format at the\n specified filename. Works by removing the widget canvas from its\n parent, rendering to an :class:`~kivy.graphics.fbo.Fbo`, and calling\n :meth:`~kivy.graphics.texture.Texture.save`.\n .. note::\n The image includes only this widget and its children. If you want to\n include widgets elsewhere in the tree, you must call\n :meth:`~Widget.export_to_png` from their common parent, or use\n :meth:`~kivy.core.window.Window.screenshot` to capture the whole\n window.\n .. note::\n The image will be saved in png format, you should include the\n extension in your filename.\n .. versionadded:: 1.8.1\n '''\n\n if self.parent is not None:\n canvas_parent_index = self.parent.canvas.indexof(self.canvas)\n self.parent.canvas.remove(self.canvas)\n\n fbo = Fbo(size=self.size)\n\n with fbo:\n ClearColor(0, 0, 0, 1)\n ClearBuffers()\n Translate(-self.x, -self.y, 0)\n\n fbo.add(self.canvas)\n fbo.draw()\n fbo.texture.save(filename)\n fbo.remove(self.canvas)\n\n if self.parent is not None:\n self.parent.canvas.insert(canvas_parent_index, self.canvas)\n\n return True\n\nkv = '''\ncameraWidget:\n orientation: 'vertical'\n Camera:\n id: camera\n resolution: (640, 480)\n play: False\n ToggleButton:\n text: 'Play'\n on_press: camera.play = not camera.play\n size_hint_y: None\n height: '48dp'\n Button:\n text: \"Take picture\"\n on_press: root.TakePicture()\n height: '48dp'\n'''\nclass cameraWidget(BoxLayout):\n def TakePicture(self, *args):\n self.export_to_png = export_to_png\n self.export_to_png(self.ids.camera, filename='test2.png')\n\nclass MyApp(App):\n def build(self):\n return Builder.load_string(kv)\nif __name__ == '__main__':\n MyApp().run()","sub_path":"camera_example.py","file_name":"camera_example.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"570732613","text":"import unittest\nfrom unittest import mock\nfrom unittest.mock import Mock\n\nfrom ekstep_data_pipelines.common.audio_commons.transcription_clients.azure_transcription_client import (\n EkstepTranscriptionClient,\n)\n\n\nclass TestEkstepTranscriptionClient(unittest.TestCase):\n def setUp(self):\n super(TestEkstepTranscriptionClient, self).setUp()\n\n config = {\"server_host\": '127.0.0.1', \"port\": '50051', \"language\": \"hi\"}\n\n self.ekstep_client = EkstepTranscriptionClient(**config)\n\n @mock.patch(\"pickle.dump\")\n def test_call_speech_to_text_ekstep(self, mock_dump):\n mock_client = Mock()\n\n self.ekstep_client.client = mock_client\n\n mock_new_result = Mock()\n\n mock_client.recognize.return_value = mock_new_result\n\n mock_new_result.transcript = (\n \" कोरोना के प्रभाव से हमारी मन की बात भी अछूती नहीं रही है।\"\n )\n\n actual_result = self.ekstep_client.generate_transcription(\n \"test_language\", \"input_file_path\"\n )\n\n self.assertEqual(mock_client.recognize.call_count, 1)\n\n self.assertEqual(\n actual_result, \" कोरोना के प्रभाव से हमारी मन की बात भी अछूती नहीं रही है।\"\n )\n","sub_path":"packages/ekstep_pipelines_tests/common/audio_commons/transcription_clients_tests/ekstepmodel_transcription_client_tests.py","file_name":"ekstepmodel_transcription_client_tests.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"457409480","text":"import torch.nn as nn\nimport torch\nimport time\n\n\nclass one_conv(nn.Module):\n def __init__(self, inchanels, growth_rate, kernel_size=3):\n super(one_conv, self).__init__()\n self.conv = nn.Conv2d(inchanels, growth_rate, kernel_size=kernel_size, padding=kernel_size >> 1, stride=1)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n output = self.relu(self.conv(x))\n output = torch.cat((x, output), 1)\n return output\n\n\nclass RDB(nn.Module):\n def __init__(self, G0, C, G, kernel_size=3):\n super(RDB, self).__init__()\n convs = []\n for i in range(C):\n convs.append(one_conv(G0 + i * G, G))\n self.conv = nn.Sequential(*convs)\n # local_feature_fusion\n self.LFF = nn.Conv2d(G0 + C * G, G0, kernel_size=1, padding=0, stride=1)\n\n def forward(self, x):\n out = self.conv(x)\n lff = self.LFF(out)\n # local residual learning\n return lff + x\n\n\nclass RDN(nn.Module):\n def __init__(self, cfg):\n '''\n cfg: the system para\n '''\n super(RDN, self).__init__()\n '''\n D: RDB number 20\n C: the number of conv layer in RDB 6\n G: the growth rate 32\n G0:local and global feature fusion layers 64filter\n '''\n self.D = 10 # 20 #\n self.C = 3 # 6\n self.G = 32\n self.G0 = 64\n kernel_size = 3\n input_channels = 3\n out_channels = 3\n # shallow feature extraction\n self.SFE1 = nn.Conv2d(input_channels, self.G0, kernel_size=kernel_size, padding=kernel_size >> 1, stride=1)\n self.SFE2 = nn.Conv2d(self.G0, self.G0, kernel_size=kernel_size, padding=kernel_size >> 1, stride=1)\n # RDB for paper we have D RDB block\n self.RDBS = nn.ModuleList()\n for d in range(self.D):\n self.RDBS.append(RDB(self.G0, self.C, self.G, kernel_size))\n # Global feature fusion\n self.GFF = nn.Sequential(\n nn.Conv2d(self.D * self.G0, self.G0, kernel_size=1, padding=0, stride=1),\n nn.Conv2d(self.G0, self.G0, kernel_size, padding=kernel_size >> 1, stride=1),\n )\n # upsample net\n self.up_net = nn.Sequential(\n nn.Conv2d(self.G0, self.G * 4, kernel_size=kernel_size, padding=kernel_size >> 1, stride=1),\n nn.PixelShuffle(2),\n nn.Conv2d(self.G, self.G * 4, kernel_size=kernel_size, padding=kernel_size >> 1, stride=1),\n nn.PixelShuffle(2),\n nn.Conv2d(self.G, out_channels, kernel_size=kernel_size, padding=kernel_size >> 1, stride=1)\n )\n\n def forward(self, **args):\n x = args['input_x']\n # f-1\n f__1 = self.SFE1(x)\n out = self.SFE2(f__1)\n RDB_outs = []\n for i in range(self.D):\n out = self.RDBS[i](out)\n RDB_outs.append(out)\n out = torch.cat(RDB_outs, 1)\n out = self.GFF(out)\n out = f__1 + out\n out = self.up_net(out)\n out = out.permute(0, 2, 3, 1)\n\n return out\n","sub_path":"NetWorks/model/SrdnModel_RDN.py","file_name":"SrdnModel_RDN.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"594701093","text":"def next_bigger(n):\n\tst = list(str(n)) \n\tfor i in xrange(len(st)-1,0,-1): #Reverse iteration \n\t\tif st[i] > st[i-1]: #If current number is greater than previous\n\t\t\tst[i:] = sorted(st[i:]) #Sort interval\n\t\t\tj = i + (next(index for index,item in enumerate(st[i:]) if item > st[i-1])) #Find index of element greater than previous number\n\t\t\tst[i-1],st[j] = st[j],st[i-1]\n\t\t\tst[i:] = sorted(st[i:])\n\t\t\treturn int(\"\".join(st))\n\treturn -1\n\n\n\n# You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:\n\n# next_bigger(12)==21\n# next_bigger(513)==531\n# next_bigger(2017)==2071\n\n# If no bigger number can be composed using those digits, return -1:\n\n# next_bigger(9)==-1\n# next_bigger(111)==-1\n# next_bigger(531)==-1\n\n\n\n\n","sub_path":"Python/4Kyu/Next bigger number with the same digits.py","file_name":"Next bigger number with the same digits.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"540438258","text":"from django.db import models\n\n\nclass Event(models.Model):\n title = models.CharField(max_length=200, verbose_name='Заголовок')\n description = models.TextField(verbose_name='Описание')\n created = models.DateTimeField('Дата создания', auto_now_add=True)\n start_date = models.DateField(\n verbose_name='Дата начала',\n help_text='DD.MM.YYYY'\n )\n start_time = models.TimeField(\n verbose_name='Время начала',\n help_text='HH:MM'\n )\n end_time = models.TimeField(\n blank=True,\n null=True,\n verbose_name='Время окончания',\n help_text='HH:MM',\n )\n responsible = models.CharField(\n max_length=200,\n verbose_name='Ответственный',\n blank=True,\n null=True,\n )\n\n class Meta:\n verbose_name = 'Событие'\n verbose_name_plural = 'События'\n ordering = ['start_date', 'start_time']\n constraints = [\n models.UniqueConstraint(\n fields=['start_date', 'start_time'],\n name='unique_start_date_time'\n )\n ]\n\n def __str__(self):\n return self.title\n\n @property\n def all_day(self):\n if self.end_time:\n if (self.end_time.hour - self.start_time.hour) >= 9:\n return True\n return False\n","sub_path":"my_calendar/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105652283","text":"# Copyright 2020, CS Systemes d'Information, http://www.c-s.fr\n#\n# This file is part of pytest-executable\n# https://www.github.com/CS-SI/pytest-executable\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\"\"\"Entry point into the pytest executable plugin.\"\"\"\n\nimport logging\nimport sys\nfrom functools import cmp_to_key\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\n\nimport _pytest\nimport py\nimport pytest\nfrom _pytest.config import Config\nfrom _pytest.terminal import TerminalReporter\n\nfrom . import report, test_case_yaml\nfrom .file_tools import create_output_directory, find_references, get_mirror_path\nfrom .script_runner import ScriptRunner, get_final_script\nfrom .settings import Settings\n\nLOGGER = logging.getLogger(__name__)\n\n# files to be ignored when creating the output directories symlinks\nOUTPUT_IGNORED_FILES = (\"__pycache__\", \"conftest.py\", \"test_case.yaml\")\n\nEXE_RUNNER_NAME = \"run_executable\"\n\n# file with the test default settings\nSETTINGS_PATH = Path(__file__).parent / \"test_case.yaml\"\n\n# caches the test case directory path to marks to propagate them to all the\n# test modules of a test case\n_marks_cache: Dict[str, List[str]] = {}\n\n\ndef pytest_addoption(parser):\n \"\"\"CLI options for the plugin.\"\"\"\n group = parser.getgroup(\"executable\", \"executable testing\")\n group.addoption(\n \"--runner\",\n metavar=\"PATH\",\n help=\"use the shell script at PATH to run an executable, if omitted then \"\n \"the executable is not run but the other test processing will be\",\n )\n group.addoption(\n \"--output-root\",\n default=\"tests-output\",\n metavar=\"PATH\",\n help=\"use PATH as the root directory of the tests output, default: %(default)s\",\n )\n group.addoption(\n \"--overwrite-output\",\n action=\"store_true\",\n help=\"overwrite existing files in the tests output directories\",\n )\n group.addoption(\n \"--clean-output\",\n action=\"store_true\",\n help=\"clean the tests output directories before executing the tests\",\n )\n group.addoption(\n \"--regression-root\",\n metavar=\"PATH\",\n help=\"use PATH as the root directory with the references for the \"\n \"regression testing, if omitted then the tests using the regression_path \"\n \"fixture will be skipped\",\n )\n group.addoption(\n \"--default-settings\",\n default=SETTINGS_PATH,\n metavar=\"PATH\",\n help=\"use the yaml file at PATH for the global default test settings \"\n \"instead of the built-in one\",\n )\n group.addoption(\n \"--equal-nan\",\n action=\"store_true\",\n help=\"consider nan values as equal when doing comparison with the \"\n \"references for the built-in regression testing\",\n )\n group.addoption(\n \"--report-generator\",\n metavar=\"PATH\",\n help=\"use the script at PATH to generate a test report\",\n )\n\n # change default traceback settings to get only the message without the\n # traceback\n term_rep_options = parser.getgroup(\"terminal reporting\").options\n tb_option = next(\n option for option in term_rep_options if option.names() == [\"--tb\"]\n )\n tb_option.default = \"line\"\n\n\ndef pytest_sessionstart(session):\n \"\"\"Check the cli arguments.\"\"\"\n getoption = session.config.getoption\n if getoption(\"clean_output\") and getoption(\"overwrite_output\"):\n msg = \"options --clean-output and --overwrite-output are not compatible\"\n raise pytest.UsageError(msg)\n\n\ndef _get_parent_path(fspath: py.path.local) -> Path:\n \"\"\"Return the resolved path to a parent directory.\n\n Args:\n fspath: Path object from pytest.\n\n Returns:\n Resolved path to the parent directory of the given pat.\n \"\"\"\n return Path(fspath).parent.resolve(True)\n\n\n@pytest.fixture(scope=\"module\")\ndef equal_nan(request):\n \"\"\"Fixture to whether consider nan as equal when comparing fields.\"\"\"\n return request.config.getoption(\"equal_nan\")\n\n\n@pytest.fixture(scope=\"module\")\ndef create_output_tree(request):\n \"\"\"Fixture to create and return the path to the output directory tree.\"\"\"\n getoption = request.config.getoption\n output_root = Path(getoption(\"output_root\"))\n parent_path = _get_parent_path(request.node.fspath)\n output_path = get_mirror_path(parent_path, output_root.resolve())\n\n try:\n create_output_directory(\n parent_path,\n output_path,\n not getoption(\"overwrite_output\"),\n getoption(\"clean_output\"),\n OUTPUT_IGNORED_FILES,\n )\n except FileExistsError:\n msg = (\n f'the output directory \"{output_path}\" already exists: either '\n \"remove it manually or use the --clean-output option to remove \"\n \"it or use the --overwrite-output to overwrite it\"\n )\n raise FileExistsError(msg)\n\n\n@pytest.fixture(scope=\"module\")\ndef output_path(request):\n \"\"\"Fixture to return the path to the output directory.\"\"\"\n output_root = Path(request.config.getoption(\"output_root\")).resolve(True)\n return get_mirror_path(_get_parent_path(request.node.fspath), output_root)\n\n\ndef _get_settings(config: _pytest.config.Config, path: Path) -> Settings:\n \"\"\"Return the settings from global and local test_case.yaml.\n\n Args:\n config: Config from pytest.\n path: Path to a test case directory.\n\n Returns:\n The settings from the test case yaml.\n \"\"\"\n return Settings.from_local_file(\n Path(config.getoption(\"default_settings\")),\n _get_parent_path(path) / SETTINGS_PATH.name,\n )\n\n\n@pytest.fixture(scope=\"module\")\ndef tolerances(request):\n \"\"\"Fixture that provides the settings from global and local test_case.yaml.\"\"\"\n return _get_settings(request.config, request.node.fspath).tolerances\n\n\n@pytest.fixture(scope=\"module\")\ndef runner(request, create_output_tree, output_path):\n \"\"\"Fixture to run the executable with a runner script.\n\n This fixture will create a :file:`run_executable.sh` script in the test case\n output directory from the script passed to the pytest command line with the\n option :option:`--runner`. The placeholders {nproc} and {output_path} are\n replaced with their actual values in the written script. The runner object\n created by the fixture can be executed with the :py:meth:`run` method\n which will return the return code of the script execution.\n\n Returns:\n ScriptRunner object.\n \"\"\"\n runner_path = request.config.getoption(\"runner\")\n if runner_path is None:\n pytest.skip(\"no runner provided to --runner\")\n\n # check path\n runner_path = Path(runner_path).resolve(True)\n\n nproc = _get_settings(request.config, request.node.fspath).nproc\n\n variables = dict(output_path=output_path, nproc=nproc)\n script = get_final_script(runner_path, variables)\n return ScriptRunner(EXE_RUNNER_NAME, script, output_path)\n\n\ndef _get_regression_path(\n config: _pytest.config.Config, fspath: py.path.local\n) -> Optional[Path]:\n \"\"\"Return the path to the reference directory of a test case.\n\n None is returned if --regression-root is not passed to the CLI.\n\n Args:\n config: Config from pytest.\n fspath: Path to a test case directory.\n\n Returns:\n The path to the reference directory of the test case or None.\n \"\"\"\n regression_path = config.getoption(\"regression_root\")\n if regression_path is None:\n return None\n return get_mirror_path(\n _get_parent_path(fspath), Path(regression_path).resolve(True)\n )\n\n\n@pytest.fixture(scope=\"module\")\ndef regression_path(request):\n \"\"\"Fixture to return the path of a test case under the references tree.\"\"\"\n regression_path = _get_regression_path(request.config, request.node.fspath)\n if regression_path is None:\n pytest.skip(\"no tests references root directory provided to --regression-root\")\n return regression_path\n\n\ndef pytest_generate_tests(metafunc):\n \"\"\"Create the regression_file_path parametrized fixture.\n\n Used for accessing the references files.\n\n If --regression-root is not set then no reference files will be provided.\n \"\"\"\n if \"regression_file_path\" not in metafunc.fixturenames:\n return\n\n # result absolute and relative file paths to be provided by the fixture parameter\n # empty means skip the test function that use the fixture\n file_paths = []\n\n regression_path = _get_regression_path(metafunc.config, metafunc.definition.fspath)\n\n if regression_path is not None:\n settings_path = metafunc.definition.fspath\n settings = _get_settings(metafunc.config, settings_path)\n\n if settings.references:\n file_paths = find_references(regression_path, settings.references)\n\n metafunc.parametrize(\n \"regression_file_path\",\n file_paths,\n scope=\"function\",\n ids=list(map(str, [f.relative for f in file_paths])),\n )\n\n\ndef pytest_collect_file(parent, path):\n \"\"\"Collect test cases defined with a yaml file.\"\"\"\n if path.basename == SETTINGS_PATH.name:\n return TestCaseYamlModule(path, parent)\n\n\ndef pytest_configure(config):\n \"\"\"Register the possible markers and change default error display.\n\n Display only the last error line without the traceback.\n \"\"\"\n config.addinivalue_line(\n \"markers\", 'slow: marks tests as slow (deselect with -m \"not slow\")'\n )\n\n # show only the last line with the error message when displaying a\n # traceback\n if config.getoption(\"tbstyle\") == \"auto\":\n config.option.tbstyle = \"line\"\n\n\nclass TestCaseYamlModule(pytest.Module):\n \"\"\"Collector for tests defined with a yaml file.\"\"\"\n\n def _getobj(self):\n \"\"\"Override the base class method.\n\n To swap the yaml file with the test_case_yaml.py module.\n \"\"\"\n # prevent python from using the module cache, otherwise the module\n # object will be the same for all the tests\n del sys.modules[test_case_yaml.__name__]\n # backup the attribute before temporary override of it\n fspath = self.fspath\n self.fspath = py.path.local(test_case_yaml.__file__)\n module = self._importtestmodule()\n # restore the backuped up attribute\n self.fspath = fspath\n # set the test case marks from settings.yaml\n settings = _get_settings(self.config, fspath)\n # store the marks for settings them later\n if settings.marks:\n _marks_cache[fspath.dirname] = settings.marks\n return module\n\n\ndef pytest_exception_interact(node, call, report):\n \"\"\"Change exception display to only show the test path and error message.\n\n Avoid displaying the test file path and the Exception type.\n \"\"\"\n excinfo = call.excinfo\n if excinfo.typename == \"CollectError\" and str(excinfo.value).startswith(\n \"import file mismatch:\\n\"\n ):\n # handle when a custom test script is used in more than one test case with\n # the same name\n dirname = node.fspath.dirname\n filename = node.fspath.basename\n report.longrepr = (\n f\"{dirname}\\nshall have a __init__.py because {filename} \"\n \"exists in other directories\"\n )\n else:\n report.longrepr.reprcrash = f\"{report.nodeid}: {excinfo.value}\"\n\n\ndef pytest_collection_modifyitems(\n session: _pytest.main.Session,\n config: _pytest.config.Config,\n items: List[_pytest.nodes.Item],\n) -> None:\n \"\"\"Change the tests execution order.\n\n Such that:\n - the tests in parent directories are executed after the tests in children\n directories\n - in a test case directory, the yaml defined tests are executed before the\n others (to handle the output directory creation).\n \"\"\"\n items.sort(key=cmp_to_key(_sort_yaml_first))\n items.sort(key=cmp_to_key(_sort_parent_last))\n _set_marks(items)\n\n\ndef _sort_yaml_first(item_1: _pytest.nodes.Item, item_2: _pytest.nodes.Item) -> int:\n \"\"\"Sort yaml item first if in the same directory.\"\"\"\n path_1 = Path(item_1.fspath)\n path_2 = Path(item_2.fspath)\n if path_1.parent == path_2.parent and (path_1.suffix, path_2.suffix) == (\n \".yaml\",\n \".py\",\n ):\n return -1\n return 1\n\n\ndef _sort_parent_last(item_1: _pytest.nodes.Item, item_2: _pytest.nodes.Item) -> int:\n \"\"\"Sort item in parent directory last.\"\"\"\n dir_1 = Path(item_1.fspath).parent\n dir_2 = Path(item_2.fspath).parent\n if dir_2 in dir_1.parents:\n return -1\n return 1\n\n\ndef _set_marks(items: List[_pytest.nodes.Item]) -> None:\n \"\"\"Set the marks to the test functions under a test case.\"\"\"\n for dirname, marks in _marks_cache.items():\n for item in items:\n if item.fspath.dirname != dirname:\n continue\n for mark in marks:\n item.add_marker(mark)\n\n\ndef pytest_terminal_summary(\n terminalreporter: TerminalReporter, exitstatus: int, config: Config\n) -> None:\n \"\"\"Create the custom report.\n\n In the directory that contains the report generator, the report database is\n created and the report generator is called.\n \"\"\"\n # path to the report generator\n reporter_path = config.getoption(\"report_generator\")\n if reporter_path is None:\n return\n\n if not terminalreporter.stats:\n # no test have been run thus no report to create or update\n return\n\n output_root = Path(config.getoption(\"output_root\"))\n\n terminalreporter.write_sep(\"=\", \"starting report generation\")\n\n try:\n report.generate(reporter_path, output_root, terminalreporter)\n except Exception as e:\n terminalreporter.write_line(str(e), red=True)\n terminalreporter.write_sep(\"=\", \"report generation failed\", red=True)\n else:\n terminalreporter.write_sep(\"=\", \"report generation done\")\n","sub_path":"pytest_executable/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":14318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"300083641","text":"\"\"\"test task1B\n\"\"\"\n\nfrom FakeStations import list_of_fake\nfrom floodsystem.station import MonitoringStation\nfrom floodsystem.flood import stations_level_over_threshold, stations_highest_rel_level\n\ndef test_relative_water_level():\n\t\t\n\t#fake stations to be tested\n\tA = list_of_fake()\t\n\n\tB = []\n\tfor i in A:\n\t\t\n\t\tif i.relative_water_level() == None:\n\t\t\tB.append(i.relative_water_level())\n\n\t\telse:\n\t\t\tB.append(round(i.relative_water_level(), 5))\n\n\tassert B == [1.5, None, None, None, 1.35]\n\n\ndef test_stations_level_over_threshold():\n\n\t#fake stations to be tested\n\tA = list_of_fake()\n\n\tB = stations_level_over_threshold(A, 0.8)\n\t\n\tC = [(B[0][0].name, B[0][1]), (B[1][0].name, B[1][1])]\n\n\tassert C == [('A', 1.5), ('E', 1.35)]\n\n\ndef test_stations_highest_rel_level():\n\t\n\t#fake stations to be tested\n\tA = list_of_fake()\n\n\t#apply function stations_highest_rel_level\n\tB = stations_highest_rel_level(A, 5)\t\n\n\tC = [(B[0][0].name, B[0][1]), (B[1][0].name, B[1][1])]\n\n\tassert C == [('A', 1.5), ('E', 1.35)]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n","sub_path":"test_Task2BC.py","file_name":"test_Task2BC.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"316588032","text":"# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nStub functions that are used by the AWS Identity and Access Management (IAM) unit tests.\n\nWhen tests are run against an actual AWS account, the stubber class does not\nset up stubs and passes all calls through to the Boto 3 client.\n\"\"\"\n\nfrom datetime import datetime\nimport random\nimport string\nfrom botocore.stub import ANY\n\nfrom test_tools.example_stubber import ExampleStubber\n\n\ndef random_string(length):\n return ''.join([random.choice(string.ascii_lowercase) for _ in range(length)])\n\n\nclass IamStubber(ExampleStubber):\n \"\"\"\n A class that implements a variety of stub functions that are used by the\n IAM unit tests.\n\n The stubbed functions all expect certain parameters to be passed to them as\n part of the tests, and will raise errors when the actual parameters differ from\n the expected.\n \"\"\"\n def __init__(self, client, use_stubs=True):\n \"\"\"\n Initializes the object with a specific client and configures it for\n stubbing or AWS passthrough.\n\n :param client: A Boto 3 IAM client.\n :param use_stubs: When True, use stubs to intercept requests. Otherwise,\n pass requests through to AWS.\n \"\"\"\n super().__init__(client, use_stubs)\n\n @staticmethod\n def _add_role(response, role_name):\n response['Role'] = {\n 'RoleName': role_name,\n 'Path': '/',\n 'RoleId': random_string(16),\n 'Arn': random_string(20),\n 'CreateDate': datetime.now()\n }\n return response\n\n def stub_create_role(self, role_name, assume_role_policy=ANY, error_code=None):\n expected_params = {\n 'RoleName': role_name,\n 'AssumeRolePolicyDocument': assume_role_policy\n }\n\n if not error_code:\n self.add_response(\n 'create_role',\n expected_params=expected_params,\n service_response=self._add_role({}, role_name)\n )\n else:\n self.add_client_error(\n 'create_role',\n expected_params=expected_params,\n service_error_code=error_code\n )\n\n def stub_get_role(self, role_name, status_code=200, error_code=None):\n expected_params = {'RoleName': role_name}\n if not error_code:\n self.add_response(\n 'get_role',\n expected_params=expected_params,\n service_response=self._add_role({\n 'ResponseMetadata': {'HTTPStatusCode': status_code}\n }, role_name)\n )\n else:\n self.add_client_error(\n 'get_role',\n expected_params=expected_params,\n service_error_code=error_code\n )\n\n def stub_delete_role(self, role_name, error_code=None):\n self._stub_bifurcator(\n 'delete_role',\n expected_params={'RoleName': role_name},\n error_code=error_code)\n\n def stub_create_policy(self, policy_name, policy_arn, policy_document=ANY,\n error_code=None):\n expected_params = {\n 'PolicyName': policy_name,\n 'PolicyDocument': policy_document\n }\n if not error_code:\n self.add_response(\n 'create_policy',\n expected_params=expected_params,\n service_response={\n 'Policy': {\n 'PolicyName': policy_name,\n 'Arn': policy_arn\n }\n }\n )\n else:\n self.add_client_error(\n 'create_policy',\n expected_params=expected_params,\n service_error_code=error_code\n )\n\n def stub_get_policy(self, policy_arn, status_code=200, error_code=None):\n expected_params = {'PolicyArn': policy_arn}\n if not error_code:\n self.add_response(\n 'get_policy',\n expected_params=expected_params,\n service_response= {\n 'ResponseMetadata': {'HTTPStatusCode': status_code},\n 'Policy': {'PolicyName': policy_arn.split(':')[-1]}\n }\n )\n else:\n self.add_client_error(\n 'get_policy',\n expected_params=expected_params,\n service_error_code=error_code\n )\n \n def stub_delete_policy(self, policy_arn, error_code=None):\n self._stub_bifurcator(\n 'delete_policy',\n expected_params={'PolicyArn': policy_arn},\n error_code=error_code)\n\n def stub_attach_role_policy(self, role_name, policy_arn, error_code=None):\n expected_params = {\n 'RoleName': role_name,\n 'PolicyArn': policy_arn\n }\n if not error_code:\n self.add_response(\n 'attach_role_policy',\n expected_params=expected_params,\n service_response={}\n )\n else:\n self.add_client_error(\n 'attach_role_policy',\n expected_params=expected_params,\n service_error_code=error_code\n )\n\n def stub_list_attached_role_policies(self, role_name, policies=None,\n error_code=None):\n expected_params = {'RoleName': role_name}\n if not error_code:\n self.add_response(\n 'list_attached_role_policies',\n expected_params=expected_params,\n service_response={\n 'AttachedPolicies': [{\n 'PolicyName': name,\n 'PolicyArn': arn\n } for name, arn in policies.items()]\n }\n )\n else:\n self.add_client_error(\n 'list_attached_role_policies',\n expected_params=expected_params,\n service_error_code=error_code\n )\n\n def stub_detach_role_policy(self, role_name, policy_arn, error_code=None):\n self._stub_bifurcator(\n 'detach_role_policy',\n expected_params={'RoleName': role_name, 'PolicyArn': policy_arn},\n error_code=error_code\n )\n","sub_path":"python/test_tools/iam_stubber.py","file_name":"iam_stubber.py","file_ext":"py","file_size_in_byte":6417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"512322749","text":"import sys\nimport keras\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Conv2D, MaxPooling2D, Conv2DTranspose\nfrom keras.layers import Input, Conv3D, MaxPooling3D, Conv3DTranspose, BatchNormalization\nfrom keras.layers import concatenate, Reshape, Activation, Permute\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.backend.tensorflow_backend import set_session\n\ndef dice_coef(y_true, y_pred):\n smooth = 0.1\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\ndef dice_coef_loss(y_true, y_pred):\n return -dice_coef(y_true, y_pred)\n\ndef get_unet():\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n # config.gpu_options.allow_growth = False\n set_session(tf.Session(config=config))\n\n inputs = Input((512, 512, 16))\n\n conv1 = Conv2D(16, (3, 3), activation='relu', padding='same')(inputs)\n conv1 = Conv2D(16, (3, 3), activation='relu', padding='same')(conv1)\n conv1 = BatchNormalization()(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n conv2 = Conv2D(32, (3, 3), activation='relu', padding='same')(pool1)\n conv2 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv2)\n conv2 = BatchNormalization()(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool2)\n conv3 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv3)\n conv3 = BatchNormalization()(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = Conv2D(128, (3, 3), activation='relu', padding='same')(pool3)\n conv4 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv4)\n conv4 = BatchNormalization()(conv4)\n\n up5 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv4), conv3], axis=3)\n conv5 = Conv2D(64, (3, 3), activation='relu', padding='same')(up5)\n conv5 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv5)\n conv5 = BatchNormalization()(conv5)\n\n up6 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv5), conv2], axis=3)\n conv6 = Conv2D(32, (3, 3), activation='relu', padding='same')(up6)\n conv6 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv6)\n conv6 = BatchNormalization()(conv6)\n\n up7 = concatenate([Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv6), conv1], axis=3)\n conv7 = Conv2D(16, (3, 3), activation='relu', padding='same')(up7)\n conv7 = Conv2D(16, (3, 3), activation='relu', padding='same')(conv7)\n conv7 = BatchNormalization()(conv7)\n\n conv8 = Conv2D(1, (1, 1), activation='relu')(conv7)\n\n model = Model(inputs=[inputs], outputs=[conv8])\n model = keras.utils.multi_gpu_model(model, gpus=2)\n\n model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss)\n\n return model\n\nif __name__ == '__main__':\n model = get_unet()\n model.summary()\n","sub_path":"unet_3d.py","file_name":"unet_3d.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"206477293","text":"import requests\n\nresponse = requests.get('http://jservice.io/api/clues?').json()\n\nimport random\nscore = 0\nb=True\n#if any questions are blank, redo sample\nwhile b==True:\n choices = random.sample(response, 5)\n for x in choices:\n if b==True:\n if len(x['question'])<2:\n b = True\n else:\n b=False\n \npossible_choices = [1, 2, 3, 4, 5]\n#play game 3x\nfor x in range(3):\n category_string = \"Select a category \\n\"\n for y in range(len(choices)):\n # print(y)\n # print(choices[y])\n category_string += str(y+1) + \") \" + choices[y]['category']['title'] + \"\\n\"\n c=True\n while c==True:\n category = input(category_string)\n if int(category) in possible_choices:\n index=possible_choices.index(int(category))\n possible_choices.pop(index)\n c=False\n elif int(category) in range(1,6):\n print('you have already selected that choice')\n else:\n print(\"type the number of the answer choice\")\n question_object = choices[int(category)-1]\n # Now, get some user input after the question. If what they type matches the answer, print a \"congratulations!\" message of some sort. If it doesn't match, print a \"sorry\" message of some sort.\n a=True\n while a==True:\n answer = input(question_object['question'] + \"\\n\")\n if answer.lower() == question_object['answer'].lower():\n print(\"Congratulations!\")\n score += question_object['value']\n print(\"Your score is \" + str(score))\n a=False\n elif answer.lower() in question_object['answer'].lower():\n print(\"Your response is a part of the correct answer. Try again.\")\n else:\n print(\"Sorry, that's incorrect. The answer was \" + question_object['answer'])\n score -= question_object['value']\n print(\"Your score is \" + str(score))\n a=False\n","sub_path":"jeopardy.py","file_name":"jeopardy.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"225664598","text":"import numpy as np\nimport keras.datasets.cifar10 as cifar10\nimport keras.utils\n\nimport paperboy.sources.base.source as s\nimport paperboy.sources.base.tensor_source as ts\n\n\n# Constant for this dataset\nNUM_CLASSES = 10\n\n\ndef adjust_data(frame):\n \"\"\" Adjust MNIST x-data for the right format for neural nets \"\"\"\n return frame.astype(np.float32) / 255.0\n\n\ndef create(batch_size, subtract_pixel_mean=False):\n \"\"\" Create a simple data source returning a CIFAR10 dataset \"\"\"\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n x_train = adjust_data(x_train)\n x_test = adjust_data(x_test)\n\n if subtract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\n y_train = keras.utils.to_categorical(y_train, NUM_CLASSES)\n y_test = keras.utils.to_categorical(y_test, NUM_CLASSES)\n\n train_source = ts.TensorSource(x_train, y_train, batch_size=batch_size)\n test_source = ts.TensorSource(x_test, y_test, batch_size=batch_size)\n\n return s.Source(\n train_source, test_source,\n train_steps=x_train.shape[0] // batch_size,\n val_steps=x_test.shape[0] // batch_size,\n x_train=x_train,\n y_train=y_train,\n x_val=x_test,\n y_val=y_test\n )\n\n","sub_path":"paperboy/sources/keras/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"643026660","text":"import os\n\nimport numpy as np\nimport torch\nfrom imageio import imwrite\nfrom pycocotools import mask as cocomask\nfrom pycocotools.coco import COCO\nfrom skimage.transform import resize\nfrom tqdm import tqdm\n\nfrom utils import get_logger\n\nlogger = get_logger()\n\n\ndef overlay_masks(data_dir, dataset, target_dir, is_small=False):\n if is_small:\n suffix = \"-small\"\n else:\n suffix = \"\"\n annotation_file_name = \"annotation{}.json\".format(suffix)\n annotation_file_path = os.path.join(data_dir, dataset, annotation_file_name)\n coco = COCO(annotation_file_path)\n image_ids = coco.getImgIds()\n for image_id in tqdm(image_ids):\n image = coco.loadImgs(image_id)[0]\n image_size = [image[\"height\"], image[\"width\"]]\n annotation_ids = coco.getAnnIds(imgIds=image_id)\n annotations = coco.loadAnns(annotation_ids)\n mask = overlay_masks_from_annotations(annotations, image_size)\n target_filepath = os.path.join(target_dir, dataset, \"masks\", image[\"file_name\"][:-4]) + \".png\"\n os.makedirs(os.path.dirname(target_filepath), exist_ok=True)\n try:\n imwrite(target_filepath, mask)\n except:\n logger.info(\"Failed to save image: {}\".format(image_id))\n\n\ndef overlay_masks_from_annotations(annotations, image_size):\n mask = np.zeros(image_size)\n for ann in annotations:\n rle = cocomask.frPyObjects(ann['segmentation'], image_size[0], image_size[1])\n m = cocomask.decode(rle)\n m = m.reshape(image_size)\n mask += m\n return (255 * (mask > 0)).astype('uint8')\n\n\ndef preprocess_image(img, target_size=(128, 128)):\n img = resize(img, target_size, mode='constant')\n x = np.expand_dims(img, axis=0)\n x = x.transpose(0, 3, 1, 2)\n x = torch.FloatTensor(x)\n if torch.cuda.is_available():\n x = torch.autograd.Variable(x, volatile=True).cuda()\n else:\n x = torch.autograd.Variable(x, volatile=True)\n return x\n","sub_path":"preparation.py","file_name":"preparation.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"337645549","text":"import sys\nfrom typing import Dict\n\nimport pytest\nimport requests\n\nfrom ray._private.test_utils import wait_for_condition\nfrom ray.serve.config import DeploymentMode\nfrom ray.serve.tests.conftest import * # noqa: F401 F403\nfrom ray.serve.schema import ServeInstanceDetails\nfrom ray.serve._private.common import ApplicationStatus, DeploymentStatus\n\nGET_OR_PUT_URL_V2 = \"http://localhost:52365/api/serve/applications/\"\n\n\ndef deploy_config_multi_app(config: Dict):\n put_response = requests.put(GET_OR_PUT_URL_V2, json=config, timeout=30)\n assert put_response.status_code == 200\n print(\"PUT request sent successfully.\")\n\n\n@pytest.mark.skipif(sys.platform == \"darwin\", reason=\"Flaky on OSX.\")\ndef test_get_serve_instance_details(ray_start_stop):\n \"\"\"\n This test is a simplified version of `test_get_serve_instance_details`\n in test_serve_agent.py because the behavior in serve_head just proxies\n to the serve_agent endpoint.\n \"\"\"\n grpc_port = 9001\n grpc_servicer_functions = [\n \"ray.serve.generated.serve_pb2_grpc.add_UserDefinedServiceServicer_to_server\",\n \"ray.serve.generated.serve_pb2_grpc.add_FruitServiceServicer_to_server\",\n ]\n world_import_path = \"ray.serve.tests.test_config_files.world.DagNode\"\n fastapi_import_path = \"ray.serve.tests.test_config_files.fastapi_deployment.node\"\n config1 = {\n \"proxy_location\": \"HeadOnly\",\n \"http_options\": {\n \"host\": \"127.0.0.1\",\n \"port\": 8005,\n },\n \"grpc_options\": {\n \"port\": grpc_port,\n \"grpc_servicer_functions\": grpc_servicer_functions,\n },\n \"applications\": [\n {\n \"name\": \"app1\",\n \"route_prefix\": \"/app1\",\n \"import_path\": world_import_path,\n \"deployments\": [\n {\n \"name\": \"f\",\n \"ray_actor_options\": {\"num_cpus\": 0.2},\n },\n ],\n },\n {\n \"name\": \"app2\",\n \"route_prefix\": \"/app2\",\n \"import_path\": fastapi_import_path,\n },\n ],\n }\n\n deploy_config_multi_app(config1)\n\n def applications_running():\n response = requests.get(GET_OR_PUT_URL_V2, timeout=15)\n assert response.status_code == 200\n\n serve_details = ServeInstanceDetails(**response.json())\n return (\n serve_details.applications[\"app1\"].status == ApplicationStatus.RUNNING\n and serve_details.applications[\"app2\"].status == ApplicationStatus.RUNNING\n )\n\n wait_for_condition(applications_running, timeout=15)\n print(\"All applications are in a RUNNING state.\")\n\n serve_details = ServeInstanceDetails(\n **requests.get(\"http://localhost:8265/api/serve_head/applications/\").json()\n )\n # CHECK: proxy location, HTTP host, and HTTP port\n assert serve_details.http_options.host == \"127.0.0.1\"\n assert serve_details.http_options.port == 8005\n assert serve_details.proxy_location == DeploymentMode.HeadOnly\n print(\n 'Confirmed fetched HTTP host and HTTP port metadata are \"127.0.0.1\" and '\n '\"8005\".'\n )\n\n # CHECK: gRPC port and grpc_servicer_functions\n assert serve_details.grpc_options.port == grpc_port\n assert serve_details.grpc_options.grpc_servicer_functions == grpc_servicer_functions\n\n app_details = serve_details.applications\n\n # CHECK: app configs are equal\n assert (\n app_details[\"app1\"].deployed_app_config.dict(exclude_unset=True)\n == config1[\"applications\"][0]\n )\n assert (\n app_details[\"app2\"].deployed_app_config.dict(exclude_unset=True)\n == config1[\"applications\"][1]\n )\n print(\"Confirmed the deployed app configs from the fetched metadata is correct.\")\n\n # CHECK: deployment timestamp\n assert app_details[\"app1\"].last_deployed_time_s > 0\n assert app_details[\"app2\"].last_deployed_time_s > 0\n print(\"Confirmed deployment timestamps are nonzero.\")\n\n # CHECK: docs path\n assert app_details[\"app1\"].docs_path is None\n assert app_details[\"app2\"].docs_path == \"/my_docs\"\n print(\"Confirmed docs paths are correct.\")\n\n # CHECK: all deployments are present\n assert app_details[\"app1\"].deployments.keys() == {\"f\", \"BasicDriver\"}\n assert app_details[\"app2\"].deployments.keys() == {\"FastAPIDeployment\"}\n print(\"Metadata for all deployed deployments are present.\")\n\n # CHECK: application details\n for app in [\"app1\", \"app2\"]:\n assert app_details[app].route_prefix == f\"/{app}\"\n for dep_details in app_details[app].deployments.values():\n assert dep_details.status == DeploymentStatus.HEALTHY\n\n # Route prefix should be app level options eventually\n assert \"route_prefix\" not in dep_details.deployment_config.dict(\n exclude_unset=True\n )\n print(\"Finished checking application details.\")\n\n\nif __name__ == \"__main__\":\n sys.exit(pytest.main([\"-v\", __file__]))\n","sub_path":"dashboard/modules/serve/tests/test_serve_head.py","file_name":"test_serve_head.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"641374683","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom datascience import *\nimport numpy as np\nimport re\nimport gensim\n\nfrom collections import Counter\n\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)\nlogging.root.level = logging.CRITICAL \n\nimport warnings\nwarnings.filterwarnings(\"ignore\",category=DeprecationWarning)\n\n# direct plots to appear within the cell, and set their style\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plots\nplots.style.use('fivethirtyeight')\n\n\n# In[2]:\n\n\nfilename = \"https://s3.amazonaws.com/sds171/labs/lab07/ted_talks.csv\"\ndata = Table.read_table(filename)\n\ntranscripts = data.column('transcript')\n\n\n# In[3]:\n\n\n#Using regular expression to clean the data\ntranscripts = [re.sub('-', ' ', plot) for plot in transcripts]\ntranscripts = [re.sub('[^\\w\\s]', '', plot) for plot in transcripts]\ntranscripts = [re.sub('[A-Z]\\w*', '', plot) for plot in transcripts]\ntranscripts = [re.sub('[ ]+', ' ', plot) for plot in transcripts]\n\n\n# In[4]:\n\n\ndef is_numeric(string):\n for char in string:\n if char.isdigit():\n return True\n return False\n\ndef has_poss_contr(string):\n for i in range(len(string) - 1):\n if string[i] == '\\'' and string[i+1] == 's':\n return True\n return False\n\ndef empty_string(string):\n return string == ''\n\ndef remove_string(string):\n return is_numeric(string) | has_poss_contr(string) | empty_string(string)\n\n\n# In[5]:\n\n\n#Tokenize\nplots_tok = []\nfor plot in transcripts:\n processed = plot.lower().strip().split(' ')\n plots_tok.append(processed)\n\n#Removing numeric, posessives/contractions, and empty strings\ntemp = []\nfor plot in plots_tok:\n filtered = []\n for token in plot:\n if not remove_string(token):\n filtered.append(token)\n temp.append(filtered)\nplots_tok = temp\n\n\n# In[6]:\n\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nnltk.download('wordnet')\n\n#Lemmatizing the tokens \nlemmatizer = WordNetLemmatizer()\n\ntemp = []\nfor plot in plots_tok:\n processed = []\n for token in plot:\n processed.append(lemmatizer.lemmatize(token, pos='v'))\n temp.append(processed)\nplots_tok = temp\n\n\n# In[7]:\n\n\n#Creating the Counter\nvocab = Counter()\nfor plot in plots_tok:\n vocab.update(plot)\n\nprint(\"Number of unique tokens: %d\" % len(vocab))\n\n\n# In[8]:\n\n\n#Keeping tokens that appear more than 20 times \ntokens = []\nfor token in vocab.elements():\n if vocab[token] > 20:\n tokens.append(token)\nvocab = Counter(tokens)\n\nprint(\"Number of unique tokens: %d\" % len(vocab))\n\n\n# In[9]:\n\n\n#Removing rare and stop words\nstop_words = []\nfor item in vocab.most_common(200):\n stop_word = item[0]\n stop_words.append(stop_word)\ntokens = []\nfor token in vocab.elements():\n if token not in stop_words:\n tokens.append(token)\nvocab = Counter(tokens)\n\nprint(\"Number of unique tokens: %d\" % len(vocab))\n\n\n# In[10]:\n\n\n#Creating the identifier mappings word2id and id2word\nitems = vocab.items()\nid2word = {}\nword2id = {}\nidx = 0\nfor word, count in vocab.items():\n id2word[idx] = word\n word2id[word] = idx\n idx += 1\n \nprint(\"Number of tokens mapped: %d\" % len(id2word))\nprint(\"Identifier for 'photograph': %d\" % word2id['photograph'])\nprint(\"Word for identifier %d: %s\" % (word2id['photograph'], id2word[word2id['photograph']]))\n\n\n# In[11]:\n\n\n#Filtering the tokens \ntemp = []\nfor plot in plots_tok:\n filtered = []\n for token in plot:\n if token in vocab:\n filtered.append(token)\n temp.append(filtered)\nplots_tok = temp\n\n\n# In[12]:\n\n\n#Creating the Corpus\nsample = 30\ncorpus = []\nfor plot in plots_tok:\n plot_count = Counter(plot)\n corpus_doc = []\n for item in plot_count.items():\n pair = (word2id[item[0]], item[1])\n corpus_doc.append(pair)\n corpus.append(corpus_doc)\n\nprint(\"Plot, tokenized:\\n\", plots_tok[sample], \"\\n\")\nprint(\"Plot, in corpus format:\\n\", corpus[sample])\n\n\n# In[13]:\n\n\nget_ipython().run_cell_magic('time', '', \"lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,\\n id2word=id2word,\\n num_topics=10, \\n random_state=100,\\n update_every=1,\\n chunksize=100,\\n passes=10,\\n alpha='auto',\\n per_word_topics=True)\")\n\n\n# In[14]:\n\n\nnum_topics = 10\nnum_words = 15\ntop_words = Table().with_column('word rank', np.arange(1,num_words+1))\nfor k in np.arange(num_topics): \n topic = lda_model.get_topic_terms(k, num_words)\n words = [id2word[topic[i][0]] for i in np.arange(num_words)]\n probs = [topic[i][1] for i in np.arange(num_words)]\n top_words = top_words.with_column('topic %d' % k, words)\n \ntop_words.show()\n\n\n# In[15]:\n\n\nsample = 13\ntopic_dist = lda_model.get_document_topics(corpus[sample], minimum_probability = 0)\ntopics = [pair[0] for pair in topic_dist] \nprobabilities = [pair[1] for pair in topic_dist]\ntopic_dist_table = Table().with_columns('Topic', topics, 'Probabilities', probabilities)\ntopic_dist_table.show(20)\nt = np.argmax(probabilities)\nprint(\"Topic with highest probability: %d (%f)\" % (t, probabilities[t]))\n\n\n# In[16]:\n\n\nprint(transcripts[sample][0:2500])\n\n\n# In this example, Topic 7, which represents technology, has the highest probability with .646. Looking at the transcript of the talk, we see that this is in fact true. In the transcript of this sample, we see terms like \"screensaver\", \"touch sensor\", and \"interactive\".\n\n# In[17]:\n\n\nsample = 7\ntopic_dist = lda_model.get_document_topics(corpus[sample], minimum_probability = 0)\nprobabilities = [pair[1] for pair in topic_dist]\ntopics = [pair[0] for pair in topic_dist]\ntopic_dist_table = Table().with_columns('Topic', topics, 'Probabilities', probabilities)\ntopic_dist_table.show(20)\nt = np.argmax(probabilities)\nprint(\"Topic with highest probability: %d (%f)\" % (t, probabilities[t]))\n\n\n# In[18]:\n\n\nprint(transcripts[sample][0:2500])\n\n\n# In this sample, we observe that topic 8, which represents art, has the highest probability with .51. Looking at the transcript, we can see that our topic model is correct since there are terms like \"modernists\", \"design\", and \"diagram\".\n\n# In[19]:\n\n\nsample = 31\ntopic_dist = lda_model.get_document_topics(corpus[sample], minimum_probability = 0)\nprobabilities = [pair[1] for pair in topic_dist]\ntopics = [pair[0] for pair in topic_dist]\ntopic_dist_table = Table().with_columns('Topic', topics, 'Probabilities', probabilities)\ntopic_dist_table.show(20)\nt = np.argmax(probabilities)\nprint(\"Topic with highest probability: %d (%f)\" % (t, probabilities[t]))\n\n\n# In[20]:\n\n\nprint(transcripts[sample][0:2500])\n\n\n# The topic with the highest probability of .64 is topic 4, which represents medicine. Looking at the transcript of the talk, we observe that our topic model was able to correctly identify the topic at hand. Terms like \"cancer\", \"medical\", and \"research\" were all used in this TED talk.\n","sub_path":"TED Talk Topic Model.py","file_name":"TED Talk Topic Model.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"612086293","text":"\"\"\"Module containing file system sensors.\"\"\"\n\nfrom airflow.sensors.base_sensor_operator import BaseSensorOperator\nfrom airflow.utils.decorators import apply_defaults\n\nfrom .hooks import MovielensHook\n\n\nclass MovielensRatingsSensor(BaseSensorOperator):\n \"\"\"\n Sensor that waits for the Movielens API to have ratings for a time period.\n\n start_date : str\n (Templated) start date of the time period to check for (inclusive).\n Expected format is YYYY-MM-DD (equal to Airflow's ds formats).\n end_date : str\n (Templated) end date of the time period to check for (exclusive).\n Expected format is YYYY-MM-DD (equal to Airflow's ds formats).\n \"\"\"\n\n template_fields = (\"_start_date\", \"_end_date\")\n\n @apply_defaults\n def __init__(self, conn_id, start_date=\"{{ds}}\", end_date=\"{{next_ds}}\", **kwargs):\n super().__init__(**kwargs)\n self._conn_id = conn_id\n self._start_date = start_date\n self._end_date = end_date\n\n # pylint: disable=unused-argument,missing-docstring\n def poke(self, context):\n hook = MovielensHook(self._conn_id)\n\n try:\n next(\n hook.get_ratings(\n start_date=self._start_date, end_date=self._end_date, batch_size=1\n )\n )\n # If no StopIteration is raised, the request returned at least one record.\n # This means that there are records for the given period, which we indicate\n # to Airflow by returning True.\n self.log.info(\n f\"Found ratings for {self._start_date} to {self._end_date}, continuing!\"\n )\n return True\n except StopIteration:\n self.log.info(\n f\"Didn't find any ratings for {self._start_date} \"\n f\"to {self._end_date}, waiting...\"\n )\n # If StopIteration is raised, we know that the request did not find\n # any records. This means that there a no ratings for the time period,\n # so we should return False.\n return False\n finally:\n # Make sure we always close our hook's session.\n hook.close()\n","sub_path":"apache-airflow/materials/data-pipelines-with-apache-airflow-master/chapters/chapter7/src/airflow-movielens/src/airflow_movielens/sensors.py","file_name":"sensors.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"568847215","text":"\n# Hydraulic Properties\n# --------------------\n\n# Generic sand\n# ------------\n# Page 85, C.W. Fetter, average HK of well-sorted sands; 1 cm/s = 2835 ft/day\n# kx_sand = 10.e-2 * 2835.\n# Average HK of surficial aquifer system in SW Fla. reported by Knochenmus (2006, pg. 11)\nkx_sand = 62.\nkz_sand = kx_sand * .1\n\n\n# Generic clay\n# ------------\n# Page 85, C.W. Fetter, average HK of clay, fine sands; 1 cm/s = 2835 ft/day\nkx_clay = 10.e-8 * 2835.\nkz_clay = kx_clay*.01\n\n\n# Generic limestone\n# -----------------\n# Page 764, Langevin (2003), HK zone 1\n# kx_lmsn = 9000./3.2808\nkx_lmsn = 500. # Arbitrary.\nkz_lmsn = kx_lmsn*.1\n\n\n# Generic tight limestone\n# -----------------------\nkx_lmsn_tight = kx_lmsn*.01\nkz_lmsn_tight = kz_lmsn*.01\n\n\n# Generic cavernous limestone\n# ---------------------------\nkx_lmsn_cvrn = kx_lmsn*10.\nkz_lmsn_cvrn = kx_lmsn_cvrn # Assume isotropic conditions\n\n\n# Generic fractured limestone\n# ---------------------------\nkz_lmsn_frac = kx_lmsn_cvrn # Assume isotropic conditions\n\n\n# Intermediate aquifer system\n# ---------------------------\n# Values as reported by Knochenmus (2006, pg. 35-36)\n# kx_ias = kx_lmsn*.01\nkx_ias = kx_lmsn\n\n\n# Sand and gravel aquifer\n# -----------------------\n# Franks (1988) notes that the calibrated K values for model layers 1 and 2 was varied over the entire\n# likely range of values (9-27 m/d) (pg. 50). Model fit was poor, likely owing to local heterogeneities\n# and the model was found to be highly sensitive to leakace between layers 1 and 2. The final calibrated\n# conductivity value used for layer 3 (main production zone) was 30 m/d (pg. 50).\nkx_sandgrav = ((980/20) * 3.2808) # Franks (1988) used 980 m2/d (pg. 48) for production zone T (20m thick, pg. 29)\nkz_sandgrav = kx_sandgrav * .1\n","sub_path":"props.py","file_name":"props.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"345635321","text":"from unittest import TestCase\nfrom i_love_lance_janice import answer\n\n\nclass TestILoveLanceJanice(TestCase):\n known_cases = ((\"wrw blf hvv ozhg mrtsg'h vkrhlwv?\",\n \"did you see last night's episode?\"),\n (\"Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!\",\n \"Yeah! I can't believe Lance lost his job at the colony!!\"))\n\n def test_answer(self):\n for coded, decoded in self.known_cases:\n self.assertEqual(answer(coded), decoded)\n","sub_path":"test_i_love_lance_janice.py","file_name":"test_i_love_lance_janice.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"378969393","text":"# Copyright (c) 2023, NVIDIA CORPORATION. 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\nimport gc\nimport logging\nimport os\nimport json\nimport warnings\nfrom typing import Optional, Union, Tuple\n\nimport cudf\nimport dask_cudf\nimport numpy as np\nimport pandas as pd\nimport dask.dataframe as dd\n\n\nfrom syngen.utils import LocalCudaClusterManager\nfrom syngen.generator.graph import RandomGraph, RandomBipartite\nfrom syngen.generator.tabular.random import RandomMVGenerator\nfrom syngen.synthesizer.base_synthesizer import BaseSynthesizer\nfrom syngen.utils.gen_utils import (\n chunk_sample_generation,\n dump_generated_graph_to_txt,\n merge_csv_files,\n read_edge_list\n)\nfrom syngen.utils.df_reader import DFReader\nfrom syngen.utils.types import MetaData\nfrom syngen.utils.utils import CustomTimer, df_to_pandas, get_object_path\n\nlogger = logging.getLogger(__name__)\nlog = logger\n\nwarnings.filterwarnings('ignore')\n\n\nclass RandomSynthesizer(BaseSynthesizer):\n \"\"\"A random graph synthesizer. It Supports generating graphs with edge features,\n node features, or both. This synthesizer does not require data for fitting, and\n generated static graphs with arbitrary number of nodes, edges, and feature dimensions.\n\n Args:\n bipartite (bool): flag to specify whether the generated graph should be bipartite.\n is_directed (bool): flag to specify if the edges of the generated graph should be directed\n save_path (str): path to the directory where the results will be saved\n features_save_name (str): save file name for the features (default: \"features.csv\").\n edge_list_save_name (str): save file name for the edge list (default: \"edge_list.txt\").\n graph_save_name (str): save file name for the final graph (default: \"graph.csv\").\n timer_path (str): path to save the timing information of the synthesizer (default: None).\n num_workers (int): number of workers to speed up generation using multiprocessing\n gpu (bool): flag to use GPU graph generator (default: True ), if set to False CPU will be used.\n use_dask (bool): flag to use dask, useful for large tables/graphs.\n \"\"\"\n\n def __init__(\n self,\n *,\n bipartite: bool = False,\n is_directed: bool = True,\n save_path: str = \"./\",\n features_save_name: str = \"feature.csv\",\n edge_list_save_name: str = \"edge_list.txt\",\n graph_save_name: str = \"graph.csv\",\n timer_path: Optional[str] = None,\n num_workers: int = 1,\n gpu: bool = True,\n use_dask: bool = False,\n **kwargs,\n ):\n self.bipartite = bipartite\n self.is_directed = is_directed\n if self.bipartite:\n self.graph_generator = RandomBipartite()\n else:\n self.graph_generator = RandomGraph()\n self.edge_feature_generator = None\n self.node_feature_generator = None\n self.save_path = save_path\n self.num_workers = num_workers\n\n if not os.path.exists(self.save_path):\n os.makedirs(self.save_path)\n\n self.features_save_name = features_save_name\n self.edge_list_save_name = edge_list_save_name\n self.graph_save_name = graph_save_name\n self.timer = CustomTimer(timer_path)\n self.gpu = gpu\n self.use_dask = use_dask\n\n if self.use_dask:\n self.dask_cluster = LocalCudaClusterManager()\n self.dask_cluster.initialize_local_cluster()\n\n if gpu:\n self.setup_gpu()\n else:\n self.setup_cpu()\n\n def setup_gpu(self):\n self.graph_generator.gpu = True\n\n def setup_cpu(self):\n self.graph_generator.gpu = False\n\n def fit(\n self,\n edge_dim: Optional[int] = None,\n node_dim: Optional[int] = None,\n *args,\n **kwargs,\n ):\n \"\"\"Fit the random synthesizer. A `RandomMVGenerator` is instantiated for either\n edge features as specified by `edge_dim` and node features specified by `node_dim`.\n The generated features follow a random multivariate gaussian distribution.\n\n Args:\n edge_dim (int): the dimension of edge features (default: None).\n node_dim (int): the dimension of node features (default: None)\n \"\"\"\n self.graph_generator.fit(is_directed=self.is_directed)\n if edge_dim is not None:\n self.edge_feature_generator = RandomMVGenerator()\n self.edge_feature_generator.fit(ndims=edge_dim)\n if node_dim is not None:\n self.node_feature_generator = RandomMVGenerator()\n self.node_feature_generator.fit(ndims=node_dim)\n\n def generate(\n self,\n num_nodes: Optional[int] = None,\n num_edges: Optional[int] = None,\n num_nodes_src_set: Optional[int] = None,\n num_nodes_dst_set: Optional[int] = None,\n num_edges_src_dst: Optional[int] = None,\n num_edges_dst_src: Optional[int] = None,\n batch_size_graph: int = 1_000_000,\n batch_size_tabular: int = 1_000,\n graph_noise: float = 0.5,\n has_self_loop: bool = False,\n *args,\n **kwargs,\n ):\n \"\"\" Generate a graph with `num_nodes` and `num_edges`,\n\n Args:\n If `bipartite` is set to false:\n num_nodes (Optional[int]): approximate number of nodes to be generated must be provided\n num_edges (Optional[int]): approximate number of edges to be generated must be provided\n If `bipartite` is set to true:\n num_nodes_src_set (Optional[int]): approximate number of nodes in the source set must be provided\n num_nodes_dst_set (Optional[int]): approximate number of nodes in the destination set must be provided\n num_edges_src_dst (Optional[int]): approximate number of edges from source to destination must be provided\n num_edges_dst_src (Optional[int]): approximate number of edges from destination to source must be provided\n batch_size_graph (int): size of the edge chunk that will be\n generated in one generation step (default: 1_000_000).\n batch_size_tabular (int): batch size for the tabular feature generator (default: 1_000).\n graph_noise (float): graph noise param for generation (default: 0.5).\n has_self_loop (bool): set to true if graph should have self loops (default: False).\n \"\"\"\n log.info(\"Generating graph...\")\n if self.bipartite:\n self.timer.start_counter(\"gen_s\")\n graph = self.graph_generator.generate(\n num_nodes_src_set=num_nodes_src_set,\n num_nodes_dst_set=num_nodes_dst_set,\n num_edges_src_dst=num_edges_src_dst,\n num_edges_dst_src=num_edges_dst_src,\n is_directed=self.is_directed,\n batch_size=batch_size_graph,\n )\n self.timer.end_counter(\"gen_s\", \"GEN STRUCT TOOK\")\n else:\n # - generate static graph\n self.timer.start_counter(\"gen_s\")\n graph = self.graph_generator.generate(\n num_nodes=num_nodes,\n num_edges=num_edges,\n is_directed=self.is_directed,\n has_self_loop=has_self_loop,\n noise=graph_noise,\n batch_size=batch_size_graph,\n )\n self.timer.end_counter(\"gen_s\", \"GEN STRUCT TOOK\")\n\n if not self.is_directed:\n # - rid of duplicate edges\n graph = list(set(map(frozenset, graph)))\n graph = np.asarray(list(map(list, graph)))\n\n # - dump edge list\n generated_graph_path = os.path.join(\n self.save_path, self.edge_list_save_name\n )\n nodes = set(list(graph[:, 0]) + list(graph[:, 1]))\n nodes_map = dict(zip(nodes, list(range(len(nodes)))))\n graph = np.asarray(\n [np.asarray([nodes_map[g[0]], nodes_map[g[1]]]) for g in graph]\n )\n dump_generated_graph_to_txt(generated_graph_path, graph)\n num_nodes = len(nodes_map)\n num_edges = len(graph)\n graph = None\n nodes_map = None\n nodes = None\n gc.collect()\n\n edge_features_save_name = \"edge_\" + self.features_save_name\n node_features_save_name = \"node_\" + self.features_save_name\n # - generate features\n self.timer.start_counter(\"gen_t\")\n if self.edge_feature_generator is not None:\n generated_files = chunk_sample_generation(\n self.edge_feature_generator,\n n_samples=num_edges,\n save_path=self.save_path,\n fname=\"table_edge_samples\",\n num_workers=self.num_workers,\n )\n merge_csv_files(\n file_paths=generated_files,\n save_path=self.save_path,\n save_name=edge_features_save_name,\n )\n if self.node_feature_generator is not None:\n generated_files = chunk_sample_generation(\n self.node_feature_generator,\n n_samples=num_nodes,\n save_path=self.save_path,\n fname=\"table_node_samples\",\n num_workers=self.num_workers,\n )\n merge_csv_files(\n file_paths=generated_files,\n save_path=self.save_path,\n save_name=node_features_save_name,\n )\n self.timer.end_counter(\"gen_t\", \"GEN FEATURE TOOK\")\n\n # - align graph + features\n node_generated_df = None\n edge_generated_df = None\n reader = (\n DFReader.get_dask_reader() if self.use_dask else DFReader.get_df_reader()\n )\n if os.path.exists(os.path.join(self.save_path, edge_features_save_name)):\n generated_table_path = os.path.join(\n self.save_path, edge_features_save_name\n )\n edge_generated_df = reader.read_csv(generated_table_path)\n\n if os.path.exists(os.path.join(self.save_path, node_features_save_name)):\n generated_table_path = os.path.join(\n self.save_path, node_features_save_name\n )\n node_generated_df = reader.read_csv(generated_table_path)\n\n generated_graph_el_df = read_edge_list(\n generated_graph_path,\n reader=\"dask_cudf\" if self.use_dask else \"cudf\",\n )\n data = {}\n if node_generated_df is not None:\n data[MetaData.NODE_DATA] = df_to_pandas(node_generated_df)\n\n if edge_generated_df is not None:\n el_df = df_to_pandas(generated_graph_el_df)\n ef_df = df_to_pandas(edge_generated_df)\n edge_data = pd.concat([el_df, ef_df], axis=1)\n data[MetaData.EDGE_DATA] = edge_data\n elif generated_graph_el_df is not None:\n data[MetaData.EDGE_DATA] = df_to_pandas(generated_graph_el_df)\n\n # - dump generated data\n for k, v in data.items():\n if isinstance(v, (cudf.DataFrame, pd.DataFrame)):\n data_df_save_path = os.path.join(\n self.save_path, f\"{k}_{self.graph_save_name}\"\n )\n v.to_csv(data_df_save_path, index=False)\n if isinstance(v, (dask_cudf.DataFrame, dd.DataFrame)):\n data_df_save_path = os.path.join(\n self.save_path, f\"{k}_*_{self.graph_save_name}\"\n )\n v = v.compute()\n v.to_csv(data_df_save_path, index=False)\n\n return data\n\n @staticmethod\n def add_args(parser):\n parser.add_argument(\n \"--edge-dim\",\n type=int,\n default=None,\n help=\"Edge feature dimension to generate using RandomSynthesizer.\",\n )\n parser.add_argument(\n \"--node-dim\",\n type=int,\n default=None,\n help=\"Node feature dimension to generate using RandomSynthesizer.\",\n )\n parser.add_argument(\n \"--g-bipartite\",\n default=False,\n action='store_true',\n help=\"Generates bipartite graph, flag used in RandomSynthesizer.\",\n )\n parser.add_argument(\n \"--g-directed\",\n default=False,\n action='store_true',\n help=\"Generates directed graph, flag used in RandomSynthesizer.\",\n )\n return parser\n\n def cleanup_session(self):\n \"\"\"clean up session and free up resources\n \"\"\"\n if self.use_dask:\n self.dask_cluster.destroy_local_cluster()\n\n @classmethod\n def load(cls, path):\n with open(os.path.join(path, \"synthesizer_metadata.json\"), \"r\") as fp:\n meta_data = json.load(fp)\n instance = cls(**meta_data)\n instance.graph_generator.fit(is_directed=instance.is_directed)\n if os.path.exists(os.path.join(path, 'node_feature_generator')):\n instance.node_feature_generator = RandomMVGenerator.load(os.path.join(path, 'node_feature_generator'))\n if os.path.exists(os.path.join(path, 'edge_feature_generator')):\n instance.edge_feature_generator = RandomMVGenerator.load(os.path.join(path, 'edge_feature_generator'))\n return instance\n\n def save(self, path):\n meta_data = {\n \"bipartite\": self.bipartite,\n \"is_directed\": self.is_directed,\n \"save_path\": self.save_path,\n \"features_save_name\": self.features_save_name,\n \"edge_list_save_name\": self.edge_list_save_name,\n \"graph_save_name\": self.graph_save_name,\n \"timer_path\": self.timer.path,\n \"num_workers\": self.num_workers,\n \"gpu\": self.gpu,\n \"use_dask\": self.use_dask,\n }\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n if self.edge_feature_generator is not None:\n self.edge_feature_generator.save(os.path.join(path, 'edge_feature_generator'))\n if self.node_feature_generator is not None:\n self.node_feature_generator.save(os.path.join(path, 'node_feature_generator'))\n with open(os.path.join(path, \"synthesizer_metadata.json\"), \"w\") as fp:\n json.dump(meta_data, fp)\n","sub_path":"Tools/DGLPyTorch/SyntheticGraphGeneration/syngen/synthesizer/random_synthesizer.py","file_name":"random_synthesizer.py","file_ext":"py","file_size_in_byte":14790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"584905982","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nimport seaborn as sb\n\nget_ipython().magic(u'matplotlib inline')\nsb.set_style('darkgrid')\n\npath = \"data/data.csv\"\ndata = pd.read_csv(path)\ndata['dump_time'] = pd.to_datetime(data['dump_time'])\ndata = data.set_index('dump_time')\ndata['date'] = data.index.date\ndata['weekofyear'] = data.index.weekofyear\n\n\n# In[2]:\n\nbuildings = {}\nfor i in range(1000):\n row = data.iloc[i]\n bldg, floor = row['parent_name'], row['group_name']\n if bldg not in buildings:\n buildings[bldg] = set([floor])\n \n else:\n buildings[bldg].add(floor)\n\n\n# In[3]:\n\nbuildings\n\n\n# In[4]:\n\ndef floor_plot(*args, **kwargs):\n group = kwargs.pop('group', None)\n group_word = {None:\"\", \"week\":\"Weekly \", \"day\":\"Daily \"}\n start_date = kwargs.pop('start', \"20140630\")\n end_date = kwargs.pop('end', \"20150419\")\n \n building = kwargs.pop('building', '')\n if building != \"\":\n building += \" \"\n \n floor = args[0]\n floors = set(args[1:])\n floor_data = data[data['group_name'] == floor][['client_count', 'date', 'weekofyear']]\n floor_data = floor_data.rename(columns={'client_count':floor})\n for floor in floors:\n floor_data[floor] = data[data['group_name'] == floor]['client_count']\n \n floors.add(floor)\n \n if group == \"week\":\n # Start/end dates hardcoded for week atm because of weird hole thing\n # TODO: fix this\n start_date = \"20140630\"\n end_date = \"20150419\"\n weeks = floor_data[start_date:end_date].groupby('weekofyear').sum()\n weeks.index = list(weeks[weeks.index < 27].index + 52) + list(weeks.index[16:])\n weeks = weeks.sort_index()\n weeks.index = floor_data[floor_data.index.dayofweek == 0][start_date:end_date]['date'].drop_duplicates().sort_values()\n ax = weeks.plot(figsize = (10, 7))\n \n elif group == \"day\":\n days = floor_data[start_date:end_date].groupby('date').sum()\n ax = days.drop('weekofyear', 1).plot(figsize = (10, 7))\n \n else:\n ax = floor_data[start_date:end_date].drop('weekofyear', 1).plot(figsize=(10, 7))\n \n ax.set_title(group_word[group] + building + \"Device Counts\")\n ax.set_xlabel(\"Date\")\n ax.set_ylabel(\"Device Count\")\n\n\n# In[5]:\n\ndef bldg_plot(building, group=None, start=\"20140630\", end=\"20150419\"):\n floors = list(buildings[building])\n floor_plot(*floors, group=group, building=building, start=start, end=end)\n\n\n# In[6]:\n\nbldg_plot(\"Butler\", group=\"week\")\n\n\n# In[7]:\n\nbldg_plot(\"Lerner\", group=\"week\")\n\n\n# In[8]:\n\nbldg_plot(\"John Jay\", group=\"week\")\n\n\n# In[9]:\n\nbldg_plot(\"Avery\", group=\"day\")\n\n\n# In[10]:\n\nbldg_plot(\"Butler\", start=\"20140907\", end=\"20140913\")\n\n\n# In[11]:\n\nbldg_plot(\"Lerner\", start=\"20150411\", end=\"20150411\")\n\n\n# In[12]:\n\nbldg_plot(\"Avery\", group=\"day\", start=\"20141101\", end=\"20141130\")\n\n\n# In[13]:\n\nbldg_plot(\"Avery\", start=\"20141101\", end=\"20141101\")\n\n\n# In[ ]:\n\n\n\n","sub_path":"density.py","file_name":"density.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424001628","text":"from pymofscreen.cif_handler import get_cif_files\nfrom pymofscreen.screen import screener\n\n#Set up paths\nmofpath = '../mofpath/'\nbasepath = '../'\nsubmit_script = 'sub_screen.job'\n\n#Get CIF files\ncif_files = get_cif_files(mofpath)\n\n#Construct screener object\ns = screener(basepath,mofpath,submit_script=submit_script)\n\n#Run screening\nfor cif_file in cif_files:\n\tmof = s.run_screen(cif_file,'volume',niggli=True)","sub_path":"examples/volume_relaxation/runner/volume_relaxation.py","file_name":"volume_relaxation.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"39433305","text":"from Controllers.BaseController import BaseController\nfrom Controllers.Addresses.AddressesListController import AddressesListController\nfrom Models.Address import Address\nfrom Database import db\nfrom flask import request, url_for\nimport os\nfrom tinydb import TinyDB\nimport time\nfrom datetime import date\nimport csv\nimport json as JSON\nimport hashlib\n\nclass FetchAddressesController(AddressesListController):\n def __init__(self):\n db.create_all()\n\n def post(self):\n file = request.files['file']\n if file and file.filename.rsplit('.', 1)[1] == 'csv':\n filename = self.save_file(file)\n json = self.csv_to_json(filename)\n\n db.session.query(Address).delete()\n\n for address in json:\n new_address = Address(\n address['address'],\n address['city'],\n self.format_datetime(address['Last met']),\n address['Language 1'] + ', ' + address['Language 2'],\n '',\n address['latitude'],\n address['longitude'],\n address['state'],\n 0)\n db.session.add(new_address)\n\n db.session.commit()\n\n return True\n\n return False\n\n\n def format_datetime(self, last_met):\n\n try:\n datetime = time.strptime(last_met, '%Y-%m-%d')\n except Exception:\n try:\n datetime = time.strptime(last_met, '%d/%m/%Y')\n except:\n try:\n datetime = time.strptime(last_met, '%d.%m.%Y')\n except:\n try:\n datetime = time.strptime(last_met, '%Y-%m-%d')\n except:\n datetime = None\n\n try:\n datetime = date.fromtimestamp(time.mktime(datetime))\n except:\n datetime = None\n\n return datetime\n\n def save_file(self, file):\n filename = file.filename + time.strftime(\"%d/%m/%Y %H:%M:%S\")\n filename = 'UT-' + hashlib.md5(bytes(filename, 'utf-8')).hexdigest()[:10] + '.csv'\n file.save(os.path.join('./uploads', filename))\n return filename\n\n def csv_to_json(self, filename):\n url = url_for('uploaded_file', filename=filename)\n file = open('.' + url, 'r', newline='')\n first_line = file.readline()\n fieldnames = first_line.split(',')\n reader = csv.DictReader(file, fieldnames)\n out = [row for row in reader]\n\n return out\n","sub_path":"Controllers/Addresses/FetchAddressesController.py","file_name":"FetchAddressesController.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"631723284","text":"import os\nimport datetime\nimport sys\nimport time\nimport json\nimport uuid\n\nimport azure.storage.blob as azureblob\nimport azure.batch.batch_service_client as batch\nimport azure.batch.batch_auth as batchauth\nimport azure.batch.models as batchmodels\n\nfrom batch_controls import *\n\nwith open(\"./batch/batch_config.json\",'r') as conf:\n config = json.load(conf)\n\n# Update the Batch and Storage account credential strings below with the values\n# unique to your accounts. These are used when constructing connection strings\n# for the Batch and Storage client objects.\n\n# Batch account credentials\n_BATCH_ACCOUNT_NAME = config[\"_BATCH_ACCOUNT_NAME\"]\n_BATCH_ACCOUNT_KEY = config[\"_BATCH_ACCOUNT_KEY\"]\n_BATCH_ACCOUNT_URL = config[\"_BATCH_ACCOUNT_URL\"]\n\n# Storage account credentials\n_STORAGE_ACCOUNT_NAME = config[\"_STORAGE_ACCOUNT_NAME\"]\n_APP_STORAGE_CONTAINER = config[\"_APP_STORAGE_CONTAINER\"]\n_INPUT_STORAGE_CONTAINER = config[\"_INPUT_STORAGE_CONTAINER\"]\n_OUTPUT_STORAGE_CONTAINER = config[\"_OUTPUT_STORAGE_CONTAINER\"]\n_STORAGE_ACCOUNT_KEY = config[\"_STORAGE_ACCOUNT_KEY\"]\n\n# Set up pool and app information\n_POOL_ID = config[\"_POOL_ID\"]\n_JOB_ID = config[\"_JOB_ID\"]\n\n_APP_NAME = config[\"_APP_NAME\"]\n_APP_VERSION = config[\"_APP_VERSION\"]\n_APP_FILE = config[\"_APP_FILE\"]\n\n_VM_PUBLISHER = config[\"vm_publisher\"].lower()\n_VM_OFFER = config[\"vm_offer\"].lower()\n_VM_SKU = config[\"vm_sku\"].lower()\n_POOL_VM_SIZE = config[\"_POOL_VM_SIZE\"]\n_POOL_NODE_COUNT = config[\"_POOL_NODE_COUNT\"]\n\n_EXPECTED_MODEL_RUN_IN_MINUTES = config[\"_EXPECTED_MODEL_RUN_IN_MINUTES\"]\n\n_FILE_PATTERN = config[\"_FILE_PATTERN\"]\n\n\nif __name__ == '__main__':\n\n # Create the blob client, for use in obtaining references to\n # blob storage containers and uploading files to containers.\n blob_client = azureblob.BlockBlobService(\n account_name=_STORAGE_ACCOUNT_NAME,\n account_key=_STORAGE_ACCOUNT_KEY)\n\n credentials = batchauth.SharedKeyCredentials(_BATCH_ACCOUNT_NAME,_BATCH_ACCOUNT_KEY)\n batch_client = batch.BatchServiceClient(credentials,base_url=_BATCH_ACCOUNT_URL)\n \n # Create a pool based on configurate\n try:\n create_pool(batch_client, _POOL_ID, None,_VM_PUBLISHER,_VM_OFFER, _VM_SKU,_POOL_VM_SIZE,_POOL_NODE_COUNT)\n except batchmodels.BatchErrorException as err:\n if err.error.code != \"PoolExists\":\n raise\n else:\n print(\"Pool already exists. Continuing with existing pool.\")\n\n\n # Creating a Job\n job = batch.models.JobAddParameter(\n id = _JOB_ID,\n pool_info = batch.models.PoolInformation(pool_id=_POOL_ID)\n )\n \n try:\n batch_client.job.add(job)\n except batchmodels.BatchErrorException as err:\n if err.error.code != \"JobExists\":\n print(err)\n raise\n else:\n print(\"Job already exists. Continuing with existing job name.\")\n\n # List all the input files in the given container that start with the _FILE_PATTERN.\n # The listing of files includes the full path (e.g. /My/Path/To/File.txt rather than File.txt)\n # Convert those inputs to \"Resource File\" objects from the batch models package.\n input_files = [\n create_resource_file_from_blob(blob_client, _INPUT_STORAGE_CONTAINER, str(blob.name)) \n for blob in blob_client.list_blobs(_INPUT_STORAGE_CONTAINER) \n if str(blob.name).startswith(_FILE_PATTERN)\n ]\n\n print(\"There are {} files to be analyzed\".format(len(input_files)))\n\n # Adding a Task\n # Referencing the AZ_BATCH_APP_PACKAGE path to get access to the application loaded via the portal.\n # Everything after the reference to the App file is custom to the app file itself.\n tasks = list()\n for idx, input_file in enumerate(input_files):\n command = ['python3 $AZ_BATCH_APP_PACKAGE{}/{} -i {} --storageaccount {} --storagecontainer {} --key {}'.format(\n app_rename_rules(_APP_NAME,_APP_VERSION),\n _APP_FILE,\n input_file.file_path,\n _STORAGE_ACCOUNT_NAME,\n _OUTPUT_STORAGE_CONTAINER,\n _STORAGE_ACCOUNT_KEY)]\n\n # Appending the tasks with a random identifier (uuid4).\n tasks.append(\n batch.models.TaskAddParameter(\n id = 'make_lm{}'.format(uuid.uuid4()),\n command_line = wrap_commands_in_shell('linux',command),\n resource_files=[input_file],\n # This part assumes you've uploaded an application package and have specified a default version\n application_package_references = [batchmodels.ApplicationPackageReference(_APP_NAME)]\n )\n )\n \n print(\"There are {} tasks created\".format(len(tasks)))\n\n successfully_added_all_tasks = batch_client.task.add_collection(_JOB_ID, tasks)\n\n registered_tasks = batch_client.task.list(_JOB_ID)\n\n print(\"Starting to wait and pinging the service for job tracking\")\n\n wait_for_tasks_to_complete(batch_client,\n _JOB_ID,\n datetime.timedelta(minutes=_EXPECTED_MODEL_RUN_IN_MINUTES)\n )\n\n print(\"Success! All tasks reached the 'Completed' state within the specified timeout period.\")","sub_path":"batch/linear_model/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"350281277","text":"import os\nimport argparse\nimport pickle\n\nimport numpy as np\nfrom functools import reduce\n\nimport cv2\n\nfrom src.a2c.models.actor_critic_model import ActorCriticModel\nfrom src.a2c.eval.a2c_eval import Memory\n\nNOISE_WEIGHT = .5\nTHRESHOLD = 0\n\nIMAGE_SHAPE = (84, 84, 3)\nBLUR_COEFF = 50\nMASK_RADIUS = 21\nSTRIDE = 4\nOFFSET = 2\n\ndef superimpose(source_image, noise_image):\n new_image = cv2.normalize(source_image, None, 255, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)\n noise_image = (noise_image * 255).astype(np.uint8)\n for y in range(IMAGE_SHAPE[0]):\n for x in range(IMAGE_SHAPE[1]):\n new_image[x,y] = (np.multiply(NOISE_WEIGHT,noise_image[x,y]) + np.multiply((1-NOISE_WEIGHT),new_image[x,y]))\n new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)\n return new_image\n\ndef blur_images(images, radius):\n # return np.array([cv2.blur(image, (radius,radius)) for image in images])\n return np.array([cv2.GaussianBlur(image, (radius,radius), 0) for image in images])\n\ndef generate_mask(image_shape, radius, x, y):\n mask_image = np.zeros(image_shape)\n mask_image[y,x] = 1.\n mask_image = cv2.GaussianBlur(mask_image, (radius,radius), 0)\n mask_image = cv2.normalize(mask_image, None, 1, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n return mask_image\n\ndef generate_masks(image_shape, radius, stride):\n masks = []\n for y in range(image_shape[0])[::stride]:\n for x in range(image_shape[0])[::stride]:\n masks.append(generate_mask(image_shape, radius, x + OFFSET, y + OFFSET))\n return np.array(masks)\n\ndef perturb_image(source_image, blurred_image, mask):\n result = np.zeros(IMAGE_SHAPE)\n for y in range(IMAGE_SHAPE[0]):\n for x in range(IMAGE_SHAPE[1]):\n if mask[y,x] > 0: result[y,x] = np.multiply(mask[y,x],blurred_image[y,x]) + np.multiply(1-mask[y,x],source_image[y,x])\n return result\n\ndef generate_perturbations(source_image, masks, blur_coeff, stride):\n perturbed_images = []\n blurred_image = cv2.blur(source_image, (blur_coeff,blur_coeff))\n for y in range(IMAGE_SHAPE[0])[::stride]:\n for x in range(IMAGE_SHAPE[1])[::stride]:\n print(x//stride + (y//stride)*(IMAGE_SHAPE[0]//stride))\n perturbed_image = perturb_image(source_image, blurred_image, masks[x//stride + y*IMAGE_SHAPE[0]//stride])\n perturbed_images.append(perturbed_image)\n return perturbed_images\n\ndef generate_saliency(model, source_image, floor_data, masks, blur_coeff, stride):\n actor_saliency_map, critic_saliency_map = np.zeros(IMAGE_SHAPE[:-1]), np.zeros(IMAGE_SHAPE[:-1])\n state = model.process_inputs([(source_image, floor_data)])\n logits, value = model.predict(state)\n logits, value = np.squeeze(logits), np.squeeze(value)\n blurred_image = cv2.blur(source_image, (blur_coeff,blur_coeff))\n for mask in masks:\n perturbed_image = perturb_image(source_image, blurred_image, mask)\n perturbed_state = model.process_inputs([(perturbed_image, floor_data)])\n perturbed_logits, perturbed_value = model.predict(perturbed_state)\n perturbed_logits, perturbed_value = np.squeeze(perturbed_logits), np.squeeze(perturbed_value)\n actor_saliency = sum(np.square(logits - perturbed_logits)) / 2\n actor_saliency_map = actor_saliency_map + np.multiply(actor_saliency, mask)\n critic_saliency = np.square(value - perturbed_value) / 2\n critic_saliency_map = critic_saliency_map + np.multiply(critic_saliency, mask)\n # actor_saliency_map = cv2.normalize(actor_saliency_map, None, 1, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n # critic_saliency_map = cv2.normalize(critic_saliency_map, None, 1, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n return actor_saliency_map, critic_saliency_map\n\nmasks = generate_masks(IMAGE_SHAPE[:-1], MASK_RADIUS, STRIDE)\n\ndef draw_current_frame(frame, actor_image, critic_image):\n y_start, x_start = 0, 0\n image_height, image_width = 640, 640\n margin = 0\n\n actor_image = cv2.resize(actor_image, dsize=(image_height,image_width), interpolation=cv2.INTER_NEAREST)\n critic_image = cv2.resize(critic_image, dsize=(image_height,image_width), interpolation=cv2.INTER_NEAREST)\n\n y_pos, x_pos = y_start, x_start\n y_end, x_end = y_pos + image_height, x_pos + image_width\n frame[y_pos:y_end,x_pos:x_end,:] = actor_image\n # cv2.putText(frame,'actor_image',(x_pos,y_end+12),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n\n y_pos, x_pos = y_start, x_start + image_width + margin\n y_end, x_end = y_pos + image_height, x_pos + image_width\n frame[y_pos:y_end,x_pos:x_end,:] = critic_image\n # cv2.putText(frame,'critic_image',(x_pos,y_end+12),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n\ndef draw_distributions(frame, distribution, max_dist):\n x = 800\n y = 350\n width = 120\n height = 200\n dx = 5\n dy = 15\n\n cv2.putText(frame,'{:+.3f}'.format(distribution[1]),(x+dx,y+height+dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.putText(frame,'camera',(x+dx,y+height+2*dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.putText(frame,'left',(x+dx,y+height+3*dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.rectangle(frame,(x,y+height),(x+width,y+height+width),(255,255,255))\n frame[int(y+height*(1-distribution[1]/max_dist)):y+height,x:x+width,:] = 255\n\n cv2.putText(frame,'{:+.3f}'.format(distribution[0]),(x+width+dx,y+height+dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.putText(frame,'forward',(x+width+dx,y+height+2*dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.rectangle(frame,(x+width,y+height),(x+2*width,y+height+width),(255,255,255))\n frame[int(y+height*(1-distribution[0]/max_dist)):y+height,x+width:x+2*width,:] = 255\n\n cv2.putText(frame,'{:+.3f}'.format(distribution[2]),(x+2*width+dx,y+height+dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.putText(frame,'camera',(x+2*width+dx,y+height+2*dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.putText(frame,'right',(x+2*width+dx,y+height+3*dy),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255))\n cv2.rectangle(frame,(x+2*width,y+height),(x+3*width,y+height+width),(255,255,255))\n frame[int(y+height*(1-distribution[2]/max_dist)):y+height,x+2*width:x+3*width,:] = 255\n\nif __name__ == '__main__':\n #COMMAND-LINE ARGUMENTS#\n parser = argparse.ArgumentParser(description='Render one memory.')\n parser.add_argument('--memory-path', required=True, help='path to saved memory object file')\n parser.add_argument('--output-dir', default='a2c_saliency', help='name of the video file')\n parser.add_argument('--restore', type=str, default=None, help='path to saved model')\n args = parser.parse_args()\n\n #LOAD FILE#\n data_path = args.memory_path\n data_file = open(data_path, 'rb+')\n memory = pickle.load(data_file)\n data_file.close()\n\n #PARSE DATA#\n states, floor_datas = zip(*memory.states)\n states = np.array(states)\n floor_datas = np.array(floor_datas)\n frame_data = zip(states, floor_datas)\n print(\"Memory length: {}\".format(len(states)))\n\n #VIDEO PARAMETERS#\n fps = 10\n width = 1280\n height = 720\n\n #INIT VIDEO#\n output_path = os.path.join(args.output_dir, 'saliency_render.mp4')\n os.makedirs(os.path.dirname(output_path), exist_ok=True)\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n video = cv2.VideoWriter(output_path, fourcc, fps, (width,height))\n\n NUM_ACTIONS = 4\n STATE_SHAPE = [84,84,3]\n STACK_SIZE = 1\n CONV_SIZE = 'quake' #((8,4,16),(4,2,32),(3,1,64))\n\n model = ActorCriticModel(num_actions=NUM_ACTIONS,\n state_size=STATE_SHAPE,\n stack_size=STACK_SIZE,\n actor_fc=(512,),\n critic_fc=(512,),\n conv_size=CONV_SIZE)\n model.load_weights(args.restore)\n\n actor_saliency_maps = []\n critic_saliency_maps = []\n #RENDER VIDEO#\n print(\"Generating saliency maps...\")\n for i, (state, floor_data) in enumerate(frame_data):\n current_image = state\n frame = np.zeros((height,width,3),dtype=np.uint8)\n\n actor_saliency_map, critic_saliency_map = generate_saliency(model, current_image, floor_data, masks, BLUR_COEFF, STRIDE)\n actor_saliency_maps.append(np.copy(actor_saliency_map))\n critic_saliency_maps.append(np.copy(critic_saliency_map))\n\n actor_saliency_map = (np.zeros(IMAGE_SHAPE) + actor_saliency_map[:,:,None]) * [1,0,0]\n critic_saliency_map = (np.zeros(IMAGE_SHAPE) + critic_saliency_map[:,:,None]) * [0,0,1]\n actor_image = superimpose(current_image.astype(np.float32), cv2.normalize(actor_saliency_map, None, 1, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F))\n critic_image = superimpose(current_image.astype(np.float32), cv2.normalize(critic_saliency_map, None, 1, 0, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F))\n actor_image_path = os.path.join(args.output_dir, 'actor_saliency_{}.png'.format(i))\n critic_image_path = os.path.join(args.output_dir, 'critic_saliency_{}.png'.format(i))\n cv2.imwrite(actor_image_path, actor_image)\n cv2.imwrite(critic_image_path, critic_image)\n print(\"--- Frame {} finished.\".format(i))\n\n actor_saliency_maps = np.array(actor_saliency_maps)\n critic_saliency_maps = np.array(critic_saliency_maps)\n actor_saliency_min, actor_saliency_max = np.amin(actor_saliency_maps), np.amax(actor_saliency_maps)\n critic_saliency_min, critic_saliency_max = np.amin(critic_saliency_maps), np.amax(critic_saliency_maps)\n actor_saliency_maps = (actor_saliency_maps - actor_saliency_min) / (actor_saliency_max - actor_saliency_min)\n critic_saliency_maps = (critic_saliency_maps - critic_saliency_min) / (critic_saliency_max - critic_saliency_min)\n \n # print(\"actor saliency range: {} - {}\".format(np.min(actor_saliency_maps),np.max(actor_saliency_maps)))\n # print(\"critic saliency range: {} - {}\".format(np.min(critic_saliency_maps),np.max(critic_saliency_maps)))\n\n print(\"Rendering video...\")\n for i, (state, actor_saliency_map, critic_saliency_map) in enumerate(zip(states, actor_saliency_maps, critic_saliency_maps)):\n current_image = state\n actor_saliency_map = (np.zeros(IMAGE_SHAPE) + actor_saliency_map[:,:,None]) * [1,0,0]\n critic_saliency_map = (np.zeros(IMAGE_SHAPE) + critic_saliency_map[:,:,None]) * [0,0,1]\n\n actor_image = superimpose(current_image.astype(np.float32), actor_saliency_map.astype(np.float32))\n critic_image = superimpose(current_image.astype(np.float32), critic_saliency_map.astype(np.float32))\n actor_image_path = os.path.join(args.output_dir, 'actor_saliency_{}.png'.format(i))\n critic_image_path = os.path.join(args.output_dir, 'critic_saliency_{}.png'.format(i))\n\n draw_current_frame(frame, actor_image, critic_image)\n video.write(frame)\n print(\"Done!\")\n\n video.release()\n cv2.destroyAllWindows()","sub_path":"src/misc/perturbation_saliency/render_1stack_saliency_normalized.py","file_name":"render_1stack_saliency_normalized.py","file_ext":"py","file_size_in_byte":10853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"617828257","text":"import sys\nimport pandas as pd\nimport numpy as np\nimport collections\nimport pickle\n\nimport tensorflow as tf\nimport tflearn\nimport tflearn.data_utils as du\n\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_1d, global_max_pool, global_avg_pool, max_pool_1d\nfrom tflearn.layers.merge_ops import merge\nfrom tflearn.layers.estimator import regression\nfrom tflearn.data_utils import to_categorical, pad_sequences\nfrom tflearn.optimizers import Adam\n\nimport utils.data_util as util\nimport utils.config as conf\nimport utils.chat_util as cu\nimport utils.nlp_util as nu\nimport utils.word2vec as wvu\nfrom utils.performance import Performance\nfrom utils.val_history_tflearn import ValHistory\n#Main class holding model\nclass TextClassificationModel:\n \n def printDiff(self,data_config_file=None):\n print(\"Printing difference of predictions for TextClassificationModel[{}]...\".format(self.model_name))\n sep = '|'\n diff = {}\n conf_df = []\n rec = 0\n rec_change_ind = False\n \n if data_config_file != None:\n print(\"printDiff Loading config from file[{}]...\".format(data_config_file))\n conf_df = pd.read_csv(data_config_file,header=None,delimiter='|') \n\n with open(self.datadir + self.model_name + '_diff.txt','w') as f1:\n prbuf = 'rec' + sep;\n for pos in range(0,2*self.config.window+1,1):\n prbuf = prbuf + 'n-' + str(pos) + sep\n prbuf = prbuf + 'y' + sep \n prbuf = prbuf + 'yhat' + '\\n'\n for i,j in enumerate(self.pred_code):\n new_rec_ind = ''\n for ci in range(self.config.window):\n new_rec_ind = new_rec_ind + self.testX[i][ci]\n if new_rec_ind == ('UNK'*self.config.window):\n rec += 1\n rec_change_ind = True\n if self.labels.idx2word[self.encodedYtestdata[i]] != self.labels.idx2word[j]:\n if rec_change_ind and len(conf_df) > 0:\n f1.write(conf_df.iloc[rec-1,1])\n f1.write('\\n')\n rec_change_ind = False\n diff[i] = j\n prbuf = str(i) + sep;\n for pos in range(0,2*self.config.window+1,1):\n prbuf = prbuf + self.vocab.idx2word[self.encodedXtestdata[i][pos]] + sep \n prbuf = prbuf + self.labels.idx2word[self.encodedYtestdata[i]] + sep \n prbuf = prbuf + self.labels.idx2word[j] + sep\n prbuf = prbuf + str(self.pred_prob[i]) + '\\n'\n f1.write(prbuf)\n \n \n self.accu = float((len(self.pred_code) - len(diff))/len(self.pred_code)) \n print(\" {} words & {} errors Accuracy: {}\".format(len(self.pred_code),len(diff),self.accu)) \n\n def printTextClassification(self,data_config_file=None):\n print(\"Printing textence classification corpus using TextClassificationModel[{}]...\".format(self.model_name))\n conf_df = []\n rec = 0\n text = []\n pred_text = ''\n \n if data_config_file != None:\n print(\"printTextClassification Loading config from file[{}]...\".format(data_config_file))\n conf_df = pd.read_csv(data_config_file,header=None,delimiter='|') \n \n p_df = pd.DataFrame(columns=[\n \"conv_id\",\n \"text\",\n \"label\",\n #\"vect_id\",\n \"pr\"])\n\n with open(self.datadir + self.model_name + '_text.txt','w') as f1:\n for i,j in enumerate(self.pred_code):\n new_rec_ind = ''\n for ci in range(self.config.window):\n new_rec_ind = new_rec_ind + self.testX[i][ci]\n if i>0 and new_rec_ind == ('UNK'*self.config.window):\n text.append(pred_text)\n #print(rec,pred_text,conf_df.iloc[rec,2])\n pred_text = ''\n rec += 1\n f1.write('\\n')\n prbuf = ''\n if self.labels.idx2word[j] == 'UNK1':\n #prbuf = prbuf + self.vocab.idx2word[self.encodedXtestdata[i][self.config.window]]\n prbuf = prbuf + self.testX[i][self.config.window]\n pred_text = pred_text + self.testX[i][self.config.window] + ' '\n else:\n prbuf = prbuf + self.labels.idx2word[j]\n pred_text = pred_text + self.labels.idx2word[j] + ' '\n prbuf = prbuf + '\\n'\n f1.write(prbuf)\n \n ''' \n prbuf = str(rec) + sep \n prbuf = prbuf + self.testX[i][self.config.window] + sep \n prbuf = prbuf + self.labels.idx2word[self.pred_code[i]] + sep\n prbuf = prbuf + self.vocab.idx2word[self.encodedXtestdata[i][self.config.window]] + sep \n prbuf = prbuf + str(self.pred_prob[i]) + '\\n'\n ''' \n p_df.loc[p_df.shape[0]] = [ str(rec),\n #self.testX[i][self.config.window],\n pred_text.split()[:10],\n self.labels.idx2word[self.pred_code[i]],\n #self.vocab.idx2word[self.encodedXtestdata[i][self.config.window]],\n str(self.pred_prob[i])]\n \n text.append(pred_text)\n p_df.to_csv(self.datadir + self.model_name + \"_pred_df.csv\")\n #print(\"***********\",conf_df.iloc[395,2],text[395],len(conf_df),len(text))\n conf_df[4] = text\n conf_df.to_csv(data_config_file + '.txt',index=None,header=None,sep='|')\n \n \"\"\" \n Constructor for TextClassificationModel\n \"\"\" \n def __init__(self,model_name,trainfl,datadir,modeldir,config_data):\n np.random.seed(1) #added to keep result consistentcy.\n self.model_name = model_name\n self.src_file = 'text_model_' + self.model_name + '.tfl'\n print(\"Initializing TextClassificationModel[{}]...\".format(self.model_name))\n self.datadir = datadir\n self.modeldir = modeldir\n self.train_data_file = datadir + trainfl\n self.perf = Performance(self.model_name) # create config file\n if config_data:\n self.config = conf.Config(self.model_name, self.datadir) # create config file\n self.config.__dict__.update(config_data)\n #import pprint\n #pp = pprint.PrettyPrinter()\n #pp.pprint(self.config)\n else:\n self.config = conf.Config(self.model_name,self.datadir) #create config file\n #import sys\n #sys.exit(0)\n self.createTextClassificationModel() #create TextClassificationModel\n #self.createSimpleDNN() #create TextSimpleDNN\n \n \"\"\" \n Function does following things\n\t- reads input file with format of raw textences which are tagged. Tag is last word of textence line\n - builds vocab as per config\n - creates X and Y out of data. X are textence words with 0 padding and Y are calssification labels.\n \"\"\" \n def buildTrainingData(self):\n print(\"Building train data for TextClassificationModel[{}]...\".format(self.model_name))\n #initialize all keys required to browse data\n raw_data_key = self.config.dp_raw_data_key\n data_key = self.config.dp_data_key\n text_class = self.config.dp_sent_class\n conv_key = self.config.dp_conv_key\n conv_tag = self.config.dp_conv_tag\n conv_tag_buf = self.config.dp_conv_tag_buf\n conv_data_key = self.config.dp_conv_data_key\n \n #read training data \n avg_words,avg_texts,conv = cu.processTaggedConv(self.train_data_file,config=self.config)\n trainX = [] \n trainY = [] \n \n for i,cdata in enumerate(conv):\n #if i >= 3:\n # break\n \n convdata = cdata[conv_data_key]\n convtag = cdata[conv_tag]\n \n for j,sdata in enumerate(convdata):\n trainX.append(sdata[data_key])\n trainY.append(sdata[text_class])\n \n #print(\"++conv[{}]+++****labels[{}]\".format(cdata[conv_key],convtag))\n \n print(\"Training data of [{}] senttences and [{}]([{}] unique) labels loaded for classification...\".format(len(trainX),len(trainY),len(set(trainY)))) \n self.vocab = nu.Vocab(trainX,self.config) #build X vocab dict & required data\n self.labels = nu.Vocab(trainY,self.config,label=True) #build Y vocab dict & required data\n \n self.labels.setUNK('UNK1') #Explicitly set label for unknown classification\n \n #Create encoding for training data\n self.encodedXdata = self.vocab.getCodedData()\n self.encodedYdata = self.labels.getCodedData()\n \n print(\"Coded X {} data: {}\".format(len(self.encodedXdata),self.vocab.getData()[:10]))\n print(\"Coded X code: {}\".format(self.encodedXdata[:10]))\n print(\"Coded Y size {} unique {} data: {}\".format(len(self.encodedYdata),len(set(self.encodedYdata)),self.labels.getData()[:10]))\n print(\"Coded Y code: {}\".format(self.encodedYdata[:10]))\n \n #pad sequence with zero's \n self.encodedXdata = pad_sequences(self.encodedXdata,maxlen=self.config.text_size,value=self.vocab.getPADCode())\n self.no_classes = len(set(self.encodedYdata)) #no of target classes\n self.Y = to_categorical(self.encodedYdata, nb_classes=self.no_classes) #Y as required by tflearn\n \n #release unwanted variables.\n trainX = None\n trainY = None\n\n def buildTextTestData(self,testfl):\n print(\"Building textence test data for TextClassificationModel[{}]...\".format(self.model_name))\n #read test data in form of (n-gram) embeding\n self.test_data_file = self.datadir + testfl\n self.testX = util.getTokenizeText(self.test_data_file,self.config.window,text_index=4)\n self.encodedXtestdata = self.vocab.encode(self.testX)\n \n print(\"Coded Test X {} data: {}\".format(len(self.encodedXtestdata),self.vocab.convData(self.encodedXtestdata)[:10]))\n print(\"Coded Test X code: {}\".format(self.encodedXtestdata[:10]))\n \n def buildTestData(self,testfl,data_only=False):\n print(\"Building test data for TextClassificationModel[{}]...\".format(self.model_name))\n #read test data in form of (n-gram) embeding\n self.test_data_file = self.datadir + testfl\n \n #initialize all keys required to browse data\n raw_data_key = self.config.dp_raw_data_key\n data_key = self.config.dp_data_key\n text_class = self.config.dp_sent_class\n conv_key = self.config.dp_conv_key\n conv_tag = self.config.dp_conv_tag\n conv_tag_buf = self.config.dp_conv_tag_buf\n conv_data_key = self.config.dp_conv_data_key\n \n avg_words = 0.0\n avg_texts = 0.0 \n convtag = ''\n conv = []\n\n #read training data \n if data_only == False:\n avg_words,avg_texts,conv = cu.processTaggedConv(self.test_data_file,config=self.config)\n else:\n avg_words,avg_texts,conv = cu.processTaggedConv(self.test_data_file,tagged=False,config=self.config)\n \n self.testX = [] \n self.raw_testX = [] \n self.conv_ind = [] #collect conv_key at conv level\n self.conv_ind1 = [] #collect conv_key at sentence level, used in printPrediction\n testY = [] \n self.test_convdata = conv\n \n for i,cdata in enumerate(conv):\n #if i >= 3:\n # break\n \n convdata = cdata[conv_data_key]\n convkey = cdata[conv_key]\n \n conv_Xdata = [] \n conv_Xrawdata = [] \n \n #build test data \n for j,sdata in enumerate(convdata):\n self.testX.append(sdata[data_key])\n if data_only == False:\n testY.append(sdata[text_class])\n self.conv_ind1.append(convkey)\n \n self.conv_ind.append(convkey)\n \n #print(\"i[{}]****conv_ind[{}]****trainX[{}]****labels[{}]\".format(i,convkey,conv_Xdata,convtag))\n \n print(\"Test data of[{}] textences and [{}] labels loaded for classification...\".format(len(self.testX),len(testY))) \n #encode the test data\n self.encodedXtestdata = self.vocab.encode(self.testX)\n if data_only == False: #encode labels\n self.encodedYtestdata = self.labels.encode(testY)\n print(\"+++++++++++++++++++++++++++++++++++++++++\")\n print(set(testY))\n print(\"Coded Test X {} data: {}\".format(len(self.encodedXtestdata),self.vocab.convData(self.encodedXtestdata)[:10]))\n print(\"Coded Test X code: {}\".format(self.encodedXtestdata[:10]))\n \n \"\"\"\n if data_only == False:\n print(\"Coded test Y size {} unique {} data: {}\".format(len(self.encodedYtestdata),len(set(self.encodedYtestdata)),self.labels.convData(self.encodedYtestdata)[:10]))\n print(\"Coded Y code: {}\".format(self.encodedYtestdata[:10]))\n \"\"\"\n #pad sequence with zero's \n self.encodedXtestdata = pad_sequences(self.encodedXtestdata,maxlen=self.config.text_size,value=0)\n\n ''' \n used for processing raw text\n ''' \n def buildTestDataFromRawText(self,text,convkey=0):\n raw_data_key = self.config.dp_raw_data_key\n conv_key = self.config.dp_conv_key\n conv_data_key = self.config.dp_conv_data_key\n text_class = self.config.dp_sent_class\n conv_tag = self.config.dp_conv_tag\n conv_tag_buf = self.config.dp_conv_tag_buf\n conv_data_key = self.config.dp_conv_data_key\n data_key = self.config.dp_data_key \n raw_data_key = self.config.dp_raw_data_key\n \n print(\"Building test data array and encoding for NERModel[{}]...\".format(self.model_name))\n conv = cu.processRawTextForConv(text=text,convkey=convkey)\n \n self.testX = [] \n self.raw_testX = [] \n self.conv_ind = [] #collect conv_key at conv level\n self.conv_ind1 = [] #collect conv_key at sentence level, used in printPrediction\n testY = [] \n self.test_convdata = conv\n \n for i,cdata in enumerate(conv):\n #if i >= 3:\n # break\n \n convdata = cdata[conv_data_key]\n convkey = cdata[conv_key]\n \n conv_Xdata = [] \n conv_Xrawdata = [] \n \n #build test data \n for j,sdata in enumerate(convdata):\n self.testX.append(sdata[data_key])\n testY.append(sdata[text_class])\n self.conv_ind1.append(convkey)\n \n self.conv_ind.append(convkey)\n \n #print(\"i[{}]****conv_ind[{}]****trainX[{}]****labels[{}]\".format(i,convkey,conv_Xdata,convtag))\n \n print(\"Test data of[{}] textences and [{}] labels loaded for classification...\".format(len(self.testX),len(testY))) \n #encode the test data\n self.encodedXtestdata = self.vocab.encode(self.testX)\n self.encodedYtestdata = self.labels.encode(testY)\n \n print(\"============================================================\") \n print(\"Coded Test X {} data: {}\".format(len(self.encodedXtestdata),self.vocab.convData(self.encodedXtestdata)[:10]))\n print(\"Coded Test X code: {}\".format(self.encodedXtestdata[:10]))\n print(\"Coded test Y size {} unique {} data: {}\".format(len(self.encodedYtestdata),len(set(self.encodedYtestdata)),self.labels.convData(self.encodedYtestdata)[:10]))\n print(\"Coded Y code: {}\".format(self.encodedYtestdata[:10]))\n print(\"============================================================\") \n \n #pad sequence with zero's \n self.encodedXtestdata = pad_sequences(self.encodedXtestdata,maxlen=self.config.text_size,value=self.vocab.getPADCode())\n\n def createTextClassificationModel(self):\n print(\"Createing the TextClassificationModel[{}]...\".format(self.model_name))\n self.buildTrainingData()\n self.config.initializeModelVariables()\n tf.reset_default_graph()\n #err #error\n\n # Building convolutional network\n network = input_data(shape=[None, self.config.text_size], name='input')\n network = tflearn.embedding(network, \n input_dim = self.vocab.dict_size, \n #weights_init = self.config.w_initializer,\n weights_init = tflearn.initializations.xavier(uniform=True, seed=self.config.tf_seed),\n output_dim = self.config.wv_size,\n name='embedding')\n \n conv1 = [] \n for f_sz in self.config.conv1_filter_sz:\n l_conv = conv_1d( network, nb_filter=self.config.conv1_nb_filter, \n filter_size=self.config.conv2_filter_sz, \n strides=self.config.conv1_stride, padding=self.config.conv1_padding, \n activation=self.config.conv1_actfun, \n bias=True,\n #weights_init = self.config.conv_w_initializer, \n weights_init = tflearn.initializations.uniform_scaling(seed=self.config.tf_seed),\n bias_init='zeros', regularizer=self.config.conv_regularizer, \n weight_decay=0.001, trainable=True, restore=True,\n name='l_conv_' + str(f_sz))\n l_pool = max_pool_1d( l_conv, kernel_size=self.config.conv1_pooling_kernel_sz, \n strides=None, padding=self.config.conv1_padding, \n name='l_conv_' + str(f_sz))\n \n conv1.append( l_pool)\n \n network = merge( conv1, mode='concat', axis=1)\n \n network = conv_1d( network, nb_filter=self.config.conv2_nb_filter, \n filter_size=self.config.conv2_filter_sz, \n strides=self.config.conv2_stride, padding=self.config.conv2_padding, \n activation=self.config.conv2_actfun, \n bias=True,\n #weights_init = self.config.conv_w_initializer, \n weights_init = tflearn.initializations.uniform_scaling(seed=self.config.tf_seed),\n bias_init='zeros', regularizer=self.config.conv_regularizer, \n weight_decay=0.001, trainable=True, restore=True,\n name='l_conv2')\n network = max_pool_1d( network, kernel_size=self.config.conv2_pooling_kernel_sz, \n strides=None, padding=self.config.conv2_padding, \n name='l_pool2')\n \n network = conv_1d( network, nb_filter=self.config.conv3_nb_filter, \n filter_size=self.config.conv3_filter_sz, \n strides=self.config.conv3_stride, padding=self.config.conv3_padding, \n activation=self.config.conv3_actfun, \n bias=True,\n #weights_init = self.config.conv_w_initializer, \n weights_init = tflearn.initializations.uniform_scaling(seed=self.config.tf_seed),\n bias_init='zeros', regularizer=self.config.conv_regularizer, \n weight_decay=0.001, trainable=True, restore=True,\n name='l_conv3')\n network = max_pool_1d( network, kernel_size=self.config.conv3_pooling_kernel_sz, \n strides=None, padding=self.config.conv3_padding, \n name='l_pool3')\n '''\n network = conv_1d( network, nb_filter=self.config.conv4_nb_filter, \n filter_size=self.config.conv4_filter_sz, \n strides=self.config.conv4_stride, padding=self.config.conv4_padding, \n activation=self.config.conv4_actfun, \n bias=True,\n #weights_init = self.config.conv_w_initializer, \n weights_init = tflearn.initializations.uniform_scaling(seed=self.config.tf_seed),\n bias_init='zeros', regularizer=self.config.conv_regularizer, \n weight_decay=0.001, trainable=True, restore=True,\n name='l_conv4')\n network = max_pool_1d( network, kernel_size=self.config.conv4_pooling_kernel_sz, \n strides=None, padding=self.config.conv4_padding, \n name='l_pool4')\n '''\n \n #network = merge([branch2, branch3, branch4, branch5], mode='concat', axis=1)\n network = tf.expand_dims(network, 2)\n network = global_max_pool(network,name='global_max_pool')\n #network = global_avg_pool(network,name='global_avg_pool')\n \n network = tflearn.fully_connected(network, \n self.config.hidden1_units, \n weights_init = tflearn.initializations.xavier(uniform=True, seed=self.config.tf_seed),\n activation=self.config.hidden1_actfun,\n name='fc_hidden1')\n network = tflearn.dropout(network,self.config.hidden1_drop_prob)\n \n network = tflearn.fully_connected(network, \n self.config.hidden2_units, \n weights_init = tflearn.initializations.xavier(uniform=True, seed=self.config.tf_seed),\n activation=self.config.hidden2_actfun,\n name='fc_hidden2')\n network = tflearn.dropout(network,self.config.hidden2_drop_prob)\n \n network = fully_connected(network, self.no_classes, self.config.fc_final_actfun,name='fc_final')\n \n # With TFLearn estimators\n #adam = Adam(learning_rate=self.config.lrate, beta1=0.99)\n\n network = regression(network, \n optimizer = self.config.optimizer,\n #optimizer = adam,\n learning_rate = self.config.lrate, \n loss='categorical_crossentropy', name='target')\n # Define model\n self.model = tflearn.DNN(network)\n\n def loadModel(self,model_file):\n # Restore model from earlier saved file \n print(\"Restoring TextClassificationModel[{}] from [{}] file...\".format(self.model_name,model_file))\n self.model.load(self.modeldir + model_file)\n\n #Incomplete....\n def reTrainTheModel(self,retrain_data_file):\n # Start training (apply gradient descent algorithm)\n print(\"Training TextClassificationModel[{}]...\".format(self.model_name))\n self.buildTrainingData()\n self.drop_prob = 0.0\n self.model.fit( self.encodedXdata, self.Y, \n n_epoch = self.config.epoch, \n validation_set = self.config.validation_set_ratio, \n batch_size = self.config.batch_size, \n verbose = self.config.tf_verbose,\n show_metric = True)\n print(\"Saving the trained model...\")\n self.model.save(self.modeldir + self.src_file)\n print(\"Model saved in [{}] file.\".format(self.src_file))\n\n def trainTheModel(self):\n # Start training (apply gradient descent algorithm)\n print(\"Training TextClassificationModel[{}]...\".format(self.model_name))\n #self.buildTrainingData()\n self.history = ValHistory()\n res = self.model.fit( self.encodedXdata, self.Y,\n n_epoch = self.config.epoch, \n validation_set = self.config.validation_set_ratio, \n batch_size = self.config.batch_size, \n show_metric = True,callbacks=[self.history])\n self.perf.set_from_training(self.history)\n print(\"Saving the trained model...\")\n self.model.save(self.modeldir + self.src_file)\n print(\"Model saved in [{}] file.\".format(self.src_file))\n \n\n #process data file with raw record data with every line in file as one textence or record.\n def processRawDataRec(self,raw_data_file):\n print(\"Processing raw test data file[{}] on TextClassificationModel[{}]...\".format(raw_data_file,self.model_name))\n interim_data_file = util.processRawData(self.datadir + raw_data_file)\n print(interim_data_file)\n self.testTheModel(interim_data_file,data_only=True)\n \n def genTextTrainingCorpus(self,test_data_file):\n print(\"Getextclassiating textence training corpus using TextClassificationModel[{}]...\".format(self.model_name))\n #Get predictions\n self.buildTextTestData(test_data_file)\n self.pred = self.model.predict(self.encodedXtestdata)\n self.pred_code = np.argmax(self.pred,axis=1)\n self.pred_prob = np.amax(self.pred,axis=1)\n #self.printPrediction(data_only)\n self.printTextClassification(data_config_file=self.datadir + test_data_file)\n\n \"\"\"\n Desc - Iterate over predictions and log details where ever prediction is diff from actual.\n\tPrediction are loged in form accuracy summary and classifier level accuracy on screen.\n\tA Diff file is created for test data with raw data, its prediction and actual label.\n A editable file is created with original data and predicted label for case where it is \n\twrong.\n \"\"\"\n def printPrediction(self,data_only=False):\n print(\"Printing predictions for TextClassificationModel[{}]...\".format(self.model_name))\n sep = ','\n rec = 0\n rec_change_flag = False\n rec_diff = 0\n rec_data = []\n err_cnt = dict() #collects stats at each of classifier for accuracy.\n i = 0\n prev_conv_ind = -99 #required to keep track of conv id change to mimic original raw file for docstart.\n\n to = 20\n digits = len(str(to - 1))\n delete = \"\\b\" * (digits)\n\n with open(self.datadir + self.model_name + '_test.pred','w') as f1, open(self.datadir + self.model_name + '_edit.pred','w') as f2:\n for i in range(len(self.testX)):\n rec += 1\n #check for textence end based in n-gram used using window size\n prbuf = '' #self.testX[i][self.config.window] + sep + self.labels.idx2word[self.pred_code[i]] + '\\n'\n if data_only == False:\n err_cnt_key = str(self.labels.idx2word[self.encodedYtestdata[i]])\n err_cnt[err_cnt_key + '0'] = err_cnt.get(err_cnt_key + '0',0) + 1\n #logic for checking conversations.\n if prev_conv_ind != self.conv_ind1[i]:\n f2.write(\"\\n-DOCSTART- {} \\n\".format(self.encodedYtestdata[i]))\n #logic to create data if prediction error\n if self.pred_code[i] != self.encodedYtestdata[i]:\n #print(i,self.labels.idx2word[self.pred_code[i]],self.raw_testX) \n err_cnt[err_cnt_key + '1'] = err_cnt.get(err_cnt_key + '1',0) + 1\n rec_diff += 1\n #print(\"{0}{1:{2}}\".format(delete, rec_diff, digits))\n #sys.stdout.write('.')\n pybuf = '\\b' * 7 + \"[%5d]\" % (rec_diff)\n sys.stdout.write(prbuf)\n sys.stdout.flush() \n self.rec_accu = float((rec-rec_diff))/rec \n f1.write(str(self.pred_prob[i]))\n f1.write(sep)\n f1.write(self.labels.idx2word[self.pred_code[i]]) \n f1.write(sep)\n f1.write(self.labels.idx2word[self.encodedYtestdata[i]])\n #f1.write(sep)\n #f1.write(self.raw_testX[i])\n f1.write(sep)\n f1.write(\" \".join(self.testX[i]))\n f1.write('\\n')\n '''\n #Create original data file for editing to corrrect data based on prediction.\n #original data is appended with prediction so that decision can be made by reviewer\n f2.write(self.raw_testX[i])\n f2.write(sep)\n f2.write(self.labels.idx2word[self.pred_code[i]]) \n f2.write('\\n')\n else:\n #Just dump write the original data as is.\n f2.write(self.raw_testX[i])\n f2.write(sep)\n f2.write(self.labels.idx2word[self.encodedYtestdata[i]])\n f2.write(sep)\n f2.write(self.labels.idx2word[self.pred_code[i]]) \n f2.write('\\n')\n '''\n #Just dump write the original data as is.\n #print(' '.join(self.testX[i]))\n #f2.write(self.labels.idx2word[self.encodedYtestdata[i]])\n #f2.write(sep)\n f2.write(self.labels.idx2word[self.pred_code[i]]) \n f2.write(sep)\n f2.write(' '.join(self.testX[i]))\n f2.write('\\n')\n \n prev_conv_ind = self.conv_ind1[i]\n \n prediction_log = \"\"\n accuracy = 0\n if data_only:\n print(\"Processes [{}] words / [{}] records\".format(len(self.raw_testX),rec))\n else:\n print(\" {} total size & {} errors Accuracy: {}\".format(rec,rec_diff,float(rec-rec_diff)/rec))\n prediction_log = ''.join(\" {} total size & {} errors Accuracy: {}\".format(rec,rec_diff,float(rec-rec_diff)/rec))\n accuracy = float(rec-rec_diff)/rec\n myCodedLabels = set(self.encodedYtestdata)\n myLabels = []\n for k in myCodedLabels:\n myLabel = self.labels.idx2word[k]\n #err = err_cnt[myLabel + '1']\n err = err_cnt.get( myLabel + '1',0)\n tot = err_cnt.get( myLabel + '0',0)\n #tot = err_cnt[self.labels.idx2word[myLabel]+'0']\n accu = (tot-err)/float(tot)*100\n print(\" Label[%20s] Total[%5d] error[%5d] Accuracy[%.2f%%]\" % (myLabel,tot,err,accu))\n prediction_log = prediction_log + \" Label[%20s] Total[%5d] error[%5d] Accuracy[%.2f%%]\" % (myLabel,tot,err,accu)\n\n self.perf.set_from_config(self.config)\n self.perf.set_from_vocab(self.vocab)\n self.perf.set_from_prediction(prediction_log, accuracy)\n\n def testTheModel(self,test_data_file,data_only=False,data_config_file=None):\n print(\"Executing test on TextClassificationModel[{}]...\".format(self.model_name))\n conv_key = self.config.dp_conv_key\n conv_data_key = self.config.dp_conv_data_key\n \n self.config.test_data_file = test_data_file #Save test data file for future reference.\n #Predict surviving chances (class 1 results)\n if data_only:\n self.buildTestData(test_data_file,data_only)\n else: \n self.buildTestData(test_data_file)\n\n \"\"\"\n #Get predictions\n layer = self.model.get_layer_variables_by_name(name='embedding')\n embeddings = layer.get_weights()\n embeddings_2d = np.array(embeddings[0])\n embd_dir = '../data/logger/embeddings/'\n embd_file = self.model_name + \"_\" + \"embeddings.npy\"\n np.save(embd_dir + embd_file, embeddings_2d)\n visualize = False\n if visualize:\n tsne_name = self.model_name\n viz = wvu.Visualize(ddir = self.datadir,\n tsne_data_dir = '../data/tsne/',\n image_file =tsne_name + '_' + 'tsne_vector_space.png',\n csv_file= tsne_name + '_' + 'tsne_result.csv',\n f_embeddings = embeddings_2d,\n reverse_dictionary = self.vocab.idx2word,\n n_components = 2,\n epoch = self.config.epoch)\n\n viz = wvu.Visualize(ddir=self.datadir,\n tsne_data_dir='../data/tsne/3D/',\n image_file=tsne_name + '_' + 'tsne_vector_space.png',\n csv_file=tsne_name + '_' + 'tsne_result.csv',\n f_embeddings=embeddings_2d,\n reverse_dictionary=self.vocab.idx2word,\n n_components=3,\n epoch=self.config.epoch)\n \"\"\"\n self.pred = self.model.predict(self.encodedXtestdata)\n self.pred_code = np.argmax(self.pred,axis=1)\n self.pred_prob = np.amax(self.pred,axis=1)\n \n #buid response object\n self.test_result = {}\n test_convdata = self.test_convdata\n k = 0 #counter/offset for pred_code. Required to match testX with predicted result in yhat\n \n for i,cdata in enumerate(self.test_convdata):\n #retirve conv data object content \n convdata = cdata[conv_data_key] \n convkey = cdata[conv_key]\n \n for j,sdata in enumerate(convdata):\n pred_key = \"{}_{}\".format(convkey,j) #since for sent level pred_code to original sent mapping cannot be done easily a composite key is gen\n res = {}\n res[self.config.tr_pred_label] = self.labels.idx2word[self.pred_code[k]]\n res[self.config.tr_pred_prob] = self.pred_prob[k]\n res[self.config.tr_label] = self.labels.idx2word[self.encodedYtestdata[k]]\n res[self.config.tr_decode_sent] = self.vocab.decodeSent( self.encodedXtestdata[k])\n res[self.config.tr_index] = k\n self.test_result[pred_key] = res\n \n #print(\"+++pred_key[{}]+++pred[{}]+++prob[{}]+++\".format(pred_key,self.labels.idx2word[self.pred_code[k]],self.pred_prob[k]))\n \n k += 1 #keep track of pred_code offset for updating pred_ind, can be used to to backtrack self.pred_code index\n \n self.printPrediction(data_only)\n self.getPredAsDFForText(data_only)\n '''\n if data_only == False:\n self.printDiff()\n '''\n \n def testTheModelForRawText(self,test_data,data_only=False,conv_id=0,text_id=0):\n #print(\"Executing test on NERModel[{}] for conv_id[{}] text_id[{}]...\".format(self.model_name,conv_id,text_id))\n #Predict surviving chances (class 1 results)\n data_key = self.config.dp_data_key \n self.buildTestDataFromRawText(test_data)\n\n #Get predictions\n self.pred = self.model.predict(self.encodedXtestdata)\n self.pred_code = np.argmax(self.pred,axis=1)\n self.pred_prob = np.amax(self.pred,axis=1)\n \n #buid response object\n self.test_result = {}\n res = {}\n res[self.config.tr_pred_label] = self.labels.idx2word[self.pred_code[i]]\n res[self.config.tr_pred_prob] = self.pred_prob[i]\n self.test_result[conv_id] = res\n \n return self.getPredAsDFForText(data_only=True)\n \n ''' \n getPredAsDFForText - dumps test data result in pandas DF (csv file) and also generates original test data file with updated tag where tag is wrongly predicted.\n ''' \n def getPredAsDFForText(self,data_only=False):\n #print(\"Generating predictions for NERModel[{}]...\".format(self.model_name))\n conv_key = self.config.dp_conv_key\n text_class = self.config.dp_sent_class\n conv_tag = self.config.dp_conv_tag\n conv_tag_buf = self.config.dp_conv_tag_buf\n conv_data_key = self.config.dp_conv_data_key\n data_key = self.config.dp_data_key \n raw_data_key = self.config.dp_raw_data_key\n \n sep = '|'\n \n p_df = pd.DataFrame(columns=[\n \"conv_id\",\n \"sent_id\",\n \"pr\",\n \"label\",\n \"text\"])\n\n with open(self.datadir + self.model_name + \"_\" + self.config.test_data_file + \".upd\",'w') as f1, open(self.datadir + self.model_name + \"_\" + self.config.test_data_file + \".diff\",'w') as f2:\n k = 0 #counter/offset for encodeTestXData. Required to pull encoded sentence.\n #iterate test data from self.test_convdata\n for i,cdata in enumerate(self.test_convdata):\n #if i >= 3:\n # break\n \n #retirve conv data object content \n convdata = cdata[conv_data_key] \n #convtag = cdata[conv_tag] #only when test is tagged test data. Ignore for this\n convkey = cdata[conv_key]\n convtagbuf = cdata[conv_tag_buf]\n \n \n #if data_only == False:\n #buf = convtagbuf + \" ##pred_label[\" + pred_label + \"] ##pred_prob[\" + str(pred_prob) + \"]\"\n f1.write( \"\\n\" + convtagbuf + \"\\n\\n\")\n \n convtext = \"\" \n for j,sdata in enumerate(convdata):\n #retirve conv response data object content \n pred_key = \"{}_{}\".format(convkey,j) #create pred_key to retrieve pred_code from self.test_result dictionary.\n test_response = self.test_result.get(pred_key)\n pred_label = test_response[self.config.tr_pred_label]\n pred_prob = test_response[self.config.tr_pred_prob]\n label = test_response[self.config.tr_label]\n decode_sent = test_response[self.config.tr_decode_sent]\n res_index = test_response[self.config.tr_index]\n \n if data_only == False:\n #buf = convtagbuf + \" ##pred_label[\" + pred_label + \"] ##pred_prob[\" + str(pred_prob) + \"]\"\n if sdata[text_class] != pred_label:\n f2.write(self.vocab.decodeSent(self.encodedXtestdata[res_index])\n + sep + label \n + sep + pred_label\n + sep + sdata[raw_data_key] + \"\\n\")\n \n if self.config.tr_tags_validation: \n if pred_label in self.config.tr_tags_to_validate:\n f1.write(sdata[raw_data_key] \n + \" ##\" + pred_label \n + \"] ##pred_prob[\" \n + str(pred_prob) \n + \"] ##\" + decode_sent\n + \"\\n\")\n else:\n f1.write(sdata[raw_data_key] + \"\\n\")\n else:\n #f1.write(sdata[raw_data_key] + \" ##\" + pred_label + \"\\n\")\n f1.write(sdata[raw_data_key] \n + \" ##\" + pred_label \n + \"] ##pred_prob[\" \n + str(pred_prob) \n + \"] ##\" + decode_sent\n + \"\\n\")\n else:\n f1.write(sdata[raw_data_key] + \"\\n\")\n else:\n f1.write(sdata[raw_data_key] + \"\\n\")\n \n k += 1 #maintain overall offset counter to our testX / encodeTextXData\n p_df.loc[p_df.shape[0]] = [ convkey,\n j,\n str(pred_prob),\n pred_label,\n #' '.join(sdata[raw_data_key])]\n sdata[raw_data_key]]\n \n \n #write pandas DF to CSV file. \n p_df.to_csv(self.datadir + self.model_name + '_conv_pred_df.csv',index=False,sep='|')\n #print(\"Processes [{}] words / [{}] records\".format(len(self.testX),i))\n \n return p_df\n\nif __name__ == \"__main__\":\n model_name = \"sent_tags5000\"\n #model_name = \"sent_tags10000\"\n \n textclassiModel = TextClassificationModel(model_name,\"train.txt\",\"../data/sent/\",modeldir=\"../data/model/SENT/\",config_data={})\n #textclassiModel = TextClassificationModel(model_name,\"sent10000_train.txt\",\"../data/chat/\")\n \n textclassiModel.trainTheModel()\n #textclassiModel.loadModel('text_model_' + model_name + '.tfl')\n \n textclassiModel.testTheModel(\"sent5000_set2_test.txt\",data_only=False)\n #textclassiModel.testTheModel(\"sent5000_set2_test.txt\",data_only=False)\n \n #textclassiModel.testTheModelForRawText(test_data=\"I am afraid my phone is not working. Can you check my account if it is active?\",data_only=True,conv_id=1,text_id=2)\n \n","sub_path":"src/sent2.py","file_name":"sent2.py","file_ext":"py","file_size_in_byte":37581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"442010772","text":"import json\nfrom sys import path\n\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import r2_score\nfrom skopt.learning.gaussian_process import kernels\n\nfrom src.gpr import gprnew\n\n\nclass Coordinator(object):\n def __init__(self, map_data, sensors: set, k_names=None, d=1.0):\n if k_names is None:\n k_names = [\"RBF\"] * len(sensors)\n self.map_data = map_data\n self.k_names = k_names # \"RBF\" Matern\" \"RQ\"\n self.sensors = sensors\n self.gps = dict()\n self.train_inputs = [np.array([[], []])]\n self.train_targets = dict()\n self.proportion = d\n\n self.mus = dict()\n self.stds = dict()\n self.has_calculated = dict()\n\n for sensor, kernel in zip(sensors, k_names):\n if kernel == \"RBF\": # \"RBF\" Matern\" \"RQ\"\n self.gps[sensor] = gprnew.GaussianProcessRegressor(kernel=kernels.RBF(100), alpha=1e-7)\n self.train_targets[sensor] = np.array([])\n self.mus[sensor] = np.array([])\n self.stds[sensor] = np.array([])\n self.has_calculated[sensor] = False\n\n self.all_vector_pos = np.mgrid[0:self.map_data.shape[1]:1, 0:self.map_data.shape[0]:1].reshape(2, -1).T\n self.vector_pos = np.fliplr(np.asarray(np.where(self.map_data == 0)).reshape(2, -1).T)\n\n self.splitted_goals = []\n self.nans = None\n self.fpx, self.fpy = self.obtain_points()\n self.fpx = list(self.fpx)\n self.fpy = list(self.fpy)\n self.current_goal = np.array([self.fpx.pop(0), self.fpy.pop(0)])\n\n def initialize_data_gpr(self, data: list):\n self.train_inputs = np.array(data[0][\"pos\"]).reshape(-1, 2)\n for key in data[0].keys():\n if key != \"pos\":\n self.train_targets[key] = np.array([data[0][key]])\n if len(data) > 1:\n for nd in data[1:]:\n self.add_data(nd)\n self.fit_data()\n\n def add_data(self, new_data):\n self.train_inputs = np.append(self.train_inputs, new_data[\"pos\"]).reshape(-1, 2)\n for key in new_data.keys():\n if key != \"pos\":\n self.train_targets[key] = np.append(self.train_targets[key], new_data[key])\n\n def fit_data(self):\n print(self.train_inputs)\n for key in self.sensors:\n self.gps[key].fit(self.train_inputs, self.train_targets[key])\n self.has_calculated[key] = False\n\n def surrogate(self, _x=None, return_std=False, keys=None):\n if keys is None:\n keys = self.sensors\n if _x is None:\n _x = self.vector_pos\n\n for key in keys:\n if not self.has_calculated[key]:\n mu, std = self.gps[key].predict(_x, True)\n self.mus[key] = mu\n self.stds[key] = std\n self.has_calculated[key] = True\n if return_std:\n return [(self.mus[key], self.stds[key]) for key in keys]\n else:\n return [self.mus[key] for key in keys]\n\n def generate_new_goal(self, pose=np.zeros((1, 3))):\n if len(self.current_goal) == 0:\n self.current_goal = np.array([self.fpx.pop(0), self.fpy.pop(0)]).T\n beacons_splitted = []\n vect_dist = np.subtract(self.current_goal, pose[:2])\n ang = np.arctan2(vect_dist[1], vect_dist[0])\n d = np.exp(np.min([self.gps[key].kernel_.theta[0] for key in list(self.sensors)])) * self.proportion\n for di in np.arange(0, np.linalg.norm(vect_dist), d)[1:]:\n mini_goal = np.array([di * np.cos(ang) + pose[0], di * np.sin(ang) + pose[1]]).astype(np.int)\n if self.map_data[mini_goal[1], mini_goal[0]] == 0:\n beacons_splitted.append(mini_goal)\n beacons_splitted.append(self.current_goal)\n new_pos = np.array(beacons_splitted[0])\n new_pos = np.append(new_pos, 0)\n if len(beacons_splitted) == 1:\n self.current_goal = []\n return new_pos\n\n def get_mse(self, y_true, key=None):\n if key is None:\n key = list(self.sensors)[0]\n if self.nans is None:\n self.nans = np.isnan(y_true)\n return mse(y_true[~self.nans], self.surrogate(keys=[key])[0])\n\n def get_score(self, y_true, key=None):\n if key is None:\n key = list(self.sensors)[0]\n if self.nans is None:\n self.nans = np.isnan(y_true)\n return r2_score(y_true[~self.nans], self.surrogate(keys=[key])[0])\n\n def obtain_points(self):\n with open(path[-1] + \"/data/Map/Ypacarai/beacons_normalized.json\") as f:\n scale = 1407.6\n data = json.load(f)\n xpos = data['x1 ']['xRel'] * scale\n ypos = data['x1 ']['yRel'] * scale\n beacons = np.array([xpos, ypos])\n beacons = np.expand_dims(beacons, 0)\n for i in range(len(data) - 1):\n name = 'x' + str(i + 2) + ' '\n xpos = data[name]['xRel'] * scale\n ypos = data[name]['yRel'] * scale\n beacons = np.concatenate([beacons, [np.array([xpos, ypos])]])\n perm_matrix = [25, 59, 26, 7, 44, 2, 42, 55, 21, 30, 53, 22,\n 52, 11, 51, 20, 50, 18, 31, 8, 33, 10, 45, 54, 43, 48, 39,\n 4, 46, 37, 38, 1, 32, 3, 19, 49, 14, 58, 9, 41, 5, 24, 36,\n 12, 47, 6, 35, 17, 57, 23, 16, 29, 13, 56, 40, 0, 28, 27, 15, 34]\n\n perm_matrix = np.roll(perm_matrix, np.random.randint(0, 60))\n\n beacons_splitted = np.round(np.array(beacons[perm_matrix])).astype(np.int)\n\n return beacons_splitted[:, 0], beacons_splitted[:, 1]\n","sub_path":"bin/v2/Comparison/ga_gym_coordinator.py","file_name":"ga_gym_coordinator.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"58122414","text":"\n\nfrom flask import render_template, Blueprint, url_for, \\\n redirect, flash, request, abort, session\nfrom flask_login import login_required\nfrom project.server import oauth2\nfrom project.server.utils import youtube as yu\n\nyoutube_blueprint = Blueprint('youtube', __name__, url_prefix='/youtube')\nYOUTUBE_SCOPE = 'https://www.googleapis.com/auth/youtube.readonly'\nFORCE_SSL = 'https://www.googleapis.com/auth/youtube.force-ssl'\n\nimport json\n\n\n@youtube_blueprint.route('/', methods=['GET'])\n@login_required\ndef index():\n if oauth2.has_credentials():\n channel_id, data = yu.channel_info(oauth2.http())\n session['channel_id'] = channel_id\n playlists = yu.list_playlist(oauth2.http(), channel_id)\n top_videos = yu.search_my_video(oauth2.http())\n return render_template('youtube/index.html',data=data, playlists=playlists, videos=top_videos)\n else:\n return render_template('youtube/index.html')\n\n\n@youtube_blueprint.route('/connect', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE, FORCE_SSL])\ndef connect():\n return redirect(url_for('youtube.index'))\n\n@youtube_blueprint.route('/playlists', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE])\ndef list_playlist():\n channel_id = None\n http = oauth2.http()\n\n if 'channel_id' in session:\n channel_id = session['channel_id']\n else:\n channel_id = yu.get_channel_id(http)\n\n playlists = yu.list_playlist(http, channel_id=channel_id, limit=9)\n return render_template('youtube/playlists.html', playlists=playlists)\n\n\n@youtube_blueprint.route('/playlists/', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE])\ndef view_playlist(id):\n channel_id = None\n http = oauth2.http()\n\n if 'channel_id' in session:\n channel_id = session['channel_id']\n else:\n channel_id = yu.get_channel_id(http)\n\n playlists = yu.list_playlist(http, channel_id=channel_id, limit=9)\n playlist = yu.get_playlist(http, id)\n playlist_items = yu.list_playlist_item(http, id)\n return render_template('youtube/playlist.html', playlist=playlist, playlist_items= playlist_items, playlists=playlists)\n\n\n@youtube_blueprint.route('/videos', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE])\ndef list_video():\n videos = yu.search_my_video(oauth2.http(), limit=18)\n return render_template('youtube/videos.html',videos=videos)\n\n@youtube_blueprint.route('/videos/', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE, FORCE_SSL])\ndef view_video(id):\n video = yu.get_video(oauth2.http(), id)\n comments = yu.list_comment_for_video(oauth2.http(), id)\n return render_template('youtube/video.html',video=video, comments=comments)\n\n@youtube_blueprint.route('/video_page/', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE, FORCE_SSL])\ndef video_page(token):\n videos = yu.search_my_video(oauth2.http(), page_token=token, limit=18)\n return json.dumps(videos)\n\n@youtube_blueprint.route('/videos//comments/', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE])\ndef comment_json(id, page_token):\n comments = yu.list_comment_for_video(oauth2.http(), id, token=page_token)\n return {'status': \"OK\", 'data': json.dumps(comments)}\n\n@youtube_blueprint.route('/search', methods=['GET'])\n@login_required\n@oauth2.required(scopes=[YOUTUBE_SCOPE])\ndef search():\n query = request.args.get('q', '')\n videos = yu.search_my_video(oauth2.http(), search_str=query)\n return render_template('youtube/search.html',videos=videos, query=query)\n","sub_path":"project/server/controllers/youtube_controller.py","file_name":"youtube_controller.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"95031794","text":"from __future__ import absolute_import\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\n\ndb = SQLAlchemy()\n\n\ndef initialize_db(app):\n db.init_app(app)\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(80),\n index=True,\n unique=True,\n nullable=False)\n username = db.Column(db.String(30),\n index=False,\n unique=True,\n nullable=False) # oauth 의 경우 id 를 username 으로 초기설정\n password = db.Column(db.String(30),\n index=False,\n unique=False,\n nullable=False)\n profile = db.Column(db.Text,\n index=False,\n unique=False,\n nullable=True)\n pic_url = db.Column(db.Text,\n index=False,\n unique=False,\n nullable=True) # null 일 경우 클라이언트에서 초기 이미지로 ���리\n timezone = db.Column(db.String(80),\n index=False,\n unique=False,\n nullable=True)\n admin = db.Column(db.Boolean,\n index=False,\n default=False,\n unique=False,\n nullable=False)\n created = db.Column(db.DateTime,\n nullable=False,\n default=datetime.utcnow)\n updated = db.Column(db.DateTime,\n onupdate=datetime.utcnow)\n routines = db.relationship('Routine',\n cascade=\"all,delete\",\n backref='user',\n lazy=True)\n\n\nclass Routine(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer,\n db.ForeignKey('user.id'),\n index=True,\n nullable=False)\n title = db.Column(db.String(80),\n nullable=False)\n mon = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n tue = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n wed = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n thu = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n fri = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n sat = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n sun = db.Column(db.Boolean,\n index=True,\n unique=False,\n nullable=False,\n default=False)\n alarm = db.Column(db.Boolean,\n index=False,\n unique=False,\n nullable=False,\n default=True)\n time = db.Column(db.String(30),\n unique=False,\n nullable=True)\n description = db.Column(db.Text,\n index=False,\n unique=False,\n nullable=True)\n category = db.Column(db.String(80),\n index=True,\n unique=False,\n nullable=True)\n color_id = db.Column(db.Integer,\n db.ForeignKey('color.id'),\n nullable=False)\n created = db.Column(db.DateTime,\n nullable=False,\n default=datetime.utcnow)\n updated = db.Column(db.DateTime,\n onupdate=datetime.utcnow)\n successes = db.relationship('Success',\n cascade=\"all,delete\",\n backref='routine',\n lazy=True)\n\n def convert_to_routine_dto(self):\n import dataclasses\n from clapme.views.interface import RoutineDto\n dto = RoutineDto(\n id=self.id,\n title=self.title,\n alarm=self.alarm,\n time=self.time,\n mon=self.mon,\n tue=self.tue,\n wed=self.wed,\n thu=self.thu,\n fri=self.fri,\n sat=self.sat,\n sun=self.sun,\n color=self.color.hex_code,\n description=self.description\n )\n return dataclasses.asdict(dto)\n\n def convert_to_routine_status_dto(self):\n import dataclasses\n from clapme.views.interface import RoutineStatusDto\n dto = RoutineStatusDto(\n id=self.id,\n title=self.title,\n alarm=self.alarm,\n time=self.time,\n color=self.color.hex_code,\n success=False\n )\n return dataclasses.asdict(dto)\n\n\nclass Success(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n routine_id = db.Column(db.Integer,\n db.ForeignKey('routine.id'),\n nullable=False)\n date_str = db.Column(db.String(80),\n index=True,\n unique=False,\n nullable=False)\n day = db.Column(db.String(80),\n index=True,\n unique=False,\n nullable=False)\n created = db.Column(db.DateTime,\n nullable=False,\n default=datetime.utcnow)\n\n\nclass Idea(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(80),\n nullable=False)\n sub_title = db.Column(db.String(80),\n nullable=True)\n contents = db.Column(db.Text,\n nullable=True)\n pic_url = db.Column(db.Text,\n nullable=True)\n routine_1 = db.Column(db.Text,\n nullable=True)\n routine_2 = db.Column(db.Text,\n nullable=True)\n routine_3 = db.Column(db.Text,\n nullable=True)\n routine_4 = db.Column(db.Text,\n nullable=True)\n routine_5 = db.Column(db.Text,\n nullable=True)\n routine_6 = db.Column(db.Text,\n nullable=True)\n routine_7 = db.Column(db.Text,\n nullable=True)\n routine_8 = db.Column(db.Text,\n nullable=True)\n routine_9 = db.Column(db.Text,\n nullable=True)\n\n def convert_to_routine_sample_dto(self):\n import dataclasses\n from clapme.views.interface import IdeaDto\n\n samples = [self.routine_1,\n self.routine_2,\n self.routine_3,\n self.routine_4,\n self.routine_5,\n self.routine_6,\n self.routine_7,\n self.routine_8,\n self.routine_9]\n\n routines = []\n for sample in samples:\n if sample is not None:\n time = sample[1:5]\n title = sample[7:len(sample)]\n routines.append({'time': time, 'title': title})\n\n dto = IdeaDto(\n title=self.title,\n subTitle=self.sub_title,\n contents=self.contents,\n picUrl=self.pic_url,\n routines=routines\n )\n return dataclasses.asdict(dto)\n\n\n\nclass Color(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n hex_code = db.Column(db.String(30),\n index=False,\n unique=False)\n routines = db.relationship('Routine',\n cascade=\"all,delete\",\n backref='color',\n lazy=True)\n","sub_path":"clapme/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"314586247","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/cuteSV/cuteSV_Description.py\n# Compiled at: 2020-04-17 02:18:29\n# Size of source mod 2**32: 9401 bytes\n\"\"\" \n * All rights Reserved, Designed By HIT-Bioinformatics \n * @Title: cuteSV_Description.py\n * @author: tjiang\n * @date: Apr 17th 2020\n * @version V1.0.5 \n\"\"\"\nimport argparse\nVERSION = '1.0.5'\n\nclass cuteSVdp(object):\n __doc__ = '\\n\\tDetailed descriptions of cuteSV version and its parameters.\\n\\n\\t'\n USAGE = '\\tLong read based fast and accurate SV detection with cuteSV.\\n\\t\\n\\tCurrent version: v%s\\n\\tAuthor: Tao Jiang\\n\\tContact: tjiang@hit.edu.cn\\n\\n\\n\\tSuggestions:\\n\\n\\tFor PacBio CLR/ONT data:\\n\\t\\t--max_cluster_bias_INS\\t\\t100\\n\\t\\t--diff_ratio_merging_INS\\t0.2\\n\\t\\t--diff_ratio_filtering_INS\\t0.6\\n\\t\\t--diff_ratio_filtering_DEL\\t0.7\\n\\tFor PacBio CCS(HIFI) data:\\n\\t\\t--max_cluster_bias_INS\\t\\t200\\n\\t\\t--diff_ratio_merging_INS\\t0.65\\n\\t\\t--diff_ratio_filtering_INS\\t0.65\\n\\t\\t--diff_ratio_filtering_DEL\\t0.35\\n\\n\\n\\t' % VERSION\n\n\ndef parseArgs(argv):\n parser = argparse.ArgumentParser(prog='cuteSV', description=(cuteSVdp.USAGE),\n formatter_class=(argparse.RawDescriptionHelpFormatter))\n parser.add_argument('--version', '-v', action='version',\n version='%(prog)s {version}'.format(version=VERSION))\n parser.add_argument('input', metavar='[BAM]',\n type=str,\n help='Sorted .bam file form NGMLR or Minimap2.')\n parser.add_argument('output', type=str,\n help='Output VCF format file.')\n parser.add_argument('work_dir', type=str,\n help='Work-directory for distributed jobs')\n parser.add_argument('-t', '--threads', help='Number of threads to use.[%(default)s]',\n default=16,\n type=int)\n parser.add_argument('-b', '--batches', help='Batch of genome segmentation interval.[%(default)s]',\n default=10000000,\n type=int)\n parser.add_argument('-S', '--sample', help='Sample name/id',\n default='NULL',\n type=str)\n GroupSignaturesCollect = parser.add_argument_group('Collection of SV signatures')\n GroupSignaturesCollect.add_argument('-p', '--max_split_parts', help='Maximum number of split segments a read may be aligned before it is ignored.[%(default)s]',\n default=7,\n type=int)\n GroupSignaturesCollect.add_argument('-q', '--min_mapq', help='Minimum mapping quality value of alignment to be taken into account.[%(default)s]',\n default=20,\n type=int)\n GroupSignaturesCollect.add_argument('-r', '--min_read_len', help='Ignores reads that only report alignments with not longer than bp.[%(default)s]',\n default=500,\n type=int)\n GroupSignaturesCollect.add_argument('-md', '--merge_del_threshold', help='Maximum distance of deletion signals to be merged.[%(default)s]',\n default=0,\n type=int)\n GroupSignaturesCollect.add_argument('-mi', '--merge_ins_threshold', help='Maximum distance of insertion signals to be merged.[%(default)s]',\n default=100,\n type=int)\n GroupSVCluster = parser.add_argument_group('Generation of SV clusters')\n GroupSVCluster.add_argument('-s', '--min_support', help='Minimum number of reads that support a SV to be reported.[%(default)s]',\n default=10,\n type=int)\n GroupSVCluster.add_argument('-l', '--min_size', help='Minimum size of SV to be reported.[%(default)s]',\n default=30,\n type=int)\n GroupSVCluster.add_argument('-L', '--max_size', help='Maximum size of SV to be reported.[%(default)s]',\n default=100000,\n type=int)\n GroupSVCluster.add_argument('-sl', '--min_siglength', help='Minimum length of SV signal to be extracted.[%(default)s]',\n default=10,\n type=int)\n GroupGenotype = parser.add_argument_group('Computing genotypes')\n GroupGenotype.add_argument('--genotype', help='Enable to generate genotypes.',\n action='store_true')\n GroupGenotype.add_argument('--hom', help='Threshold on allele frequency for homozygous.[%(default)s]',\n default=0.8,\n type=float)\n GroupGenotype.add_argument('--het', help='Threshold on allele frequency for heterozygous.[%(default)s].',\n default=0.2,\n type=float)\n GroupAdvanced = parser.add_argument_group('Advanced')\n GroupAdvanced.add_argument('--max_cluster_bias_INS', help='Maximum distance to cluster read together for insertion.[%(default)s]',\n default=100,\n type=int)\n GroupAdvanced.add_argument('--diff_ratio_merging_INS', help='Do not merge breakpoints with basepair identity more than [%(default)s] for insertion.',\n default=0.2,\n type=float)\n GroupAdvanced.add_argument('--diff_ratio_filtering_INS', help='Filter breakpoints with basepair identity less than [%(default)s] for insertion.',\n default=0.6,\n type=float)\n GroupAdvanced.add_argument('--max_cluster_bias_DEL', help='Maximum distance to cluster read together for deletion.[%(default)s]',\n default=200,\n type=int)\n GroupAdvanced.add_argument('--diff_ratio_merging_DEL', help='Do not merge breakpoints with basepair identity more than [%(default)s] for deletion.',\n default=0.3,\n type=float)\n GroupAdvanced.add_argument('--diff_ratio_filtering_DEL', help='Filter breakpoints with basepair identity less than [%(default)s] for deletion.',\n default=0.7,\n type=float)\n GroupAdvanced.add_argument('--max_cluster_bias_INV', help='Maximum distance to cluster read together for inversion.[%(default)s]',\n default=500,\n type=int)\n GroupAdvanced.add_argument('--max_cluster_bias_DUP', help='Maximum distance to cluster read together for duplication.[%(default)s]',\n default=500,\n type=int)\n GroupAdvanced.add_argument('--max_cluster_bias_TRA', help='Maximum distance to cluster read together for translocation.[%(default)s]',\n default=50,\n type=int)\n GroupAdvanced.add_argument('--diff_ratio_filtering_TRA', help='Filter breakpoints with basepair identity less than [%(default)s] for translocation.',\n default=0.6,\n type=float)\n args = parser.parse_args(argv)\n return args\n\n\ndef Generation_VCF_header(file, contiginfo, sample):\n file.write('##fileformat=VCFv4.2\\n')\n file.write('##source=cuteSV-%s\\n' % VERSION)\n import time\n file.write('##fileDate=%s\\n' % time.strftime('%Y-%m-%d %H:%M:%S %w-%Z', time.localtime()))\n for i in contiginfo:\n file.write('##contig=\\n' % (i[0], i[1]))\n\n file.write('##ALT=\\n')\n file.write('##ALT=\\n')\n file.write('##ALT=\\n')\n file.write('##ALT=\\n')\n file.write('##ALT=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##INFO=\\n')\n file.write('##FORMAT=\\n')\n file.write('##FORMAT=\\n')\n file.write('##FORMAT=\\n')\n file.write('#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\t%s\\n' % sample)","sub_path":"pycfiles/cuteSV-1.0.5-py3.7/cuteSV_Description.cpython-37.py","file_name":"cuteSV_Description.cpython-37.py","file_ext":"py","file_size_in_byte":8374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"505745794","text":"from django.db import models, DatabaseError\n\nfrom ..base import BaseModel\n\nfrom typing import Optional\n\nfrom core.globals import logger\n\n\nclass ChatMemberCountAnalyzerMetaDataQuerySet(models.QuerySet):\n def update_or_create_analyzer(self, *, defaults: dict, **kwargs) -> Optional['ChatMemberCountAnalyzerMetaData']:\n try:\n return self.update_or_create(\n defaults=defaults,\n **kwargs\n )[0]\n except DatabaseError as e:\n logger.exception(e)\n except Exception as e:\n logger.exception(e)\n\n return None\n\n def update_analyzer(self, **kwargs) -> bool:\n try:\n return bool(\n self.update(\n **kwargs\n )\n )\n except DatabaseError as e:\n logger.exception(e)\n except Exception as e:\n logger.exception(e)\n\n return False\n\n def filter_by_id(self, *, id: int) -> 'ChatMemberCountAnalyzerMetaDataQuerySet':\n return self.filter(id=id)\n\n\nclass ChatMemberCountAnalyzerMetaDataManager(models.Manager):\n def get_queryset(self) -> ChatMemberCountAnalyzerMetaDataQuerySet:\n return ChatMemberCountAnalyzerMetaDataQuerySet(self.model, using=self._db)\n\n def update_or_create_analyzer(\n self,\n *,\n chat_id: int,\n enabled: bool,\n ) -> Optional['ChatMemberCountAnalyzerMetaData']:\n if chat_id is None:\n return None\n\n return self.get_queryset().update_or_create(\n id=chat_id,\n defaults={\n 'enabled': enabled,\n }\n )\n\n def update_analyzer(self, id: int, **kwargs) -> bool:\n return self.get_queryset().filter_by_id(id=id).update_analyzer(**kwargs)\n\n\nclass ChatMemberCountAnalyzerMetaData(BaseModel):\n id = models.BigIntegerField(primary_key=True) # `chat__chat_id`\n\n enabled = models.BooleanField(default=False)\n first_analyzed_ts = models.BigIntegerField(null=True, blank=True)\n last_analyzed_ts = models.BigIntegerField(null=True, blank=True)\n disable_ts = models.BigIntegerField(null=True, blank=True)\n disable_reason = models.TextField(max_length=256, null=True, blank=True)\n\n ######################################\n # `chat` : chat this analyzer metadata belongs to\n\n objects = ChatMemberCountAnalyzerMetaDataManager()\n\n class Meta:\n verbose_name_plural = 'Analyzers (chat member count)'\n\n def __str__(self):\n return f\"{self.id} : {self.enabled}\"\n\n def update_fields(self, **kwargs) -> bool:\n return ChatMemberCountAnalyzerMetaData.objects.update_analyzer(id=self.id, **kwargs)\n","sub_path":"backend/telegram/models/analyzers/chat_member_count_analyzer.py","file_name":"chat_member_count_analyzer.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"478813388","text":"# 백준 10816 숫자 카드2\n\nfrom collections import Counter # collections 모듈의 Counter 사용 딕셔너리의 확장기능이다.\n\nN = int(input())\narrN = list(map(int, input().split(' ')))\n\nM = int(input())\narrM = list(map(int, input().split(' ')))\n\narrN = Counter(arrN) # ex) arrN = { 6 3 2 10 10 10} -> [(6 : 1), (3 : 1), (2 : 1), (10 : 3)]\nfor i in arrM:\n print(arrN[i], end=\" \")\n","sub_path":"2020_07_30_Algorithm/python/NumberCard2_10816.py","file_name":"NumberCard2_10816.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"509070996","text":"\"\"\"Test settings.\"\"\"\nfrom collections import OrderedDict\nimport itertools\nimport sys\nimport os\nimport pytest\nimport json\nfrom textwrap import dedent\nimport toml\nimport yaml\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nfrom climatecontrol import settings_parser # noqa: E402\n\n\n@pytest.fixture\ndef mock_os_environ(monkeypatch):\n \"\"\"Mock os environment and set a few settings with environment variables.\"\"\"\n mock_environ = OrderedDict([\n ('test_stuff', 2),\n ('TEST_STUFF', 5),\n ('TEST_STUFF_TESTGROUP__TEST_VAR', 6),\n ('TEST_STUFF_TESTGROUP__TESTVAR', 7),\n ('TEST_STUFFTESTGROUP__TESTVAR', 8),\n ('TEST_STUFF_TESTGROUP_TEST_VAR', 9),\n ])\n monkeypatch.setattr(os, 'environ', mock_environ)\n\n\n@pytest.fixture\ndef mock_empty_os_environ(monkeypatch):\n \"\"\"Mock os environment so it seems completely empty.\"\"\"\n mock_environ = {}\n monkeypatch.setattr(os, 'environ', mock_environ)\n\n\n@pytest.fixture\ndef mock_settings_prefix(monkeypatch):\n \"\"\"Mock default settings prefix.\"\"\"\n monkeypatch.setattr(settings_parser.Settings, 'prefix', 'TEST_STUFF')\n\n\n@pytest.fixture(params=list(itertools.product(['.toml', '.yml', '.yaml', '.json'], [False, True])))\ndef file_extension(request, monkeypatch):\n \"\"\"Fixture for providing file extension to use in settings files.\n\n This fixture is parametrized to mock out all \"unneeded\" modules to make\n sure that unneeded libraries do not need to be installed.\n\n \"\"\"\n ext, mock_other = request.param\n if mock_other:\n if ext == '.toml':\n monkeypatch.setattr('climatecontrol.file_loaders.yaml', None)\n elif ext in {'.yml', '.yaml'}:\n monkeypatch.setattr('climatecontrol.file_loaders.toml', None)\n else:\n monkeypatch.setattr('climatecontrol.file_loaders.yaml', None)\n monkeypatch.setattr('climatecontrol.file_loaders.toml', None)\n return ext\n\n\n@pytest.fixture\ndef mock_settings_file(request, monkeypatch, tmpdir, file_extension):\n \"\"\"Temporarily write a settings file and return the filepath and the expected settings outcome.\"\"\"\n ext = file_extension\n p = tmpdir.mkdir('sub').join('settings' + ext)\n\n expected_result = {\n 'testgroup': {\n 'testvar': 123\n }, 'othergroup': {\n 'blabla': 555\n }\n }\n\n if ext == '.toml':\n p.write(toml.dumps(expected_result))\n elif ext in ['.yml', '.yaml']:\n p.write('---\\n' + yaml.dump(expected_result))\n elif ext == '.json':\n p.write(json.dumps(expected_result))\n else:\n raise NotImplementedError('Invalid file extension :{}.'.format(ext))\n\n return str(p), expected_result\n\n\n@pytest.fixture\ndef mock_settings_files(request, monkeypatch, tmpdir, mock_settings_file, file_extension):\n \"\"\"Temporarily write multiple settings file and return the filepaths and the expected settings outcome.\"\"\"\n subdir = tmpdir.mkdir('sub2')\n ext = file_extension\n\n # File to load in settings file by adding \"from_file\" to the variable we want.\n inline_path = subdir.join('secret.txt')\n inline_path.write('foo')\n\n if ext == '.toml':\n s1 = dedent(\"\"\"\\\n [testgroup]\n testvar = 123\n testvar_inline_1_from_file = \"{}\"\n\n [othergroup]\n blabla = 55\n testvar_inline_2_from_file = \"{}\"\n \"\"\".format(str(inline_path), str(inline_path)))\n\n s2 = dedent(\"\"\"\\\n\n [othergroup]\n blabla = 555\n testvar_inline_2 = \"bar\"\n \"\"\")\n elif ext in ('.yml', '.yaml'):\n s1 = dedent(\"\"\"\\\n testgroup:\n testvar: 123\n testvar_inline_1_from_file: {}\n\n othergroup:\n blabla: 55\n testvar_inline_2_from_file: {}\n \"\"\".format(str(inline_path), str(inline_path)))\n\n s2 = dedent(\"\"\"\\\n\n othergroup:\n blabla: 555\n testvar_inline_2: bar\n \"\"\")\n elif ext == '.json':\n s1 = dedent(\"\"\"\\\n {\n \"testgroup\": {\"testvar\": 123, \"testvar_inline_1_from_file\": \"%s\"},\n \"othergroup\": {\"blabla\": 55, \"testvar_inline_2_from_file\": \"%s\"}\n }\n \"\"\") % (str(inline_path), str(inline_path))\n\n s2 = dedent(\"\"\"\\\n {\"othergroup\": {\"blabla\": 555, \"testvar_inline_2\": \"bar\"}}\n \"\"\")\n else:\n raise NotImplementedError('Invalid file extension :{}.'.format(ext))\n p1 = subdir.join('settings' + ext)\n p1.write(s1)\n p2 = subdir.join('settings2' + ext)\n p2.write(s2)\n\n expected_result = {\n 'testgroup': {\n 'testvar': 123,\n 'testvar_inline_1': 'foo'\n }, 'othergroup': {\n 'blabla': 555, # Overridden by file 2\n 'testvar_inline_2': 'bar' # Overridden by file 2\n }\n }\n return [str(p1), str(p2)], expected_result\n\n\n@pytest.fixture\ndef mock_env_settings_file(mock_os_environ, mock_settings_file):\n \"\"\"Set the settings file env variable to a temporary settings file.\"\"\"\n os.environ['TEST_STUFF_SETTINGS_FILE'] = mock_settings_file[0]\n return mock_settings_file\n\n\n@pytest.fixture\ndef mock_env_parser(mocker):\n \"\"\"Mock out environment variable parser.\"\"\"\n return mocker.patch('climatecontrol.settings_parser.EnvParser')\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"150182249","text":"# -*- coding: utf-8 -*-\n# Copyright 2022 Google LLC\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#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nfrom google.protobuf import field_mask_pb2 # type: ignore\nfrom google.protobuf import timestamp_pb2 # type: ignore\nfrom google.rpc import status_pb2 # type: ignore\nimport proto # type: ignore\n\nfrom google.cloud.dialogflow_v2beta1.types import gcs\n\n__protobuf__ = proto.module(\n package=\"google.cloud.dialogflow.v2beta1\",\n manifest={\n \"Document\",\n \"GetDocumentRequest\",\n \"ListDocumentsRequest\",\n \"ListDocumentsResponse\",\n \"CreateDocumentRequest\",\n \"ImportDocumentsRequest\",\n \"ImportDocumentTemplate\",\n \"ImportDocumentsResponse\",\n \"DeleteDocumentRequest\",\n \"UpdateDocumentRequest\",\n \"ExportOperationMetadata\",\n \"KnowledgeOperationMetadata\",\n \"ReloadDocumentRequest\",\n },\n)\n\n\nclass Document(proto.Message):\n r\"\"\"A knowledge document to be used by a\n [KnowledgeBase][google.cloud.dialogflow.v2beta1.KnowledgeBase].\n\n For more information, see the `knowledge base\n guide `__.\n\n Note: The ``projects.agent.knowledgeBases.documents`` resource is\n deprecated; only use ``projects.knowledgeBases.documents``.\n\n This message has `oneof`_ fields (mutually exclusive fields).\n For each oneof, at most one member field can be set at the same time.\n Setting any member of the oneof automatically clears all other\n members.\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n name (str):\n Optional. The document resource name. The name must be empty\n when creating a document. Format:\n ``projects//locations//knowledgeBases//documents/``.\n display_name (str):\n Required. The display name of the document.\n The name must be 1024 bytes or less; otherwise,\n the creation request fails.\n mime_type (str):\n Required. The MIME type of this document.\n knowledge_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]):\n Required. The knowledge type of document\n content.\n content_uri (str):\n The URI where the file content is located.\n\n For documents stored in Google Cloud Storage, these URIs\n must have the form ``gs:///``.\n\n NOTE: External URLs must correspond to public webpages,\n i.e., they must be indexed by Google Search. In particular,\n URLs for showing documents in Google Cloud Storage (i.e. the\n URL in your browser) are not supported. Instead use the\n ``gs://`` format URI described above.\n\n This field is a member of `oneof`_ ``source``.\n content (str):\n The raw content of the document. This field is only\n permitted for EXTRACTIVE_QA and FAQ knowledge types. Note:\n This field is in the process of being deprecated, please use\n raw_content instead.\n\n This field is a member of `oneof`_ ``source``.\n raw_content (bytes):\n The raw content of the document. This field is only\n permitted for EXTRACTIVE_QA and FAQ knowledge types.\n\n This field is a member of `oneof`_ ``source``.\n enable_auto_reload (bool):\n Optional. If true, we try to automatically reload the\n document every day (at a time picked by the system). If\n false or unspecified, we don't try to automatically reload\n the document.\n\n Currently you can only enable automatic reload for documents\n sourced from a public url, see ``source`` field for the\n source types.\n\n Reload status can be tracked in ``latest_reload_status``. If\n a reload fails, we will keep the document unchanged.\n\n If a reload fails with internal errors, the system will try\n to reload the document on the next day. If a reload fails\n with non-retriable errors (e.g. PERMISSION_DENIED), the\n system will not try to reload the document anymore. You need\n to manually reload the document successfully by calling\n ``ReloadDocument`` and clear the errors.\n latest_reload_status (google.cloud.dialogflow_v2beta1.types.Document.ReloadStatus):\n Output only. The time and status of the\n latest reload. This reload may have been\n triggered automatically or manually and may not\n have succeeded.\n metadata (MutableMapping[str, str]):\n Optional. Metadata for the document. The metadata supports\n arbitrary key-value pairs. Suggested use cases include\n storing a document's title, an external URL distinct from\n the document's content_uri, etc. The max size of a ``key``\n or a ``value`` of the metadata is 1024 bytes.\n state (google.cloud.dialogflow_v2beta1.types.Document.State):\n Output only. The current state of the\n document.\n \"\"\"\n\n class KnowledgeType(proto.Enum):\n r\"\"\"The knowledge type of document content.\n\n Values:\n KNOWLEDGE_TYPE_UNSPECIFIED (0):\n The type is unspecified or arbitrary.\n FAQ (1):\n The document content contains question and\n answer pairs as either HTML or CSV. Typical FAQ\n HTML formats are parsed accurately, but unusual\n formats may fail to be parsed.\n\n CSV must have questions in the first column and\n answers in the second, with no header. Because\n of this explicit format, they are always parsed\n accurately.\n EXTRACTIVE_QA (2):\n Documents for which unstructured text is\n extracted and used for question answering.\n ARTICLE_SUGGESTION (3):\n The entire document content as a whole can be\n used for query results. Only for Contact Center\n Solutions on Dialogflow.\n AGENT_FACING_SMART_REPLY (4):\n The document contains agent-facing Smart\n Reply entries.\n SMART_REPLY (4):\n The legacy enum for agent-facing smart reply\n feature.\n \"\"\"\n _pb_options = {\"allow_alias\": True}\n KNOWLEDGE_TYPE_UNSPECIFIED = 0\n FAQ = 1\n EXTRACTIVE_QA = 2\n ARTICLE_SUGGESTION = 3\n AGENT_FACING_SMART_REPLY = 4\n SMART_REPLY = 4\n\n class State(proto.Enum):\n r\"\"\"Possible states of the document\n\n Values:\n STATE_UNSPECIFIED (0):\n The document state is unspecified.\n CREATING (1):\n The document creation is in progress.\n ACTIVE (2):\n The document is active and ready to use.\n UPDATING (3):\n The document updation is in progress.\n RELOADING (4):\n The document is reloading.\n DELETING (5):\n The document deletion is in progress.\n \"\"\"\n STATE_UNSPECIFIED = 0\n CREATING = 1\n ACTIVE = 2\n UPDATING = 3\n RELOADING = 4\n DELETING = 5\n\n class ReloadStatus(proto.Message):\n r\"\"\"The status of a reload attempt.\n\n Attributes:\n time (google.protobuf.timestamp_pb2.Timestamp):\n Output only. The time of a reload attempt.\n This reload may have been triggered\n automatically or manually and may not have\n succeeded.\n status (google.rpc.status_pb2.Status):\n Output only. The status of a reload attempt\n or the initial load.\n \"\"\"\n\n time: timestamp_pb2.Timestamp = proto.Field(\n proto.MESSAGE,\n number=1,\n message=timestamp_pb2.Timestamp,\n )\n status: status_pb2.Status = proto.Field(\n proto.MESSAGE,\n number=2,\n message=status_pb2.Status,\n )\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n display_name: str = proto.Field(\n proto.STRING,\n number=2,\n )\n mime_type: str = proto.Field(\n proto.STRING,\n number=3,\n )\n knowledge_types: MutableSequence[KnowledgeType] = proto.RepeatedField(\n proto.ENUM,\n number=4,\n enum=KnowledgeType,\n )\n content_uri: str = proto.Field(\n proto.STRING,\n number=5,\n oneof=\"source\",\n )\n content: str = proto.Field(\n proto.STRING,\n number=6,\n oneof=\"source\",\n )\n raw_content: bytes = proto.Field(\n proto.BYTES,\n number=9,\n oneof=\"source\",\n )\n enable_auto_reload: bool = proto.Field(\n proto.BOOL,\n number=11,\n )\n latest_reload_status: ReloadStatus = proto.Field(\n proto.MESSAGE,\n number=12,\n message=ReloadStatus,\n )\n metadata: MutableMapping[str, str] = proto.MapField(\n proto.STRING,\n proto.STRING,\n number=7,\n )\n state: State = proto.Field(\n proto.ENUM,\n number=13,\n enum=State,\n )\n\n\nclass GetDocumentRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.GetDocument][google.cloud.dialogflow.v2beta1.Documents.GetDocument].\n\n Attributes:\n name (str):\n Required. The name of the document to retrieve. Format\n ``projects//locations//knowledgeBases//documents/``.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass ListDocumentsRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments].\n\n Attributes:\n parent (str):\n Required. The knowledge base to list all documents for.\n Format:\n ``projects//locations//knowledgeBases/``.\n page_size (int):\n The maximum number of items to return in a\n single page. By default 10 and at most 100.\n page_token (str):\n The next_page_token value returned from a previous list\n request.\n filter (str):\n The filter expression used to filter documents returned by\n the list method. The expression has the following syntax:\n\n [AND ] ...\n\n The following fields and operators are supported:\n\n - knowledge_types with has(:) operator\n - display_name with has(:) operator\n - state with equals(=) operator\n\n Examples:\n\n - \"knowledge_types:FAQ\" matches documents with FAQ\n knowledge type.\n - \"display_name:customer\" matches documents whose display\n name contains \"customer\".\n - \"state=ACTIVE\" matches documents with ACTIVE state.\n - \"knowledge_types:FAQ AND state=ACTIVE\" matches all active\n FAQ documents.\n\n For more information about filtering, see `API\n Filtering `__.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n page_size: int = proto.Field(\n proto.INT32,\n number=2,\n )\n page_token: str = proto.Field(\n proto.STRING,\n number=3,\n )\n filter: str = proto.Field(\n proto.STRING,\n number=4,\n )\n\n\nclass ListDocumentsResponse(proto.Message):\n r\"\"\"Response message for\n [Documents.ListDocuments][google.cloud.dialogflow.v2beta1.Documents.ListDocuments].\n\n Attributes:\n documents (MutableSequence[google.cloud.dialogflow_v2beta1.types.Document]):\n The list of documents.\n next_page_token (str):\n Token to retrieve the next page of results,\n or empty if there are no more results in the\n list.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n documents: MutableSequence[\"Document\"] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=\"Document\",\n )\n next_page_token: str = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass CreateDocumentRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.CreateDocument][google.cloud.dialogflow.v2beta1.Documents.CreateDocument].\n\n Attributes:\n parent (str):\n Required. The knowledge base to create a document for.\n Format:\n ``projects//locations//knowledgeBases/``.\n document (google.cloud.dialogflow_v2beta1.types.Document):\n Required. The document to create.\n import_gcs_custom_metadata (bool):\n Whether to import custom metadata from Google\n Cloud Storage. Only valid when the document\n source is Google Cloud Storage URI.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n document: \"Document\" = proto.Field(\n proto.MESSAGE,\n number=2,\n message=\"Document\",\n )\n import_gcs_custom_metadata: bool = proto.Field(\n proto.BOOL,\n number=3,\n )\n\n\nclass ImportDocumentsRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments].\n\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n parent (str):\n Required. The knowledge base to import documents into.\n Format:\n ``projects//locations//knowledgeBases/``.\n gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSources):\n The Google Cloud Storage location for the documents. The\n path can include a wildcard.\n\n These URIs may have the forms\n ``gs:///``.\n ``gs:////*.``.\n\n This field is a member of `oneof`_ ``source``.\n document_template (google.cloud.dialogflow_v2beta1.types.ImportDocumentTemplate):\n Required. Document template used for\n importing all the documents.\n import_gcs_custom_metadata (bool):\n Whether to import custom metadata from Google\n Cloud Storage. Only valid when the document\n source is Google Cloud Storage URI.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n gcs_source: gcs.GcsSources = proto.Field(\n proto.MESSAGE,\n number=2,\n oneof=\"source\",\n message=gcs.GcsSources,\n )\n document_template: \"ImportDocumentTemplate\" = proto.Field(\n proto.MESSAGE,\n number=3,\n message=\"ImportDocumentTemplate\",\n )\n import_gcs_custom_metadata: bool = proto.Field(\n proto.BOOL,\n number=4,\n )\n\n\nclass ImportDocumentTemplate(proto.Message):\n r\"\"\"The template used for importing documents.\n\n Attributes:\n mime_type (str):\n Required. The MIME type of the document.\n knowledge_types (MutableSequence[google.cloud.dialogflow_v2beta1.types.Document.KnowledgeType]):\n Required. The knowledge type of document\n content.\n metadata (MutableMapping[str, str]):\n Metadata for the document. The metadata supports arbitrary\n key-value pairs. Suggested use cases include storing a\n document's title, an external URL distinct from the\n document's content_uri, etc. The max size of a ``key`` or a\n ``value`` of the metadata is 1024 bytes.\n \"\"\"\n\n mime_type: str = proto.Field(\n proto.STRING,\n number=1,\n )\n knowledge_types: MutableSequence[\"Document.KnowledgeType\"] = proto.RepeatedField(\n proto.ENUM,\n number=2,\n enum=\"Document.KnowledgeType\",\n )\n metadata: MutableMapping[str, str] = proto.MapField(\n proto.STRING,\n proto.STRING,\n number=3,\n )\n\n\nclass ImportDocumentsResponse(proto.Message):\n r\"\"\"Response message for\n [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments].\n\n Attributes:\n warnings (MutableSequence[google.rpc.status_pb2.Status]):\n Includes details about skipped documents or\n any other warnings.\n \"\"\"\n\n warnings: MutableSequence[status_pb2.Status] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=status_pb2.Status,\n )\n\n\nclass DeleteDocumentRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.DeleteDocument][google.cloud.dialogflow.v2beta1.Documents.DeleteDocument].\n\n Attributes:\n name (str):\n Required. The name of the document to delete. Format:\n ``projects//locations//knowledgeBases//documents/``.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass UpdateDocumentRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.UpdateDocument][google.cloud.dialogflow.v2beta1.Documents.UpdateDocument].\n\n Attributes:\n document (google.cloud.dialogflow_v2beta1.types.Document):\n Required. The document to update.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n Optional. Not specified means ``update all``. Currently,\n only ``display_name`` can be updated, an InvalidArgument\n will be returned for attempting to update other fields.\n \"\"\"\n\n document: \"Document\" = proto.Field(\n proto.MESSAGE,\n number=1,\n message=\"Document\",\n )\n update_mask: field_mask_pb2.FieldMask = proto.Field(\n proto.MESSAGE,\n number=2,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass ExportOperationMetadata(proto.Message):\n r\"\"\"Metadata related to the Export Data Operations (e.g.\n ExportDocument).\n\n Attributes:\n exported_gcs_destination (google.cloud.dialogflow_v2beta1.types.GcsDestination):\n Cloud Storage file path of the exported data.\n \"\"\"\n\n exported_gcs_destination: gcs.GcsDestination = proto.Field(\n proto.MESSAGE,\n number=1,\n message=gcs.GcsDestination,\n )\n\n\nclass KnowledgeOperationMetadata(proto.Message):\n r\"\"\"Metadata in google::longrunning::Operation for Knowledge\n operations.\n\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n state (google.cloud.dialogflow_v2beta1.types.KnowledgeOperationMetadata.State):\n Required. Output only. The current state of\n this operation.\n knowledge_base (str):\n The name of the knowledge base interacted\n with during the operation.\n export_operation_metadata (google.cloud.dialogflow_v2beta1.types.ExportOperationMetadata):\n Metadata for the Export Data Operation such\n as the destination of export.\n\n This field is a member of `oneof`_ ``operation_metadata``.\n \"\"\"\n\n class State(proto.Enum):\n r\"\"\"States of the operation.\n\n Values:\n STATE_UNSPECIFIED (0):\n State unspecified.\n PENDING (1):\n The operation has been created.\n RUNNING (2):\n The operation is currently running.\n DONE (3):\n The operation is done, either cancelled or\n completed.\n \"\"\"\n STATE_UNSPECIFIED = 0\n PENDING = 1\n RUNNING = 2\n DONE = 3\n\n state: State = proto.Field(\n proto.ENUM,\n number=1,\n enum=State,\n )\n knowledge_base: str = proto.Field(\n proto.STRING,\n number=3,\n )\n export_operation_metadata: \"ExportOperationMetadata\" = proto.Field(\n proto.MESSAGE,\n number=4,\n oneof=\"operation_metadata\",\n message=\"ExportOperationMetadata\",\n )\n\n\nclass ReloadDocumentRequest(proto.Message):\n r\"\"\"Request message for\n [Documents.ReloadDocument][google.cloud.dialogflow.v2beta1.Documents.ReloadDocument].\n\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n name (str):\n Required. The name of the document to reload. Format:\n ``projects//locations//knowledgeBases//documents/``\n gcs_source (google.cloud.dialogflow_v2beta1.types.GcsSource):\n The path for a Cloud Storage source file for\n reloading document content. If not provided, the\n Document's existing source will be reloaded.\n\n This field is a member of `oneof`_ ``source``.\n import_gcs_custom_metadata (bool):\n Whether to import custom metadata from Google\n Cloud Storage. Only valid when the document\n source is Google Cloud Storage URI.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n gcs_source: gcs.GcsSource = proto.Field(\n proto.MESSAGE,\n number=3,\n oneof=\"source\",\n message=gcs.GcsSource,\n )\n import_gcs_custom_metadata: bool = proto.Field(\n proto.BOOL,\n number=4,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/dialogflow_v2beta1/types/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":22425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"189867463","text":"from zope.interface import Interface, Attribute\nfrom zope import schema\nfrom zope.interface import implements\nfrom z3c.form.object import registerFactoryAdapter\nfrom collective.listingviews import LVMessageFactory as _\nfrom validation import validate_id, validate_class, validate_tal\ntry:\n from plone.autoform import directives as form\nexcept:\n from plone.directives import form\nfrom z3c.formwidget.query.interfaces import IQuerySource\nfrom zope.schema.interfaces import IContextSourceBinder, IVocabularyFactory\nfrom utils import ComplexRecordsProxy\nfrom zope.schema.vocabulary import SimpleVocabulary, SimpleTerm\nfrom zope.component import queryUtility, getUtility\nfrom plone.registry.interfaces import IRegistry\nfrom Products.CMFCore.utils import getToolByName\ntry:\n from zope.app.component.hooks import getSite\nexcept ImportError:\n from zope.component.hooks import getSite\n\n\nclass ICustomFieldDefinition(Interface):\n id = schema.ASCIILine(title=(u\"Id\"),\n required=True,\n description=_(u\"It must contains only alphanumeric or underscore, starting with alpha. Will be used as css class\"),\n constraint=validate_id)\n\n name = schema.ASCIILine(title=_(u\"Title\"),\n description=_(u\"Name as it will appear in html of view\"),\n required=False)\n\n tal_statement = schema.ASCIILine(title=_(u\"TAL expression\"),\n required=True,\n description=_(u'variables available include \"item\":catalog brain, \"object\": context object, \"folder\": parent of object if object is not a folder. e.g. \"python:item.getObject().getBody()\"'),\n constraint=validate_tal)\n\n css_class = schema.ASCIILine(title=_(u\"Additional CSS classes\"),\n required=False,\n constraint=validate_class)\n\n\nclass CustomFieldDefinition(object):\n implements(ICustomFieldDefinition)\n\nregisterFactoryAdapter(ICustomFieldDefinition, CustomFieldDefinition)\n\n\n\ndef ListingViewVocabulary(context):\n terms = []\n reg = queryUtility(IRegistry)\n if reg is not None:\n proxy = ComplexRecordsProxy(reg, IListingControlPanel, prefix='collective.listingviews',\n key_names={'views': 'id'})\n for view in proxy.views:\n terms.append(SimpleVocabulary.createTerm(view.id, view.id, view.name))\n return SimpleVocabulary(terms)\n\n\ndef MetadataVocabulary(context):\n \"\"\"\n Metadata name is stored in registry. Format for default name is \"fieldname:\"\n and format for custom name is \":customname\"\n \"\"\"\n terms = []\n portal = getSite()\n metadataDisplay = getToolByName(portal, 'portal_atct').getMetadataDisplay()\n for name, display_name in metadataDisplay.items():\n if name in ['end', 'EffectiveDate', 'start', 'ExpirationDate', 'ModificationDate', 'CreationDate']:\n for format,format_name in [('localshort', 'Date'),('locallong','Date & Time')]:\n terms.append(SimpleVocabulary.createTerm(\"%s:%s\"% (name, format), None,\n \"%s (%s)\"%(display_name, format_name)))\n elif name in ['Title', 'getId']:\n terms.append(SimpleVocabulary.createTerm(name + \":\", None, display_name))\n for format,format_name in [('tolink', 'Link')]:\n terms.append(SimpleVocabulary.createTerm(\"%s:%s\"% (name, format), None,\n \"%s (%s)\"%(display_name, format_name)))\n else:\n terms.append(SimpleVocabulary.createTerm(name + \":\", None, display_name))\n\n # custom field\n reg = queryUtility(IRegistry)\n if reg is not None:\n proxy = ComplexRecordsProxy(reg, IListingCustomFieldControlPanel,\n prefix='collective.listingviews.customfield',\n key_names={'fields': 'id'})\n for field in proxy.fields:\n terms.append(SimpleVocabulary.createTerm(':' + field.id, None,\n \"%s (Custom)\" % field.name))\n return SimpleVocabulary(terms)\n\nclass VocabularySource(object):\n implements(IQuerySource)\n def __init__(self, vocabulary):\n self.vocabulary = vocabulary\n def __contains__(self, item):\n return self.vocabulary.__contains__(item)\n def __iter__(self):\n return self.vocabulary.__iter__()\n def getTerm(self):\n return self.vocabulary.getTerm()\n\n def getTermByToken(self):\n return self.vocabulary.getTermByToken()\n\n def search(self, query_string):\n return [v\n for v in self\n if query_string.lower() in v.value.lower()]\n\nclass MetadataSourceBinder(object):\n implements(IContextSourceBinder)\n\n def __call__(self, context):\n return VocabularySource(MetadataVocabulary(context))\n\ndef all_types():\n\n portal = getSite()\n vocab = getUtility(IVocabularyFactory, name=\"plone.app.vocabularies.ReallyUserFriendlyTypes\")\n return [term.value for term in vocab(portal)]\n\n\nclass IListingDefinition(Interface):\n id = schema.ASCIILine(title=_(u\"Id\"),\n required=True,\n description=_(\n u\"Unique id of your listing (will appear as css class). It must contains only alphanumeric or underscore, starting with alpha\"),\n constraint=validate_id)\n\n name = schema.ASCIILine(title=_(u\"Title\"),\n required=False,\n description=_(u\"Name as it will appear in the display menu to editors\"))\n\n # http://plone.org/products/dexterity/documentation/manual/developer-manual/advanced/vocabularies/\n# form.widget(item_fields=ChosenMultiFieldWidget)\n item_fields = schema.List(title=_(u\"Item Fields\"),\n description=_(\n u\"Display the following fields at of current content item. Sort to change order.\"),\n required=False,\n default=[],\n value_type=schema.Choice(\n vocabulary=\"collective.listingviews.MetadataVocabulary\",\n #source=MetadataSourceBinder(),\n )\n )\n\n# form.widget(listing_fields=ChosenMultiFieldWidget)\n listing_fields = schema.List(title=_(u\"Listing Fields\"),\n description=_(\n u\"Folders/Collections and other listable items will list contents displaying these fields for each\"),\n required=False,\n default=[],\n value_type=schema.Choice(\n vocabulary=\"collective.listingviews.MetadataVocabulary\",\n #source=MetadataSourceBinder(),\n )\n )\n\n # form.widget(restricted_to_types=AutocompleteMultiSelectionFieldWidget)\n restricted_to_types = schema.List(title=_(u\"Enabled on Types\"),\n description=_(u\"Show in display menu or make portlet visible only for these types\"),\n required=True,\n# defaultFactory=all_types,\n value_type=schema.Choice(\n vocabulary=\"plone.app.vocabularies.ReallyUserFriendlyTypes\"\n ),\n )\n\n batch_size = schema.Int(\n title=_(u\"label_batch_size\", default=u\"Batch Size\"),\n description=_(u\"description_batch_size\",\n default=u\"The amount of items shown in one page. \"\n u\"Enter zero if you want to disable view batching.\"\n ),\n default=10,\n required=True)\n\n portlet_more_text = schema.ASCIILine(title=_(u\"Portlet Read More Text\"), required=False)\n\n css_class = schema.ASCIILine(title=_(u\"Additional CSS classes\"),\n required=False,\n constraint=validate_class)\n\n\n\n#class IListingSettings(Interface):\n# listing_choice = schema.Choice(\n# title=_(u\"label_listing_choice\", default=u\"Listing views\"),\n# description=_(u\"description_listing_choice\",\n# default=u\"Select the custom listing views.\"),\n# vocabulary=\"collective.listingviews.ListingViewVocabulary\",\n# default=\"view1\")\n\n\nclass IListingControlSettings(Interface):\n pass\n\n\nclass IListingControlPanel(Interface):\n views = schema.List(\n title=_(u'Custom listing views'),\n description=(\n u\"Create and manage your custom listing views which can be used in collections, folders, portlets and tiles\"),\n value_type=schema.Object(IListingDefinition,\n title=_(u\"Listing View\")),\n required=False,\n default=[],\n missing_value=[],\n )\n\n\nclass IListingCustomFieldControlPanel(Interface):\n fields = schema.Tuple(\n title=_(u'Names of custom listing fields'),\n description=_(\n u\"Create new fields to insert into your Listing Views based on existing fields of data from your content\"),\n value_type=schema.Object(ICustomFieldDefinition,\n title=_(u\"Custom Field Definition\")),\n required=False,\n default=(),\n missing_value=(),\n )\n\n\n#class IBaseSettings(Interface):\n# pass\n\n\n#class IBasicListingSettings(IBaseSettings):\n# pass\n\n\nclass IListingAdapter(Interface):\n def retrieve_context_item(self):\n \"\"\"\n This method retrieves all the item fields\n \"\"\"\n\n def retrieve_listing_items(self):\n \"\"\"\n This method retrieves all the listing fields\n \"\"\"\n\n def number_of_items(self):\n \"\"\"\n Total items of the current list\n \"\"\"\n\n def listing_style_class(self):\n \"\"\"\n Listing view css class\n \"\"\"\n\n def listing_view_batch_size(self):\n \"\"\"\n Batch size\n \"\"\"\n\n def set_listing_view(self, view_name):\n \"\"\"\n Set id of the view to one of the available views stored in the registry.\n \"\"\"\n\n def is_container(self):\n \"\"\"\n Return true if current object is a container, such as folder, or collection\n \"\"\"\n","sub_path":"src/collective/listingviews/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":10642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"36315500","text":"import os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\" \n\n\nimport json\nimport random\nimport re\nimport numpy as np\nfrom os import path\nimport pdb\nimport pickle as pkl\nimport sys\nfrom tqdm import tqdm\nimport numpy as np\nimport yaml\nfrom datetime import datetime\nimport coloredlogs\nimport logging\nfrom sklearn.metrics import f1_score, precision_score, recall_score\n\nfrom sesame.evaluation import *\nfrom sesame.dataio import *\nfrom sesame.globalconfig import VERSION, TRAIN_FTE, UNK, DEV_CONLL, TEST_CONLL, FRAME_DIR, EMPTY_FE\nfrom sesame.conll09 import lock_dicts, post_train_lock_dicts\nfrom sesame.housekeeping import filter_long_ex, merge_span_ex\nfrom sesame.evaluation import calc_f, evaluate_example_argid, evaluate_corpus_argid\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom transformers import T5Config, T5ForConditionalGeneration, T5Tokenizer\nfrom transformers import AdamW, Adafactor\nfrom transformers import get_constant_schedule_with_warmup, get_linear_schedule_with_warmup\n\n\n# from .conll09 import lock_dicts, post_train_lock_dicts, VOCDICT, POSDICT, LEMDICT, LUDICT, LUPOSDICT\n# from .dataio import create_target_lu_map, get_wvec_map, read_conll\n# from .evaluation import calc_f, evaluate_example_targetid\n# from .frame_semantic_graph import LexicalUnit\n# from .housekeeping import unk_replace_tokens\n# from .raw_data import make_data_instance\n# from .semafor_evaluation import convert_conll_to_frame_elements\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--hier\", type=bool, default=False, help=\"Use phrase structure features.\")\nargs = parser.parse_args(\"\")\n\n\ntrain_conll = TRAIN_FTE\ndev_conll = DEV_CONLL\ntest_conll = TEST_CONLL\n\ntrain_examples, _, _ = read_conll(train_conll)\npost_train_lock_dicts()\nfrmfemap, corefrmfemap, _ = read_frame_maps()\nif args.hier:\n frmrelmap, feparents = read_frame_relations()\nlock_dicts()\n\nNOTANFEID = FEDICT.getid(EMPTY_FE) # O in CoNLL format.\nUSE_SPAN_CLIP = True\nALLOWED_SPANLEN = 20\nmerge_span_ex(train_examples, NOTANFEID)\ntrain_examples = filter_long_ex(train_examples, USE_SPAN_CLIP, ALLOWED_SPANLEN, NOTANFEID)\n\ndev_examples, _, _ = read_conll(dev_conll)\nmerge_span_ex(dev_examples, NOTANFEID)\ndev_examples = filter_long_ex(dev_examples, USE_SPAN_CLIP, ALLOWED_SPANLEN, NOTANFEID)\n\ntest_examples, _, _ = read_conll(test_conll)\nmerge_span_ex(test_examples, NOTANFEID)\ntest_examples = filter_long_ex(test_examples, USE_SPAN_CLIP, ALLOWED_SPANLEN, NOTANFEID)\n\nprint (\"Total number of distinct frames\", FRAMEDICT.size())\nprint (\"Total number of dictinct frame elements\", FEDICT.size())\n\n\nMODEL_NAME = 't5-base'\ntokenizer = T5Tokenizer.from_pretrained(MODEL_NAME)\n\n\nclass DataInstance:\n def __init__(self, guid, task, ex, frame_label,\n input_ids, input_mask,\n target_ids, target_mask):\n self.guid = guid\n self.task = task\n self.ex = ex\n self.frame_label = frame_label\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.target_ids = target_ids\n self.target_mask = target_mask\n\n\nclass CustomDataset(Dataset):\n def __init__(self, examples, task):\n self.instances = self.process_instances(examples, task)\n \n def sent_format(self, words, targetpos):\n sent = \"\"\n for index, word in enumerate(words):\n sent += \" \" + str(index)\n if index != targetpos: sent += \" \" + word\n else: sent += \" * \" + word + \" *\"\n return sent\n \n def frame_format(self, frame, words, targetpos):\n frame_str = \" \".join(frame.get_str(FRAMEDICT).split('_'))\n sent = \"FRAME:\" + self.sent_format(words, targetpos)\n return sent, frame_str\n \n def arg_format(self, frame, framedict, words, targetpos):\n frame_str = \" \".join(frame.get_str(FRAMEDICT).split('_'))\n sent = \"ARGS for \" + frame_str + \":\" + self.sent_format(words, targetpos)\n arg_str = \"\"\n for fe, spans in framedict.items():\n if fe == NOTANFEID: continue\n fe_str = \" \".join(FEDICT.getstr(fe).split('_'))\n span = spans[0]\n arg_str += \" \" + fe_str + \" = \" + str(span[0]) + \"-\" + str(span[1]) + \" |\"\n return sent, arg_str\n \n def process_instances(self, examples, task):\n instances = []\n guid = 0\n max_seq_length = 128\n \n # pdb.set_trace()\n \n for index, ex in enumerate(tqdm(examples)):\n words = [VOCDICT.getstr(tok) for tok in ex.tokens]\n frame = ex.frame\n tfdict = ex.targetframedict\n \n targetpos = [i for i in range(len(words)) if ex._elements[i].is_pred][0]\n \n if task == 0:\n frame_inputstr, frame_outputstr = self.frame_format(ex.frame, words, targetpos)\n frame_inputenc = tokenizer.encode_plus(frame_inputstr, max_length=max_seq_length, padding='max_length', truncation=True, return_tensors='np')\n frame_outputenc = tokenizer.encode_plus(frame_outputstr, max_length=10, padding='max_length', truncation=True, return_tensors='np')\n instances.append(\n DataInstance(index, task, ex, ex.frame.id,\n frame_inputenc['input_ids'][0], frame_inputenc['attention_mask'][0],\n frame_outputenc['input_ids'][0], frame_outputenc['attention_mask'][0])\n )\n else:\n arg_inputstr, arg_outputstr = self.arg_format(ex.frame, ex._get_inverted_femap(), words, targetpos)\n arg_inputenc = tokenizer.encode_plus(arg_inputstr, max_length=max_seq_length, padding='max_length', truncation=True, return_tensors='np')\n arg_outputenc = tokenizer.encode_plus(arg_outputstr, max_length=max_seq_length, padding='max_length', truncation=True, return_tensors='np')\n instances.append(\n DataInstance(index, task, ex, None,\n arg_inputenc['input_ids'][0], arg_inputenc['attention_mask'][0],\n arg_outputenc['input_ids'][0], arg_outputenc['attention_mask'][0])\n )\n \n return instances\n\n def __len__(self):\n return len(self.instances)\n \n def __getitem__(self, index):\n return (self.instances[index].input_ids, self.instances[index].input_mask,\n self.instances[index].target_ids, self.instances[index].target_mask)\n\n\ntorch.manual_seed(42)\nrandom.seed(42)\n\nwith open('config_frame.yaml', 'r') as f:\n config = yaml.safe_load(f)\nprint ()\nprint (config)\nprint ()\n\n\ntrain_frame_dataset = CustomDataset(train_examples, 0)\ndev_frame_dataset = CustomDataset(dev_examples, 0)\ntest_frame_dataset = CustomDataset(test_examples, 0)\n\n# train_arg_dataset = CustomDataset(train_examples, 1)\n# dev_arg_dataset = CustomDataset(dev_examples, 1)\n# test_arg_dataset = CustomDataset(test_examples, 1)\n\ntrain_frame_dataloader = torch.utils.data.DataLoader(train_frame_dataset, batch_size=config['batch_size'], shuffle=True)\ndev_frame_dataloader = torch.utils.data.DataLoader(dev_frame_dataset, batch_size=config['eval_batch_size'], shuffle=False)\ntest_frame_dataloader = torch.utils.data.DataLoader(test_frame_dataset, batch_size=config['eval_batch_size'], shuffle=False)\n\n# train_arg_dataloader = torch.utils.data.DataLoader(train_arg_dataset, batch_size=config['batch_size'], shuffle=True)\n# dev_arg_dataloader = torch.utils.data.DataLoader(dev_arg_dataset, batch_size=config['eval_batch_size'], shuffle=False)\n# test_arg_dataloader = torch.utils.data.DataLoader(test_arg_dataset, batch_size=config['eval_batch_size'], shuffle=False)\n\n# # Model\n\nimport collections\n\ndef make_invertedfedict(arg_txt):\n fedict = {}\n \n args = arg_txt.split(\"|\")\n for arg in args:\n if arg == '': continue\n fename, span = arg.split(\"=\")\n fename, span = fename.strip(), span.strip()\n fename = \"_\".join(fename.split(\" \"))\n feid = FEDICT.getid(fename)\n span = span.split(\"-\")\n spanlist = [(int(span[0]), int(span[1]))]\n fedict[feid] = spanlist\n \n return fedict\n\n\ndef make_frameid(frame_txt):\n framename = '_'.join(frame_txt.split(\" \"))\n return FRAMEDICT.getid(framename)\n\n\nlogger = logging.getLogger('Log')\ncoloredlogs.install(logger=logger, level='DEBUG', fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n\nclass Roundrobinloader:\n def __init__(self, dl1, dl2):\n assert(len(dl1) == len(dl2))\n self.len = 2 * len(dl1)\n self.frame_data = [t for t in dl1]\n self.arg_data = [t for t in dl2]\n self.index = -1\n \n def __iter__(self):\n return self\n\n def __len__(self):\n return self.len\n\n def __next__(self):\n self.index += 1\n if self.index >= self.len:\n raise StopIteration\n if self.index % 2 == 0:\n return self.frame_data[self.index//2]\n else:\n return self.arg_data[self.index//2]\n\n \nclass Argloader:\n def __init__(self, dl1, shuffle=True):\n self.len = len(dl1)\n self.arg_data = [t for t in dl1]\n self.shuffle = shuffle\n if shuffle:\n random.shuffle(self.arg_data)\n self.index = -1\n \n def __iter__(self):\n return self\n\n def __len__(self):\n return self.len\n\n def __next__(self):\n self.index += 1\n if self.index >= self.len:\n if self.shuffle: \n random.shuffle(self.arg_data)\n raise StopIteration\n return self.arg_data[self.index]\n\n\nclass SeqSupervisedNetwork(nn.Module):\n def __init__(self, config):\n super(SeqSupervisedNetwork, self).__init__()\n self.base_path = config['base_path']\n self.early_stopping = config['early_stopping']\n self.lr = config.get('lr', 1e-4)\n self.weight_decay = config.get('weight_decay', 0.0)\n self.gradient_accumulation_steps = config.get('gradient_accumulation_steps', 1)\n\n self.learner = T5ForConditionalGeneration.from_pretrained(MODEL_NAME)\n # self.learner = torch.nn.DataParallel(self.learner)\n \n if config.get('trained_learner', False):\n self.learner.load_state_dict(torch.load(\n os.path.join(self.base_path, 'saved_models', config['trained_learner'])\n ))\n logger.info('Loaded trained learner model {}'.format(config['trained_learner']))\n \n self.device = torch.device(config.get('device', 'cpu'))\n self.to(self.device)\n logger.info('Model loaded to {}'.format(self.device))\n \n self.initialize_optimizer_scheduler()\n \n \n def initialize_optimizer_scheduler(self):\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.learner.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": self.weight_decay,\n },\n {\"params\": [p for n, p in self.learner.named_parameters() if any(nd in n for nd in no_decay)], \"weight_decay\": 0.0}\n ]\n \n # self.optimizer = AdamW(optimizer_grouped_parameters, lr=self.lr, weight_decay=self.weight_decay)\n # self.lr_scheduler = get_constant_schedule_with_warmup(self.optimizer, num_warmup_steps=100)\n \n self.optimizer = Adafactor(optimizer_grouped_parameters, relative_step=True, warmup_init=True, lr=None)\n\n \n def vectorize(self, batch):\n with torch.no_grad():\n if len(batch) == 3:\n return torch.LongTensor(batch[0]), torch.LongTensor(batch[1]), torch.LongTensor(batch[2])\n else:\n return torch.LongTensor(batch[0]), torch.LongTensor(batch[1]), torch.LongTensor(batch[2]), torch.LongTensor(batch[3])\n \n \n def arg_forward(self, input_ids, input_mask, target_ids=None, target_mask=None):\n if target_ids is None:\n inputs = {\"input_ids\": input_ids, \"attention_mask\": input_mask, \n \"max_length\": 10, \"num_beams\": 3, \"num_return_sequences\": 1}\n outputs = self.learner.generate(**inputs)\n # pdb.set_trace()\n return outputs\n else:\n inputs = {\"input_ids\": input_ids, \"attention_mask\": input_mask,\n \"labels\": target_ids, \"decoder_attention_mask\": target_mask}\n outputs = self.learner(**inputs)\n loss = outputs[0]\n return loss\n \n def forward_eval(self, arg_dataloader, mode):\n if mode == 1:\n examples = dev_examples\n elif mode == 2:\n examples = test_examples\n elif mode == 3:\n examples = train_examples\n \n self.eval()\n \n labels, preds = [], []\n true_labels, pred_labels = [], []\n with torch.no_grad():\n for batch in tqdm(arg_dataloader, desc=\"Frame evaluation\"):\n batch = self.vectorize(batch)\n batch = tuple(t.to(config['device']) for t in batch)\n output = self.arg_forward(batch[0], batch[1])\n pred_txt = tokenizer.batch_decode(output)\n label_txt = tokenizer.batch_decode(batch[2])\n preds.extend(pred_txt)\n labels.extend(label_txt)\n \n for index in range(len(arg_dataloader)):\n try:\n pred = make_frameid(preds[index])\n true = make_frameid(labels[index])\n pred_labels.append(pred)\n true_labels.append(true)\n except:\n # pdb.set_trace()\n # logger.error(preds[index])\n continue\n \n return precision_score(true_labels, pred_labels, average='micro'), \\\n recall_score(true_labels, pred_labels, average='micro'), \\\n f1_score(true_labels, pred_labels, average='micro')\n \n \n def forward(self, arg_dataloader, mode):\n if mode != 0:\n return self.forward_eval(arg_dataloader, mode)\n \n self.train()\n \n dataloader = Argloader(arg_dataloader)\n \n log_every = 100\n avg_arg_loss = 0\n loss_log = 0\n \n loader_t = tqdm(iter(dataloader))\n for batch_id, batch in enumerate(loader_t):\n batch = self.vectorize(batch)\n batch = tuple(t.to(config['device']) for t in batch)\n \n loss = self.arg_forward(batch[0], batch[1], batch[2])\n loss = loss.mean()\n \n if self.gradient_accumulation_steps > 1:\n loss = loss / self.gradient_accumulation_steps\n\n loss.backward()\n \n avg_arg_loss += loss.item() * self.gradient_accumulation_steps\n\n if (batch_id + 1) % self.gradient_accumulation_steps == 0:\n # torch.nn.utils.clip_grad_norm_(self.learner.parameters(), 1.0)\n self.optimizer.step()\n self.optimizer.zero_grad()\n # self.lr_scheduler.step()\n \n if (batch_id + 1) % log_every == 0:\n avg_arg_loss /= log_every\n loss_log = avg_arg_loss\n loader_t.set_description('Batch {}/{}, avg_argloss = {:.5f}'.format(batch_id + 1, len(dataloader), avg_arg_loss))\n loader_t.refresh()\n avg_arg_loss = 0\n\n return loss_log\n\n# In[33]:\n\n\nclass SupervisedNetwork:\n def __init__(self, config):\n now = datetime.now()\n date_time = now.strftime(\"%m-%d-%H-%M-%S\")\n self.tensorboard_writer = SummaryWriter(log_dir='runs/{}-'.format(MODEL_NAME) + date_time)\n \n self.base_path = config['base_path']\n self.stamp = config['stamp']\n self.meta_epochs = config['num_epochs']\n self.early_stopping = config['early_stopping']\n self.stopping_threshold = config.get('stopping_threshold', 1e-3)\n\n self.model = SeqSupervisedNetwork(config)\n\n logger.info('Supervised network instantiated')\n\n def training(self, train_arg_dataloader, val_arg_dataloader):\n best_loss = float('inf')\n best_f1 = 0\n patience = 0\n model_path = os.path.join(self.base_path, 'saved_models', '{}-t5model.h5'.format(self.stamp))\n logger.info('Model name: {}-t5model.h5'.format(self.stamp))\n for epoch in range(self.meta_epochs):\n logger.info('Starting epoch {}/{}'.format(epoch + 1, self.meta_epochs))\n \n avg_loss = self.model(train_arg_dataloader, mode=0)\n\n logger.info('Train epoch {}: Avg loss = {:.5f}'.format(epoch + 1, avg_loss))\n self.tensorboard_writer.add_scalar('Loss/train', avg_loss, global_step=epoch + 1)\n \n avg_precision, avg_recall, avg_f1 = self.model(val_arg_dataloader, mode=1)\n\n logger.info('Val epoch {}: avg precision = {:.5f}, '\n 'avg recall = {:.5f}, avg F1 score = {:.5f}'.format(epoch + 1, avg_precision, avg_recall, avg_f1))\n \n if avg_f1 > best_f1 + self.stopping_threshold:\n patience = 0\n best_loss = avg_loss\n best_f1 = avg_f1\n logger.info('Saving the model since the F1 improved')\n torch.save(self.model.learner.state_dict(), model_path)\n logger.info('')\n else:\n patience += 1\n logger.info('F1 did not improve')\n logger.info('')\n if patience == self.early_stopping:\n break\n\n # Log params and grads into tensorboard\n# for name, param in self.model.named_parameters():\n# if param.requires_grad and param.grad is not None:\n# self.tensorboard_writer.add_histogram('Params/' + name, param.data.view(-1),\n# global_step=epoch + 1)\n# self.tensorboard_writer.add_histogram('Grads/' + name, param.grad.data.view(-1),\n# global_step=epoch + 1)\n\n self.model.learner.load_state_dict(torch.load(model_path))\n return best_f1\n\n def testing(self, test_arg_dataloader):\n logger.info('---------- Supervised testing starts here ----------')\n precision, recall, f1_score = self.model(test_arg_dataloader, mode=2)\n\n logger.info('Avg meta-testing metrics: precision = {:.5f}, recall = {:.5f}, '\n 'F1 score = {:.5f}'.format(precision,\n recall,\n f1_score))\n return f1_score\n \n def testing_train(self, arg_dataloader):\n logger.info('---------- Evaluating training data starts here ----------')\n precision, recall, f1_score = self.model(arg_dataloader, mode=3)\n\n logger.info('Avg meta-testing metrics: precision = {:.5f}, recall = {:.5f}, '\n 'F1 score = {:.5f}'.format(precision,\n recall,\n f1_score))\n return f1_score\n\n\n# In[34]:\n\n\nlearner = SupervisedNetwork(config)\n\n\n# In[35]:\n\n\nif config['train']:\n learner.training(train_frame_dataloader, dev_frame_dataloader)\n logger.info('Supervised learning completed')\n\n\n# In[ ]:\n\n\nlearner.testing(test_frame_dataloader)\nlogger.info('Supervised testing completed')\n\n\ntrain_frame_dataloader = torch.utils.data.DataLoader(train_frame_dataset, batch_size=config['batch_size'], shuffle=False)\nlearner.testing_train(train_frame_dataloader)\nlogger.info('Is there overfit?')","sub_path":"SRL/train_frame.py","file_name":"train_frame.py","file_ext":"py","file_size_in_byte":19952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"67648397","text":"import sublime\nimport sublime_plugin\n\nfrom .PrettyJson import PrettyJsonBaseCommand\n\ns = sublime.load_settings(\"Pretty JSON.sublime-settings\")\n\nclass PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand):\n def on_post_save(self, view):\n validate = s.get('validate_on_save', True)\n as_json = s.get('as_json', ['JSON'])\n if validate and any(\n syntax in view.settings().get(\"syntax\") for syntax in as_json\n ):\n self.view = view\n PrettyJsonBaseCommand.clear_phantoms(self)\n json_content = self.view.substr(sublime.Region(0, self.view.size()))\n try:\n self.json_loads(json_content)\n except Exception as ex:\n self.show_exception(msg=ex)\n\n\nclass PrettyJsonAutoPrettyOnSaveListener(sublime_plugin.EventListener):\n def on_pre_save(self, view):\n auto_pretty = s.get('pretty_on_save', False)\n as_json = s.get('as_json', ['JSON'])\n if auto_pretty and any(\n syntax in view.settings().get('syntax') for syntax in as_json\n ):\n sublime.active_window().run_command('pretty_json')\n","sub_path":"PrettyJsonListeners.py","file_name":"PrettyJsonListeners.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"629158908","text":"# Copyright (C) 2023 The Qt Company Ltd.\n# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause\n\nfrom PySide6.QtCore import Qt\nfrom PySide6.QtGui import QImage, QVector3D\nfrom PySide6.QtDataVisualization import (QSurface3DSeries, QSurfaceDataItem)\n\n\n# Value used to encode height data as RGB value on PNG file\nPACKING_FACTOR = 11983.0\n\n\nclass TopographicSeries(QSurface3DSeries):\n\n def __init__(self):\n super().__init__()\n self._sampleCountX = 0.0\n self._sampleCountZ = 0.0\n self.setDrawMode(QSurface3DSeries.DrawSurface)\n self.setFlatShadingEnabled(True)\n self.setBaseColor(Qt.white)\n\n def sampleCountX(self):\n return self._sampleCountX\n\n def sampleCountZ(self):\n return self._sampleCountZ\n\n def setTopographyFile(self, file, width, height):\n heightMapImage = QImage(file)\n bits = heightMapImage.bits()\n imageHeight = heightMapImage.height()\n imageWidth = heightMapImage.width()\n widthBits = imageWidth * 4\n stepX = width / float(imageWidth)\n stepZ = height / float(imageHeight)\n\n dataArray = []\n for i in range(0, imageHeight):\n p = i * widthBits\n z = height - float(i) * stepZ\n newRow = []\n for j in range(0, imageWidth):\n aa = bits[p + 0]\n rr = bits[p + 1]\n gg = bits[p + 2]\n color = (gg << 16) + (rr << 8) + aa\n y = float(color) / PACKING_FACTOR\n item = QSurfaceDataItem(QVector3D(float(j) * stepX, y, z))\n newRow.append(item)\n p += 4\n dataArray.append(newRow)\n\n self.dataProxy().resetArray(dataArray)\n\n self._sampleCountX = float(imageWidth)\n self._sampleCountZ = float(imageHeight)\n","sub_path":"examples/datavisualization/graphgallery/topographicseries.py","file_name":"topographicseries.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569614389","text":"import json\nfrom varys.models import Employee\n\n_BLAKE = Employee.objects.get(name='Blake Irving')\n\ndef create_json_tree(employee):\n\tname = employee.name\n\tmanager_name = employee.manager_name\n\toffice_name = employee.office_name\n\tselected = employee.selected\n\tuser_name = employee.user_name\n\ttitle = employee.title\n\n\tif name == 'Blake Irving':\n\t\tchildren = Employee.objects.filter(manager_name=name).exclude(name='Blake Irving')\n\t\tchildren = Employee.objects.filter(manager_name='Blake Irving').exclude(name='Blake Irving')\n\telse:\n\t\tchildren = Employee.objects.filter(manager_name=name)\n\n\temployee_children = []\n\tif children:\n\t\temployee_children = []\n\t\tfor child in children:\n\t\t\tnew_child = create_json_tree(child)\n\t\t\temployee_children.append(new_child)\n\n\treturn create_json_node(name, manager_name, office_name,\n\t\t\t\t\t \t\tselected, user_name, title, employee_children)\n\ndef create_json_node(name, manager_name, office_name, selected,\n\t\t\t\t\t user_name, title, children):\n\treturn {\n\t\t'name': name,\n\t\t'parent': manager_name,\n\t\t'location': office_name,\n\t\t'user_name': user_name,\n\t\t'title': title,\n\t\t'selected': selected,\n\t\t'_children': children\n\t}\n\ndef write_tree():\n\toutput_file = open('varys/json_tree.json', 'wb')\n\tjson_trees = create_json_tree(_BLAKE)\n\toutput_file.write(json.dumps(json_trees))\n\toutput_file.close()\n","sub_path":"varys/data/json_tree.py","file_name":"json_tree.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"279994079","text":"import random\n\n#A container for the connections and coordinates of each part of the maze.\nclass MazePiece:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n self.shortest_path = float(\"infinity\")\n #Empty lists will denote a wall, and non-empty lists will denote \n #a corridor. \n self.connections = []\n \n def __str__(self):\n return str(len(self.connections))\n\n#print the number of connections for each MazePiece\ndef print_maze_connections(m):\n for i in range(len(m[0])):\n for x in m:\n if len(x[i].connections):\n print(x[i], end = \" \")\n else:\n print(\"W\", end = \" \")\n print()\n print()\n\n#return a list of coordinates along which the shortest path through maze m lies.\ndef shortest_path(m, start, target):\n #BFS\n visited = [start]\n fronteir = start.connections[:]\n for i in fronteir:\n i.shortest_path = 1\n \n start.shortest_path = 0\n curr = start\n \n #tell all the pieces what their shortest path is\n while curr != target and fronteir != []:\n visited.append(curr)\n curr = fronteir.pop(0)\n for i in curr.connections:\n if (curr.shortest_path+1 < i.shortest_path):\n i.shortest_path = curr.shortest_path+1\n if (i not in visited and i not in fronteir):\n fronteir.append(i)\n \n #follow and record the path from the target back to the start\n path = [(target.x,target.y)]\n curr = target\n while curr != start:\n for i in curr.connections:\n if (i.shortest_path == curr.shortest_path-1):\n curr = i\n path.append((curr.x,curr.y))\n return path\n \n \n\n#print the properly formatted maze, optionally with the shortest path through it\ndef print_maze(m, draw_shortest_path = False):\n start = m[0][h//4]\n \n #fill display grid with walls to start\n display = []\n for x in range(len(m)*2+1):\n row = []\n for y in range(len(m[0])*2+1):\n row.append(\"W\")\n display.append(row)\n \n connections = wall_table(len(m),len(m[0]))\n \n l = [start] \n seen = [start]\n while l:\n #draw paths at corners\n current = l.pop(0)\n seen.append(current)\n display[current.x*2+1][current.y*2+1] = \" \"\n #draw path between corners\n for i in current.connections:\n if i not in seen:\n display[current.x*2 + i.x-current.x + 1][current.y*2 + i.y-current.y + 1] = \" \"\n l.append(i)\n\n #entrance & exit\n if draw_shortest_path:\n if len(m[0])%2 != 0:\n display[0][len(m[0])] = \">\"\n display[-1][len(m[0])] = \">\" \n else:\n display[0][len(m[0]) + 1] = \">\"\n display[-1][len(m[0])+ 1] = \">\"\n else:\n if len(m[0])%2 != 0:\n display[0][len(m[0])] = \" \"\n display[-1][len(m[0])] = \" \" \n else:\n display[0][len(m[0]) + 1] = \" \"\n display[-1][len(m[0])+ 1] = \" \"\n \n #draw the shortest path\n if draw_shortest_path:\n path = shortest_path(m, m[0][len(m[0])//2], m[-1][len(m[0])//2])\n for i in range(len(path)):\n display[2*path[i][0]+1][2*path[i][1]+1] = \">\"\n if i > 0:\n display[2*path[i][0] + (path[i-1][0])+1-path[i][0]][2*path[i][1] + (path[i-1][1]-path[i][1])+1] = \">\"\n \n #print the display grid \n for i in range(len(display[0])):\n for x in display:\n print(x[i], end = \" \")\n print(\"\")\n \n \n#return the direct neighbours of piece\ndef get_neighbours(table, piece):\n l = []\n if piece.x >= 1:\n l.append(table[piece.x-1][piece.y])\n if piece.y >= 1:\n l.append(table[piece.x][piece.y-1])\n if piece.x < len(table)-1:\n l.append(table[piece.x+1][piece.y])\n if piece.y < len(table[0])-1:\n l.append(table[piece.x][piece.y+1])\n return l\n \n#make a table filled with MazePieces\ndef wall_table(width, height):\n t = []\n for x in range(width):\n row = []\n for y in range(height):\n row.append(MazePiece(x,y))\n t.append(row)\n return t\n \n \ndef make_maze(width, height):\n\n #find the size that the maze matrix needs to be since it doesn't contain\n #walls, but connections.\n width = width//2\n height = height//2\n \n \n #m will hold the maze pieces\n m = wall_table(width, height)\n \n #set the starting point and the walls around it\n maze_list = [m[0][height//2]]\n wall_list = get_neighbours(m,m[0][height//2])\n\n while wall_list:\n current = wall_list[random.randint(0,len(wall_list)-1)]\n \n #get a random neighbour that is in the maze\n n = []\n for i in get_neighbours(m,current):\n if i in maze_list:\n n.append(i)\n \n #if we found one then make a connection between the it and current\n #and add current's neighbours to the wall_list\n if n != []:\n n = n[random.randint(0, len(n)-1)]\n \n n.connections.append(current)\n current.connections.append(n)\n maze_list.append(current)\n \n for i in get_neighbours(m, current):\n if i not in maze_list and i not in wall_list:\n wall_list.append(i)\n \n wall_list.remove(current)\n\n return m\n \nif __name__ == \"__main__\":\n \n #w = 70\n #h = 70\n w = int(input(\"Please enter a width: \"))\n h = int(input(\"Please enter a height: \"))\n print_path = input(\"Print the path to the exit? (y/n): \")\n print_path = True if print_path==\"y\" else False\n \n m = make_maze(w,h)\n #print_maze_connections(m)\n print_maze(m,print_path)","sub_path":"maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"370655254","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 29 12:26:47 2021\r\n\r\n@author: pyliu\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport scipy as sp\r\nimport time\r\n\r\nfrom underscore_prefix import *\r\nfrom underscore_suffix import *\r\nfrom select_data_edge import *\r\nfrom get_length import *\r\nfrom get_connections import *\r\nfrom get_angle_max import *\r\nfrom get_angle_sum import *\r\nfrom error_square_2samples import *\r\n\r\ndef regression_dataloader_square(df, filename = \"aaf_map.yaml\",metric = \"difference\",cutoff = 1, verbose = False, report_interval = 5000):\r\n \"\"\"\r\n Get KS scores & spatial features between edges\r\n This one does not calculate KS score for fitted lognormal distributions\r\n\r\n Parameters\r\n ----------\r\n df : pd df\r\n observations\r\n fit : pandas df\r\n contains fitted params for Bayesian lognormal optimisation\r\n filename : STR\r\n name of YAML file containing contextual information. The default is \"aaf_map.yaml\".\r\n metric : STR\r\n Valid metrics are \"difference\" & \"operation_time\". The default is \"difference\".\r\n cutoff : INT\r\n Disregards edges with fewer observations than cutoff\r\n precision : INT\r\n precision of KS test for fitted distributions. The default is 2.\r\n verbose : BOOL\r\n If true, print statements to update user about progress. The default is False.\r\n report_interval : INT\r\n How frequently to update user. The default is 5000.\r\n\r\n Raises\r\n ------\r\n ValueError\r\n invalid metric.\r\n\r\n Returns\r\n -------\r\n df_ks_diff : pandas df\r\n columns = [\"edge1\",\"edge2\",\r\n \"n_obs1\",\"n_obs2\",\r\n \"ks\",\"square\",\r\n \"edge_length_diff\", \"origin_connections_diff\", \r\n \"target_connections_diff\", \"total_connections_diff\", \r\n \"max_angle_diff\", \"sum_angle_diff\"]\r\n ks_raw is output of 2 sample KS test\r\n\r\n \"\"\"\r\n \r\n tic = time.time()\r\n #turn off warnings\r\n pd.options.mode.chained_assignment = None # default='warn'\r\n \r\n valid_metrics = [\"operation_time\", \"difference\"]\r\n if metric not in valid_metrics:\r\n raise ValueError(\"Invalid metric. Valid metrics are ['operation_time', 'difference']\")\r\n \r\n #1) Order edges by amount of data\r\n #1a) Order the data in terms of edges with the largest no. of observations\r\n count = df[\"edge_id\"].value_counts() #sort by no. of samples per edge\r\n count.to_csv('waypoint_pairs.csv') #save and reload for DataFrame format\r\n count = pd.read_csv(\"waypoint_pairs.csv\")\r\n count.columns = [\"edge_id\", \"samples\"] #rename columns\r\n \r\n #1b) split edge_id into target & origin\r\n count[\"origin\"] = None #Add new columns\r\n count[\"target\"] = None\r\n \r\n for i in range(len(count[\"edge_id\"])):\r\n count[\"origin\"][i] = underscore_prefix(str(count[\"edge_id\"][i]))\r\n count[\"target\"][i] = underscore_suffix(str(count[\"edge_id\"][i]))\r\n \r\n #2) initialise empty dataframe to store results\r\n n_edges = len(count)\r\n n_edge_pairs = int(n_edges * (n_edges-1)//2)\r\n df_ks_diff = pd.DataFrame(index = np.arange(n_edge_pairs), \r\n columns = [\"edge1\",\"edge2\",\r\n \"n_obs1\",\"n_obs2\",\r\n \"ks\",\"square\",\r\n \"edge_length_diff\", \"origin_connections_diff\", \r\n \"target_connections_diff\", \"total_connections_diff\", \r\n \"max_angle_diff\", \"sum_angle_diff\"])\r\n\r\n #3) get context\r\n length = get_length(filename,suppress_message = True)\r\n connections = get_connections(filename,suppress_message = True)\r\n angle_max = get_angle_max(filename,suppress_message = True)\r\n angle_sum = get_angle_sum(filename,suppress_message = True)\r\n \r\n #4) Load fit data\r\n for i in range(n_edges-1):\r\n #load edge 1 data\r\n edge1 = count[\"edge_id\"][i]\r\n subset1 = select_data_edge(df, edge1)\r\n #skip edge if below cutoff\r\n if len(subset1) < cutoff:\r\n continue\r\n \r\n #fit edge 1\r\n if metric == \"operation_time\":\r\n t_op1 = subset1[\"operation_time\"]\r\n elif metric == \"difference\":\r\n t_op1 = subset1[\"operation_time\"] - subset1[\"time_to_waypoint\"]\r\n else:\r\n raise ValueError(\"Invalid metric. Valid metrics are ['operation_time','difference']\")\r\n \r\n \r\n for j in range(i+1,n_edges):\r\n index = i*n_edges + j\r\n \r\n #progress update\r\n if verbose == True:\r\n if index % report_interval == 0:\r\n toc = time.time()\r\n print(index, \"iterations:\", toc-tic, \"secs\")\r\n \r\n #load edge 2 data\r\n edge2 = count[\"edge_id\"][j]\r\n subset2 = select_data_edge(df, edge2)\r\n #skip edge if below cutoff\r\n if len(subset2) < cutoff:\r\n continue\r\n\r\n #fit edge 2\r\n if metric == \"operation_time\":\r\n t_op2 = subset2[\"operation_time\"]\r\n elif metric == \"difference\":\r\n t_op2 = subset2[\"operation_time\"] - subset2[\"time_to_waypoint\"]\r\n else:\r\n raise ValueError(\"Invalid metric. Valid metrics are ['operation_time','difference']\")\r\n \r\n #5) Calculate values for dataframe\r\n #5a) Edge names & no. of observations\r\n df_ks_diff[\"edge1\"][index] = edge1\r\n df_ks_diff[\"edge2\"][index] = edge2\r\n df_ks_diff[\"n_obs1\"][index] = len(subset1)\r\n df_ks_diff[\"n_obs2\"][index] = len(subset2)\r\n \r\n #5b) KS values\r\n ks_raw,p_val_raw = sp.stats.ks_2samp(t_op1,t_op2)\r\n df_ks_diff[\"ks\"][index] = ks_raw\r\n \r\n area = error_square_2samples(t_op1, t_op2, plot_graph = False)\r\n df_ks_diff[\"square\"][index] = area\r\n \r\n #5c) Spatial features\r\n df_ks_diff[\"edge_length_diff\"][index] = np.abs(length[edge1] - length[edge2])\r\n df_ks_diff[\"origin_connections_diff\"][index] = np.abs(connections[edge1][0] - connections[edge2][0])\r\n df_ks_diff[\"target_connections_diff\"][index] = np.abs(connections[edge1][1] - connections[edge2][1])\r\n df_ks_diff[\"total_connections_diff\"][index] = np.abs(np.sum(connections[edge1]) - np.sum(connections[edge2]))\r\n df_ks_diff[\"max_angle_diff\"][index] = np.abs(angle_max[edge1] - angle_max[edge2])\r\n df_ks_diff[\"sum_angle_diff\"][index] = np.abs(angle_sum[edge1] - angle_sum[edge2])\r\n \r\n \r\n df_ks_diff = df_ks_diff.dropna().reset_index(drop=True)\r\n toc = time.time()\r\n print(\"Time taken (regression_dataloader):\", toc-tic,\"secs\")\r\n \r\n return df_ks_diff\r\n \r\n \r\n ","sub_path":"Wk9_STRANDS/regression_dataloader_square.py","file_name":"regression_dataloader_square.py","file_ext":"py","file_size_in_byte":6958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"79673942","text":"#-*-encode: utf-8 -*-\n\n##############\n#Technion #\n#Architecture#\n#Professors #\n##############\n\nfrom lxml import html\nimport urllib, re, sys\nsys.path.append(r'C:\\Python27\\Scripts\\Experiments\\databases')\nfrom export_classes import instances_to_file\n\ndef get_domain(url):\n\tdomain_regex = r'(http://)?(www.)?(?P[^/]+)'\n\tmatch = re.search(domain_regex, url)\n\tif match:\n\t\tresult = match.group('domain')\n\telse:\n\t\tresult = raw_input('Enter file name:\\n')\n\treturn result\n\nclass BiologyStaff(object):\n\tattributes_ordered = ['name', 'job', 'phone', 'email', 'office_location', 'pic_url']\n\tdef __init__(self, name='', job='', phone='', office_location='', email='', pic_url='', specialties=''):\n\t\tself.name=name\n\t\tself.job=job\n\t\tself.phone=phone\n\t\tself.email=email\n\t\tself.office_location=office_location\n\t\tself.pic_url=pic_url\n\n\tdef __str__(self):\n\t\treturn self.name\n\ndef clean_email(str_email):\n\treturn re.sub('^mailto:', '', str_email).strip()\n\ndef clean_and_concat(str_specialties):\n\n\tif isinstance(str_specialties, list):\n\t\tonly_specialties = [str_specialty.strip() for str_specialty in str_specialties if str_specialty.strip()]\n\t\treturn '|'.join(map(lambda x: unicode(re.sub(r'(^[\\s*|]*)|([\\s*|]*$)', '', x)), only_specialties))\n\treturn str_specialties\n\ndef first_item_or_null(value_lst):\n\tif len(value_lst) > 0:\n\t\tvalue = value_lst[0]\n\t\tif type(value) == html.HtmlElement:\n\t\t\t#Get text of element\n\t\t\tvalue = value.text_content()\n\n\t\t#XML Element\n\t\treturn unicode(value)\n\n\treturn ''\n\n\ndef parse_professor_from_row(professor_row_element, url_domain=''):\n\tname_path = './/div[@class=\"memberName\"]//a/text()'\n\tjob_path = './/div[@class=\"memberPosition\"]/text()'\n\tphone_path = './/span[@class=\"phone\"]/text()'\n\temail_path = './/div[@class=\"memberEmail\"]/a/text()'\n\toffice_location_path = './/span[@class=\"room\"]/text()'\n\tpic_url_path = './/td[@class=\"memberProfileImage\"]//img/@src'\n\n\n\tname = first_item_or_null(professor_row_element.xpath(name_path))\n\tif name != '':\n\t\tjob = clean_and_concat(professor_row_element.xpath(job_path))\n\t\tphone = first_item_or_null(professor_row_element.xpath(phone_path))\n\t\temail = first_item_or_null(professor_row_element.xpath(email_path))\n\t\toffice_location = first_item_or_null(professor_row_element.xpath(office_location_path))\n\t\tpic_url = url_domain + first_item_or_null(professor_row_element.xpath(pic_url_path))\n\t\t\n\t\tprofessor = BiologyStaff(name=name, job=job, phone=phone, email=email, office_location=office_location, pic_url=pic_url)\n\t\treturn professor\n\treturn None\n\ndef parse_professors(base_url):\n\t\"\"\" parses professors from different URL's \"\"\"\n\n\turl_domain = get_domain(base_url)\n\n\trow_xpath = '//table[@class=\"stuffMember\"]'\n\n\tprofessors_lst = []\n\tpage_source=urllib.urlopen(base_url).read()\n\n\tpage_tree = html.fromstring(page_source)\n\tprofessor_rows = page_tree.xpath(row_xpath)\n\n\tfor professor_row in professor_rows:\n\t\tprofessor = parse_professor_from_row(professor_row, url_domain)\n\t\tif professor != None:\n\t\t\tprofessors_lst.append(professor)\n\n\treturn professors_lst\n\ndef main():\n\tBASE_URL=r'http://biology.technion.ac.il/?cmd=staff.161&letter='\n\tprofessors_lst = parse_professors(BASE_URL)\n\tinstances_to_file(professors_lst)\n\n\treturn professors_lst\n","sub_path":"scrapers/technion/biology_technion_professor.py","file_name":"biology_technion_professor.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"607805557","text":"from lib.db_functions import DB_Python_czas as DB\nfrom lib.add_data_time import *\nfrom python_time.python_data_operation import *\nfrom lib.charts_options import wykres\n\n\nclass Python_time_choises():\n\n def __init__(self):\n self.db = DB()\n\n def seperator(self):\n print(\"\\n\"*2)\n print(\"-\"*60)\n print(\"\\n\"*2)\n\n def choice_1_1(self):\n data_base = self.db\n data_base.create_table()\n data_base.add_data(get_data(), get_time())\n\n def choice_2_1(self):\n DB_fun = self.db\n print(\"Wybierz datę od: \")\n datafiltr_1 = get_data()\n print(\"Wybierz datę do: \")\n datafiltr_2 = get_data()\n data = DB_fun.selec_data(datafiltr_1, datafiltr_2)\n time_list = [line for line in data[1::2]]\n time_sum = time_paras(time_list)\n print(\n f\"\\nNa nauke Python od {datafiltr_1} do \"\n f\"{datafiltr_2} przeznaczyłeś {time_sum}\\n\")\n self.seperator()\n\n def choice_2_2(self):\n DB_fun = self.db\n data = DB_fun.selec_data()\n time_list = [line for line in data[1::2]]\n time_sum = time_paras(time_list)\n print(f\"\\nŁącznie na nauke Pythona przeznaczyłeś {time_sum}\")\n self.seperator()\n\n def choice_2_3(self):\n DB_fun = self.db\n data = DB_fun.selec_data()\n data_list = [line for line in data[0::2]]\n time_list = [line for line in data[1::2]]\n lista_czasu = time_in_mins_list(time_list)\n wykres(lista_czasu, data_list)\n\n def choice_3_1(self):\n DB_fun = self.db\n data = DB_fun.selec_data()\n time_list = [line for line in data[1::2]]\n money_per_hour = 0.2\n time_value = money_for_time(time_list, money_per_hour)\n if time_value == 0:\n pass\n else:\n result = round(time_value, 2)\n print(f\"Łącznie za naukę przysługuje {result} zł.\")\n self.seperator()\n\n def choice_3_2(self):\n DB_fun = self.db\n data = DB_fun.selec_data()\n time_list = [line for line in data[1::2]]\n money_per_hour = 0.2\n time_value = money_for_time(time_list, money_per_hour)\n cash_out_list = DB_fun.selec_cash()\n money_left(cash_out_list, time_value)\n self.seperator()\n\n def choice_3_3(self):\n DB_fun = self.db\n DB_fun.create_table_cash()\n data = get_data()\n cash = add_cash()\n DB_fun.add_cash(data, cash)\n self.seperator()\n","sub_path":"python_time/python_time_choises.py","file_name":"python_time_choises.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"461673853","text":"import os\nfrom argparse import ArgumentParser\n\nimport cv2\nimport torch\n\nfrom mmpose.apis import (inference_bottom_up_pose_model, init_pose_model,\n vis_pose_result)\n\n\ndef parse_args():\n parser = ArgumentParser(description='MMDetection webcam demo')\n parser.add_argument('pose_config', help='Config file for pose')\n parser.add_argument('pose_checkpoint', help='Checkpoint file for pose')\n parser.add_argument(\n '--device', type=str, default='cuda:0', help='CPU/CUDA device option')\n parser.add_argument('--img_root', type=str, default='', help='Image root')\n parser.add_argument(\n '--kpt-thr', type=float, default=0.01, help='Keypoint score threshold')\n args = parser.parse_args()\n return args\n\ndef get_pose(img, result_path, pose_config='./mobilenetv2_coco_512x512.py',\n pose_checkpoint='./mobilenetv2_coco_512x512-4d96e309_20200816.pth', device='cpu', kpt_thr=0.5):\n\n # build the pose model from a config file and a checkpoint file\n pose_model = init_pose_model(\n pose_config, pose_checkpoint, device=device.lower())\n # optional\n return_heatmap = False\n dataset = pose_model.cfg.data['test']['type']\n assert (dataset == 'BottomUpCocoDataset')\n\n # e.g. use ('backbone', ) to return backbone feature\n output_layer_names = None\n img = cv2.imread(img)\n\n pose_results, returned_outputs = inference_bottom_up_pose_model(\n pose_model,\n img,\n return_heatmap=return_heatmap,\n outputs=output_layer_names)\n # show the results\n vis_img = vis_pose_result(\n pose_model,\n img,\n pose_results,\n dataset=dataset,\n kpt_score_thr=kpt_thr,\n show=False)\n cv2.imwrite(result_path, vis_img)\n\n sample0 = {\"url\": result_path}\n\n res_list = [sample0]\n\n return res_list\n\ndef main():\n args = parse_args()\n\n device = torch.device(args.device)\n\n # build the pose model from a config file and a checkpoint file\n pose_model = init_pose_model(\n args.pose_config, args.pose_checkpoint, device=args.device.lower())\n # optional\n return_heatmap = False\n dataset = pose_model.cfg.data['test']['type']\n assert (dataset == 'BottomUpCocoDataset')\n\n # e.g. use ('backbone', ) to return backbone feature\n output_layer_names = None\n print('Press \"Esc\", \"q\" or \"Q\" to exit.')\n while True:\n # ret_val, img = camera.read()\n img = cv2.imread(args.img_root)\n\n pose_results, returned_outputs = inference_bottom_up_pose_model(\n pose_model,\n img,\n return_heatmap=return_heatmap,\n outputs=output_layer_names)\n # show the results\n vis_img = vis_pose_result(\n pose_model,\n img,\n pose_results,\n dataset=dataset,\n kpt_score_thr=args.kpt_thr,\n show=False)\n ch = cv2.waitKey(1)\n if ch == 27 or ch == ord('q') or ch == ord('Q'):\n break\n\n cv2.imshow('Image', vis_img)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"web_server/image_demo.py","file_name":"image_demo.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105892580","text":"import os\nfrom setuptools import setup\n\ndata_files = []\nfor root, dirs, files in os.walk(\"lib/domains\"):\n data_files.append((os.path.join(\"swot_lib\", root), [os.path.join(root, f) for f in files]))\n\nwith open(\"README.rst\") as f:\n long_description = f.read()\n\nwith open(\"VERSION\") as f:\n version = f.read()\n\nsetup(\n name=\"swot\",\n version=version,\n description=(\"Swot is a community-driven or crowdsourced library for verifying \"\n \"that domain names and email addresses are tied to a legitimate university of college.\"),\n long_description=long_description,\n keywords=\"swot email academic university college verification identification\",\n author=\"Zakaria Elkatani\",\n author_email=\"zelkatani@gmail.com\",\n license=\"MIT\",\n url=\"http://github.com/ze/swot\",\n data_files=data_files,\n py_modules=[\"swot\"],\n python_requires=\">=3.6\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"535312536","text":"from freeze_rules.util import desc\nfrom rules import NormalRule\n\n\ndef get_rules():\n rules = [\n NormalRule([\"OCSymbolWithQualifiedName.getLocationString\"],\n desc(\"getLocationString()\", \"CPP-10102\", fixed=\"review\")),\n NormalRule([\"TextEditorPsiDataProvider.getData\", \"TargetElementUtil.findTargetElement\"],\n desc(\"getData(PSI_ELEMENT)\")),\n ]\n return rules\n","sub_path":"freeze_rules/resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"479802814","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User, auth\n#from django.contrib.auth.forms import UserCreationProfile\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.contrib.auth import login, authenticate\nfrom .forms import RegisterForm\nimport speech_recognition as sr\nimport pyttsx3\nimport wolframalpha\nimport wikipedia\nimport webbrowser\nfrom .models import review\nfrom .models import news\nfrom .models import event\nfrom .forms import EventForm\nfrom .forms import ImageForm\nfrom .models import UserProfile\nfrom .forms import EditProfileForm\nfrom .models import project\nfrom .models import achievements\nfrom .forms import EditProfileForm,UserProfileForm,AcheivementForm,ProjectForm\nfrom django.contrib import messages\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.urls import reverse_lazy\nfrom .models import report\nfrom .forms import Report\n \n# Create your views here.\ndef comment(request):\n obj = review.objects.all()\n return render(request,\"review.html\",{'obj':obj})\n\n\ndef add_comment(request):\n p = request.GET['head']\n c = request.GET['review']\n review.objects.create(name=p,comment=c)\n return HttpResponseRedirect(\"/\")\n\ndef basic(request):\n\t\n return render(request,\"basic.html\",{'name':request.user.username})\n\n\ndef pybot(request):\n query = request.GET.get('query')\n\n \n try:\n client = wolframalpha.Client(\"<--Your API key-->\")\n res = client.query(query)\n ans = next(res.results).text\n return render(request,\"pybot.html\", {'ans': ans, 'query': query})\n\n \n except Exception:\n try:\n ans = wikipedia.summary(query, sentences=10)\n return render(request,\"pybot.html\", {'ans': ans, 'query': query})\n\n\n except Exception:\n ans = \"FOUND NOTHING\"\n return render(request,\"pybot.html\", {'ans': ans, 'query': query})\n\ndef register(request):\n form = UserCreationForm()\n \n \n\n if request.method == \"POST\":\n form = RegisterForm(request.POST)\n \n if form.is_valid():\n form.save()\n return redirect(\"/\")\n else:\n return redirect(\"register/\")\n \n \n context = {'form':form}\n return render(request,\"register.html\",context)\n\ndef tmembers(request,tager=\"1\"):\n obj1=UserProfile.objects.get(idcard=1)\n obj2=UserProfile.objects.get(idcard=2)\n obj3=UserProfile.objects.get(idcard=3)\n return render(request,\"tmembers.html\",{'obj1':obj1,'obj2':obj2,'obj3':obj3})\n \ndef aboutus(request):\n return render(request,\"aboutus.html\")\ndef contactus(request):\n return render(request,\"contactus.html\")\n\n\n\n\ndef newspost(request):\n obj=news.objects.all()\n return render(request,\"newspostdisplay.html\",{'obj':obj})\n\ndef pproject(request):\n obj=project.objects.all()\n return render(request,\"project.html\",{'obj':obj})\n\ndef newspostupload(request):\n \n if request.method == 'POST':\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n \n img_obj = form.instance\n return render(request, 'addpost.html', {'form': form, 'img_obj': img_obj})\n else:\n form = ImageForm()\n return render(request, 'addpost.html', {'form': form})\n\ndef projectupload(request):\n \n if request.method == 'POST':\n form = ProjectForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n \n img_obj = form.instance\n return render(request, 'uploadproject.html', {'form': form, 'img_obj': img_obj})\n else:\n form = ProjectForm()\n return render(request, 'uploadproject.html', {'form': form})\n\ndef addachievements(request):\n if request.method == 'POST':\n form = AcheivementForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n \n img_obj = form.instance\n return render(request, 'addachievements.html', {'form': form, 'img_obj': img_obj})\n else:\n form = AcheivementForm()\n return render(request, 'addachievements.html', {'form': form})\n\ndef eventspostupload(request):\n \n if request.method == 'POST':\n form = EventForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n \n img_obj = form.instance\n return render(request, 'addpostevents.html', {'form': form, 'img_obj': img_obj})\n else:\n form = EventForm()\n return render(request, 'addpostevents.html', {'form': form})\n\ndef eventpost(request):\n obj=event.objects.all()\n \n return render(request,\"events.html\",{'obj':obj})\n\ndef profile(request,tager=\"1\"):\n s=request.GET.get('test')\n #return HttpResponse(s)\n q=UserProfile.objects.get(idcard=s)\n return render(request,\"profile.html\",{'q':q})\n\ndef viewprofile(request):\n \n if request.method == 'POST':\n e_form = EditProfileForm(request.POST,instance=request.user)\n u_form = UserProfileForm(request.POST,request.FILES,instance=request.user.userprofile)\n \n if e_form.is_valid() and u_form.is_valid():\n e_form.save()\n u_form.save()\n messages.success(request,f'your account has been updated!')\n return redirect('dispprofile')\n else:\n e_form = EditProfileForm(instance=request.user)\n u_form = UserProfileForm(instance=request.user.userprofile) \n context ={\n 'e_form':e_form,\n 'u_form':u_form\n }\n return render(request,\"viewprofile.html\",context) \n\ndef members(request):\n obj=UserProfile.objects.all()\n #obj = review.objects.all()\n #return HttpResponse(obj)\n return render(request,\"members.html\",{'obj':obj})\n\ndef newspage(request):\n obj=report.objects.all()\n return render(request,\"news.html\",{'obj':obj})\n\ndef aachievements(request):\n obj=achievements.objects.all()\n return render(request,\"achievements.html\",{'obj':obj})\n\ndef DispProfile(request):\n return render(request,\"disp_profile.html\")\n\ndef reportupload(request):\n \n if request.method == 'POST':\n form = Report(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n \n img_obj = form.instance\n return render(request, 'reportnews.html', {'form': form, 'img_obj': img_obj})\n else:\n form = Report()\n return render(request, 'reportnews.html', {'form': form}) \n\ndef showinfo(request):\n a=request.GET['image']\n b=request.GET['information']\n return render(request,\"showinfo.html\",{'a':a,'b':b})\n\n\ndef viewinfo(request,tager=\"1\"):\n a = request.GET.get('info')\n obj = news.objects.all().get(pk = a)\n context = {\n 'obj':obj\n }\n return render(request,\"viewinfo.html\",context)\n\ndef testingresize(request):\n return render(request,\"testingresize.html\",{})","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"88507342","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport xml.etree.cElementTree as ET\nimport pprint\n'''\ntakes OSM file then finds tags and counts number of occurrences;\nreturns a dictionary with tag names as keys and counts of tags as values\n'''\ndef count_tags(filename):\n tags = {}\n for event, elem in ET.iterparse(filename):\n if elem.tag not in tags.keys():\n tags[elem.tag] = 1\n else:\n tags[elem.tag] += 1\n return tags\n\n\nmy_file = 'sample.OSM'\ncount_tags(my_file)\n\ndef test():\n\n tags = count_tags('sample.osm')\n pprint.pprint(tags)\n '''\n assert tags == {'bounds': 1,\n 'member': 3,\n 'nd': 4,\n 'node': 20,\n 'osm': 1,\n 'relation': 1,\n 'tag': 7,\n 'way': 1}\n '''\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"DAND/OpenStreetMap/count_tags.py","file_name":"count_tags.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"153016542","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport facenet\nimport os\nimport sys\nimport math\nimport pickle\nfrom sklearn.svm import SVC\nimport time\nimport cv2\n\nmodel_path = \"./models/20170512-110547.pb\"\ninit_image_path = \"./image/init.png\"\n\nclass Classify():\n def __init__(self,model):\n self._model = model\n tensorflow_graph = tf.Graph()\n with tensorflow_graph.as_default():\n facenet.load_model(model_path)\n self.images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n self.embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n self.phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n self.embedding_size = self.embeddings.get_shape()[1]\n self.sess = tf.Session(graph=tensorflow_graph)\n init_frame = cv2.imread(init_image_path)\n self.classify_image(init_frame)\n\n def classify_image(self,image):\n np.random.seed(seed=666)\n\n model = self._model.get_model()\n class_names = self._model.get_class_names()\n\n nrof_images = 1\n emb_array = np.zeros((nrof_images, self.embedding_size))\n\n images = facenet.load_data(image, False, False, 160)\n \n feed_dict = { self.images_placeholder:images, self.phase_train_placeholder:False }\n \n emb_array[0:1,:] = self.sess.run(self.embeddings, feed_dict=feed_dict)\n \n predictions = model.predict_proba(emb_array)\n best_class_indices = np.argmax(predictions, axis=1)\n best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]\n \n mistake_number = 0\n ChangeToStranger = False\n second_class_indices = predictions[0].argsort()[-3:][::-1][1]\n second_class_probabilities = predictions[0][second_class_indices]\n if(predictions.shape[1] > 2):\n third_class_indices = predictions[0].argsort()[-3:][::-1][2]\n third_class_probabilities = predictions[0][third_class_indices]\n else:\n third_class_indices = 0\n third_class_probabilities = 0\n\n if(self.first_filter(class_names,best_class_indices,0)):\n if(self.second_filter(best_class_probabilities,0)):\n if(self.third_filter(best_class_probabilities,0) or self.forth_filter(class_names,second_class_indices,third_class_probabilities)):\n mistake_number = mistake_number + 1\n print('%s: %.3f' % (class_names[best_class_indices[0]], best_class_probabilities))\n print('%s: %.3f' % (class_names[second_class_indices], second_class_probabilities))\n print('%s: %.3f' % (class_names[third_class_indices], third_class_probabilities)) \n ChangeToStranger = True\n \n classify_people_name = class_names[best_class_indices[0]]\n classify_rate = best_class_probabilities[0]\n if(classify_people_name == \"unknown\"):\n classify_rate = 1.0\n if(ChangeToStranger):\n classify_rate = 1.0\n classify_people_name = \"unknown\"\n return (classify_people_name, classify_rate)\n \n def first_filter(self,class_names,best_class_indices,index):\n return (class_names[best_class_indices[index]] != \"unknow\")\n\n def second_filter(self,best_class_probabilities,index):\n return (best_class_probabilities[index] < 0.5)\n \n def third_filter(self,best_class_probabilities,index):\n return (best_class_probabilities[index] < 0.3) \n\n def forth_filter(self,class_names,second_class_indices,third_class_probabilities):\n return (class_names[second_class_indices] != \"unknown\" or third_class_probabilities > 0.1) \n\n","sub_path":"device/Classify.py","file_name":"Classify.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"456919793","text":"import reward as Cls\n\npop_size= 1000\nn_time_steps=20\ncoin_prob=0.5\n\nmyCohort = Cls.cohort(id=1, pop_size=pop_size, coin_prob=coin_prob)\n\nmyCohort.simulate(n_time_steps)\n\n\nprint ('average of these realizations', myCohort.get_reward())\n","sub_path":"reward_run.py","file_name":"reward_run.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"240005519","text":"# -*- coding: utf-7 -*-\r\n\"\"\"\r\nCreated on Sun May 12 23:13:15 2019\r\n\r\n@author: 12134\r\n\"\"\"\r\n\r\nimport os\r\nimport sys\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\nimport math\r\nfrom torch.autograd import Function\r\nimport torch.nn.functional as F\r\n\r\ntry:\r\n from urllib import urlretrieve\r\nexcept ImportError:\r\n from urllib.request import urlretrieve\r\n\r\n\r\nmodel_urls = {'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\r\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'\r\n}\r\n\r\n\r\nzsize = 48\r\nbatch_size = 16\r\niterations = 20\r\nlearningRate= 0.0001\r\n\r\ndef conv3x3(in_planes, out_planes, stride=1):\r\n \"\"\"3x3 convolution with padding\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\r\n padding=1, bias=False)\r\n\r\nclass BasicBlock(nn.Module):\r\n expansion = 1\r\n\r\n def __init__(self, inplanes, planes, stride=1, downsample=None):\r\n super(BasicBlock, self).__init__()\r\n self.conv1 = conv3x3(inplanes, planes, stride)\r\n self.bn1 = nn.BatchNorm2d(planes)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = conv3x3(planes, planes)\r\n self.bn2 = nn.BatchNorm2d(planes)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n out += residual\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n\r\nclass Bottleneck(nn.Module):\r\n expansion = 4\r\n\r\n def __init__(self, inplanes, planes, stride=1, downsample=None):\r\n super(Bottleneck, self).__init__()\r\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\r\n self.bn1 = nn.BatchNorm2d(planes)\r\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\r\n padding=1, bias=False)\r\n self.bn2 = nn.BatchNorm2d(planes)\r\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\r\n self.bn3 = nn.BatchNorm2d(planes * 4)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n\t\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv3(out)\r\n out = self.bn3(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n out += residual\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n###############################################################\r\n\r\n\r\n\r\n###############################################################\r\nclass Encoder(nn.Module):\r\n\r\n def __init__(self, block, layers, num_classes=23):\r\n self.inplanes = 64\r\n super (Encoder, self).__init__()\r\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\r\n bias=False)\r\n self.bn1 = nn.BatchNorm2d(64)\r\n self.relu = nn.ReLU(inplace=False)\r\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)#, return_indices = True)\r\n self.layer1 = self._make_layer(block, 64, layers[0])\r\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\r\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\r\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\r\n self.avgpool = nn.AvgPool2d(7, stride=1)\r\n self.fc = nn.Linear(512 * block.expansion, 1000)\r\n\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n m.weight.data.normal_(0, math.sqrt(2. / n))\r\n elif isinstance(m, nn.BatchNorm2d):\r\n m.weight.data.fill_(1)\r\n m.bias.data.zero_()\r\n\r\n def _make_layer(self, block, planes, blocks, stride=1):\r\n downsample = None\r\n if stride != 1 or self.inplanes != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n nn.Conv2d(self.inplanes, planes * block.expansion,\r\n kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm2d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes, planes, stride, downsample))\r\n self.inplanes = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n\t\r\n x = self.bn1(x)\r\n x = self.relu(x)\r\n\t\r\n x = self.maxpool(x)\r\n\t\r\n x = self.layer1(x)\r\n x = self.layer2(x)\r\n x = self.layer3(x)\r\n x = self.layer4(x)\r\n\r\n x = self.avgpool(x)\r\n x = x.view(x.size(0), -1)\r\n x = self.fc(x)\r\n\r\n return x\r\n\r\ndef load_url(url, model_dir='./pretrained', map_location=None):\r\n if not os.path.exists(model_dir):\r\n os.makedirs(model_dir)\r\n filename = url.split('/')[-1]\r\n cached_file = os.path.join(model_dir, filename)\r\n if not os.path.exists(cached_file):\r\n sys.stderr.write('Downloading: \"{}\" to {}\\n'.format(url, cached_file))\r\n urlretrieve(url, cached_file)\r\n return torch.load(cached_file, map_location=map_location) \r\n\r\nencoder = Encoder(Bottleneck, [3, 4, 6, 3])\r\nencoder.load_state_dict(load_url(model_urls['resnet50']), strict=False)\r\nencoder.fc = nn.Linear(2048, 48)\r\n\r\nencoder=encoder.cuda()\r\ny=torch.rand(1,3,224,224)\r\nx=torch.rand(1,128)\r\nx=Variable(x.cuda())\r\n\r\n##########################################################################\r\nclass Binary(Function):\r\n\r\n @staticmethod\r\n def forward(ctx, input):\r\n return F.relu(Variable(input.sign())).data\r\n\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n return grad_output\r\n\r\nbinary = Binary()\r\n##########################################################################\r\n\r\nclass Decoder(nn.Module):\r\n def __init__(self):\r\n super(Decoder,self).__init__()\r\n self.dfc3 = nn.Linear(zsize, 4096)\r\n self.bn3 = nn.BatchNorm2d(4096)\r\n self.dfc2 = nn.Linear(4096, 4096)\r\n self.bn2 = nn.BatchNorm2d(4096)\r\n self.dfc1 = nn.Linear(4096,256 * 6 * 6)\r\n self.bn1 = nn.BatchNorm2d(256*6*6)\r\n self.upsample1=nn.Upsample(scale_factor=2)\r\n self.dconv5 = nn.ConvTranspose2d(256, 256, 3, padding = 0)\r\n self.dconv4 = nn.ConvTranspose2d(256, 384, 3, padding = 1)\r\n self.dconv3 = nn.ConvTranspose2d(384, 192, 3, padding = 1)\r\n self.dconv2 = nn.ConvTranspose2d(192, 64, 5, padding = 2)\r\n self.dconv1 = nn.ConvTranspose2d(64, 3, 12, stride = 4, padding = 4)\r\n\r\n def forward(self,x):\r\n\r\n x = self.dfc3(x)\r\n x = F.relu(self.bn3(x))\r\n\r\n x = self.dfc2(x)\r\n x = F.relu(self.bn2(x))\r\n x = self.dfc1(x)\r\n x = F.relu(self.bn1(x))\r\n x = x.view(batch_size,256,6,6)\r\n x=self.upsample1(x)\r\n x = self.dconv5(x)\r\n x = F.relu(x)\r\n x = F.relu(self.dconv4(x))\r\n x = F.relu(self.dconv3(x)) \r\n x=self.upsample1(x) \r\n x = self.dconv2(x) \r\n x = F.relu(x)\r\n x=self.upsample1(x)\r\n x = self.dconv1(x)\r\n x = F.sigmoid(x)\r\n return x\r\ndecoder = Decoder().cuda()\r\n##########################################\r\nclass Autoencoder(nn.Module):\r\n def __init__(self):\r\n super(Autoencoder,self).__init__()\r\n self.encoder = encoder\r\n self.binary = Binary()\r\n self.decoder = Decoder().cuda()\r\n\r\n def forward(self,x):\r\n x = self.encoder(x)\r\n x = binary.apply(x)\r\n x = self.decoder(x)\r\n return x\r\n\r\nautoencoder = Autoencoder()\r\nif torch.cuda.is_available():\r\n autoencoder.cuda()\r\n decoder.cuda()\r\n encoder.cuda()\r\nprint(\"Done\")","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":8563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"521572077","text":"import copy\nfrom statistics import mean\nimport numpy as np\nimport time\nfrom helpers import is_atari_game, store_safely, Database\nfrom race_components.helpers import load_race_agents_config\nfrom rl.make_game import make_game\nfrom models.model_tf2 import ModelWrapper\nfrom policies.eval_policy import eval_policy, parallelize_eval_policy\nimport json\nfrom utils.env_wrapper import Wrapper\nfrom particle_filtering.parallel_sampler import ParallelSampler\nimport os\n\nfrom utils.race_wrapper import RaceWrapper\n\nDEBUG = False\nDEBUG_TAXI = False\nUSE_TQDM = True\n\n\n#### Agent ####\ndef agent(game, n_ep, n_mcts, max_ep_len, lr, c, gamma, data_size, batch_size, temp, n_hidden_layers, n_hidden_units,\n stochastic=False, eval_freq=-1, eval_episodes=100, alpha=0.6, n_epochs=100, c_dpw=1, numpy_dump_dir='../',\n pre_process=None, visualize=False, game_params={}, parallelize_evaluation=False, mcts_only=False,\n particles=0, show_plots=False, n_workers=1, use_sampler=False, budget=np.inf, unbiased=False, biased=False,\n max_workers=100, variance=False, depth_based_bias=False, scheduler_params=None, out_dir=None,\n render=False, second_version=False, third_version=False):\n visualizer = None\n\n # if particles:\n # parallelize_evaluation = False # Cannot run parallelized evaluation with particle filtering\n\n if not mcts_only:\n from mcts import MCTS\n from mcts_dpw import MCTSStochastic\n elif particles:\n if unbiased:\n from particle_filtering.ol_uct import OL_MCTS\n elif biased:\n if second_version:\n from particle_filtering.pf_uct_2 import PFMCTS2 as PFMCTS\n elif third_version:\n from particle_filtering.pf_uct_3 import PFMCTS3 as PFMCTS\n else:\n from particle_filtering.pf_uct import PFMCTS\n else:\n from particle_filtering.pf_mcts_edo import PFMCTS\n else:\n from pure_mcts.mcts import MCTS\n from pure_mcts.mcts_dpw import MCTSStochastic\n\n if parallelize_evaluation:\n print(\"The evaluation will be parallel\")\n\n parameter_list = {\"game\": game, \"n_ep\": n_ep, \"n_mcts\": n_mcts, \"max_ep_len\": max_ep_len, \"lr\": lr, \"c\": c,\n \"gamma\": gamma, \"data_size\": data_size, \"batch_size\": batch_size, \"temp\": temp,\n \"n_hidden_layers\": n_hidden_layers, \"n_hidden_units\": n_hidden_units, \"stochastic\": stochastic,\n \"eval_freq\": eval_freq, \"eval_episodes\": eval_episodes, \"alpha\": alpha, \"n_epochs\": n_epochs,\n \"out_dir\": numpy_dump_dir, \"pre_process\": pre_process, \"visualize\": visualize,\n \"game_params\": game_params, \"n_workers\": n_workers, \"use_sampler\": use_sampler,\n \"variance\": variance, \"depth_based_bias\": depth_based_bias, \"unbiased\": unbiased,\n \"second_version\": second_version, 'third_version': third_version}\n if out_dir is not None:\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n with open(os.path.join(out_dir, \"parameters.txt\"), 'w') as d:\n d.write(json.dumps(parameter_list))\n #logger = Logger(parameter_list, game, show=show_plots)\n\n if DEBUG_TAXI:\n from utils.visualization.taxi import TaxiVisualizer\n with open(game_params[\"grid\"]) as f:\n m = f.readlines()\n matrix = []\n for r in m:\n row = []\n for ch in r.strip('\\n'):\n row.append(ch)\n matrix.append(row)\n visualizer = TaxiVisualizer(matrix)\n f.close()\n exit()\n\n ''' Outer training loop '''\n if pre_process is not None:\n pre_process()\n\n # numpy_dump_dir = logger.numpy_dumps_dir\n #\n # if not os.path.exists(numpy_dump_dir):\n # os.makedirs(numpy_dump_dir)\n\n episode_returns = [] # storage\n timepoints = []\n\n # Environments\n if game == 'Trading-v0':\n game_params['save_dir'] = out_dir #logger.save_dir\n Env = make_game(game, game_params)\n num_actions = Env.action_space.n\n sampler = None\n if use_sampler and not (unbiased or biased):\n def make_pi(action_space):\n def pi(s):\n return np.random.randint(low=0, high=action_space.n)\n\n return pi\n\n def make_env():\n return make_game(game, game_params)\n\n sampler = ParallelSampler(make_pi=make_pi, make_env=make_env, n_particles=particles,\n n_workers=n_workers, seed=10)\n\n is_atari = is_atari_game(Env)\n mcts_env = make_game(game, game_params) if is_atari else None\n online_scores = []\n offline_scores = []\n\n # Setup the parameters for generating the search environments\n\n if game==\"RaceStrategy-v1\":\n mcts_maker, mcts_params, c_dpw = load_race_agents_config('envs/configs/race_strategy_full.json', gamma)\n\n else:\n mcts_params = dict(gamma=gamma)\n if particles:\n if not (biased or unbiased):\n mcts_params['particles'] = particles\n mcts_params['sampler'] = sampler\n elif biased:\n mcts_params['alpha'] = alpha\n mcts_maker = PFMCTS\n\n mcts_params['depth_based_bias'] = depth_based_bias\n if unbiased:\n mcts_params['variance'] = variance\n mcts_maker = OL_MCTS\n\n elif stochastic:\n mcts_params['alpha'] = alpha\n mcts_params['depth_based_bias'] = depth_based_bias\n mcts_maker = MCTSStochastic\n else:\n mcts_maker = MCTS\n\n # Prepare the database for storing training data to be sampled\n db = Database(max_size=data_size, batch_size=batch_size)\n\n # TODO extract dimensions to avoid allocating model\n # Setup the model\n model_params = {\"Env\": Env,\n \"lr\": lr,\n \"n_hidden_layers\": n_hidden_layers,\n \"n_hidden_units\": n_hidden_units,\n \"joint_networks\": True}\n\n model_wrapper = ModelWrapper(**model_params)\n\n t_total = 0 # total steps\n R_best = -np.Inf\n a_best = None\n seed_best = None\n\n # Variables for storing values to be plotted\n avgs = []\n stds = []\n\n # Run the episodes\n for ep in range(n_ep):\n\n if DEBUG_TAXI:\n visualizer.reset()\n\n ##### Policy evaluation step #####\n if eval_freq > 0 and ep % eval_freq == 0: # and ep > 0\n print('--------------------------------\\nEvaluating policy for {} episodes!'.format(eval_episodes))\n seed = np.random.randint(1e7) # draw some Env seed\n Env.seed(seed)\n s = Env.reset()\n\n if parallelize_evaluation:\n penv = None\n pgame = {\"game_maker\": make_game,\n \"game\": game,\n \"game_params\": game_params}\n else:\n penv = Env\n pgame = None\n\n model_file = os.path.join(out_dir, \"model.h5\")\n\n # model_wrapper.save(model_file)\n\n if game == \"RaceStrategy-v1\":\n env_wrapper = RaceWrapper(s, mcts_maker, model_file, model_params, mcts_params, is_atari, n_mcts, budget,\n mcts_env, c_dpw, temp, env=penv, game_maker=pgame, mcts_only=mcts_only,\n scheduler_params=scheduler_params)\n else:\n env_wrapper = Wrapper(s, mcts_maker, model_file, model_params, mcts_params, is_atari, n_mcts, budget,\n mcts_env, c_dpw, temp, env=penv, game_maker=pgame, mcts_only=mcts_only,\n scheduler_params=scheduler_params)\n\n # Run the evaluation\n if parallelize_evaluation:\n total_reward, reward_per_timestep, lens, action_counts = \\\n parallelize_eval_policy(env_wrapper, n_episodes=eval_episodes, verbose=False, max_len=max_ep_len,\n max_workers=max_workers, out_dir=out_dir)\n else:\n total_reward, reward_per_timestep, lens, action_counts = \\\n eval_policy(env_wrapper, n_episodes=eval_episodes, verbose=False, max_len=max_ep_len,\n visualize=visualize, out_dir=out_dir, render=render)\n\n # offline_scores.append([np.min(rews), np.max(rews), np.mean(rews), np.std(rews),\n # len(rews), np.mean(lens)])\n\n offline_scores.append([total_reward, reward_per_timestep, lens, action_counts])\n\n #np.save(numpy_dump_dir + '/offline_scores.npy', offline_scores)\n\n # Store and plot data\n avgs.append(np.mean(total_reward))\n stds.append(np.std(total_reward))\n\n #logger.plot_evaluation_mean_and_variance(avgs, stds)\n\n ##### Policy improvement step #####\n\n if not mcts_only:\n\n start = time.time()\n s = start_s = Env.reset()\n R = 0.0 # Total return counter\n a_store = []\n seed = np.random.randint(1e7) # draw some Env seed\n Env.seed(seed)\n if is_atari:\n mcts_env.reset()\n mcts_env.seed(seed)\n\n if eval_freq > 0 and ep % eval_freq == 0:\n print(\"\\nCollecting %d episodes\" % eval_freq)\n mcts = mcts_maker(root_index=s, root=None, model=model_wrapper, na=model_wrapper.action_dim,\n **mcts_params) # the object responsible for MCTS searches\n\n print(\"\\nPerforming MCTS steps\\n\")\n\n ep_steps = 0\n start_targets = []\n\n for st in range(max_ep_len):\n\n print_step = max_ep_len // 10\n if st % print_step == 0:\n print('Step ' + str(st + 1) + ' of ' + str(max_ep_len))\n\n # MCTS step\n if not is_atari:\n mcts_env = None\n mcts.search(n_mcts=n_mcts, c=c, Env=Env, mcts_env=mcts_env) # perform a forward search\n\n if visualize:\n mcts.visualize()\n\n state, pi, V = mcts.return_results(temp) # extract the root output\n\n # Save targets for starting state to debug\n if np.array_equal(start_s, state):\n if DEBUG:\n print(\"Pi target for starting state:\", pi)\n start_targets.append((V, pi))\n db.store((state, V, pi))\n\n # Make the true step\n a = np.random.choice(len(pi), p=pi)\n a_store.append(a)\n\n s1, r, terminal, _ = Env.step(a)\n\n # Perform command line visualization if necessary\n if DEBUG_TAXI:\n olds, olda = copy.deepcopy(s1), copy.deepcopy(a)\n visualizer.visualize_taxi(olds, olda)\n print(\"Reward:\", r)\n\n R += r\n t_total += n_mcts # total number of environment steps (counts the mcts steps)\n ep_steps = st + 1\n\n if terminal:\n break # Stop the episode if we encounter a terminal state\n else:\n mcts.forward(a, s1, r) # Otherwise proceed\n\n # Finished episode\n if DEBUG:\n print(\"Train episode return:\", R)\n print(\"Train episode actions:\", a_store)\n episode_returns.append(R) # store the total episode return\n online_scores.append(R)\n timepoints.append(t_total) # store the timestep count of the episode return\n #store_safely(numpy_dump_dir, '/result', {'R': episode_returns, 't': timepoints})\n #np.save(numpy_dump_dir + '/online_scores.npy', online_scores)\n\n if DEBUG or True:\n print('Finished episode {} in {} steps, total return: {}, total time: {} sec'.format(ep, ep_steps,\n np.round(R, 2),\n np.round((\n time.time() - start),\n 1)))\n # Plot the online return over training episodes\n\n #logger.plot_online_return(online_scores)\n\n if R > R_best:\n a_best = a_store\n seed_best = seed\n R_best = R\n\n print()\n\n # Train only if the model has to be used\n if not mcts_only:\n # Train\n try:\n print(\"\\nTraining network\")\n ep_V_loss = []\n ep_pi_loss = []\n\n for _ in range(n_epochs):\n # Reshuffle the dataset at each epoch\n db.reshuffle()\n\n batch_V_loss = []\n batch_pi_loss = []\n\n # Batch training\n for sb, Vb, pib in db:\n\n if DEBUG:\n print(\"sb:\", sb)\n print(\"Vb:\", Vb)\n print(\"pib:\", pib)\n\n loss = model_wrapper.train(sb, Vb, pib)\n\n batch_V_loss.append(loss[1])\n batch_pi_loss.append(loss[2])\n\n ep_V_loss.append(mean(batch_V_loss))\n ep_pi_loss.append(mean(batch_pi_loss))\n\n # Plot the loss over training epochs\n\n #logger.plot_loss(ep, ep_V_loss, ep_pi_loss)\n\n except Exception as e:\n print(\"Something wrong while training:\", e)\n\n # model.save(out_dir + 'model')\n\n # Plot the loss over different episodes\n #logger.plot_training_loss_over_time()\n\n pi_start = model_wrapper.predict_pi(start_s)\n V_start = model_wrapper.predict_V(start_s)\n\n print(\"\\nStart policy: \", pi_start)\n print(\"Start value:\", V_start)\n\n #logger.log_start(ep, pi_start, V_start, start_targets)\n\n # Return results\n if use_sampler:\n sampler.close()\n return episode_returns, timepoints, a_best, seed_best, R_best, offline_scores\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":14715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"112485923","text":"from dataclasses import dataclass\nimport random\n\n\n@dataclass\nclass Enemies:\n name: str\n health: int\n exp: int\n gold: int\n attack: str\n damage: int\n\n\n@dataclass\nclass Player:\n player_health: int\n player_health_capacity: int\n gold: int\n exp: int\n potions: list\n weapons: list\n armor: list\n spells: list\n mana: int\n mana_capacity: int\n punch: int\n\n\n@dataclass\nclass Death:\n succ1: bool\n succ2: bool\n inc: bool\n locust1: bool\n locust2: bool\n flies: bool\n flies2: bool\n lilcounter: int\n beecounter: int\n\n\n@dataclass\nclass ItemPickup:\n lr5: bool\n lr8: bool\n gr3: bool\n gr4: bool\n gr5: bool\n gr9: bool\n gr12: bool\n gr13: bool\n\n\ndef playername() -> str:\n not_player_name = input(\"Name: \")\n if not_player_name == \"Nate\":\n print(\"You are not yet allowed to play this game.\")\n quit()\n elif not_player_name == \"Dante\":\n print(\"A classic. Proceed.\")\n player_name = not_player_name\n else:\n print(\"Ew, no. We aren't using that.\")\n player_name = input(\"Name: \")\n while player_name == not_player_name:\n print(\"I said pick a new one.\")\n player_name = input(\"Name: \")\n return player_name\n\n\ndef item_pickup(player: Player, item_bools: ItemPickup, location: str) -> bool:\n if location == \"Lust R5\":\n item = \"Lesser Health Potion\"\n item_type = \"potion\"\n item_bool = item_bools.lr5\n elif location == \"Lust R8\":\n item = \"Legendary 24 in. Sub\"\n item_type = \"weapon\"\n item_bool = item_bools.lr8\n elif location == \"Gluttony R3\":\n item = \"Mysterious Potion\"\n item_type = \"potion\"\n item_bool = item_bools.gr3\n elif location == \"Gluttony R4\":\n item = \"plate of spaghett\"\n item_type = \"food\"\n item_bool = item_bools.gr4\n elif location == \"Gluttony R5\":\n item = \"plate of spaghett\"\n item_type = \"food\"\n item_bool = item_bools.gr5\n elif location == \"Gluttony R9\":\n item = \"Cooked Turkey\"\n item_type = \"food\"\n item_bool = item_bools.gr9\n elif location == \"Gluttony R12\":\n item = \"Lo Mein\"\n item_type = \"food\"\n item_bool = item_bools.gr12\n elif location == \"Gluttony R13\":\n item = \"Fly Swatter\"\n item_type = \"weapon\"\n item_bool = item_bools.gr13\n if item_bool == False:\n action = input(\"You see something on the table. Do you take it?\\n> \")\n if action == \"Yes\":\n if item_type == \"weapon\":\n player.weapons.append(item)\n item_bool = True\n print(\"You picked up a\", item)\n elif item_type == \"potion\":\n player.potions.append(item)\n item_bool = True\n print(\"You picked up a\", item)\n elif item_type == \"armor\":\n player.armor.append(item)\n item_bool = True\n if item == \"Steel Armor\":\n player.player_health_capacity = (\n player.player_health_capacity + 25)\n else:\n player.player_health_capacity = (\n player.player_health_capacity + 50)\n print(\"You put on the\", item)\n elif item_type == \"spell\":\n player.spells.append(item)\n item_bool = True\n print(\"You have learned\", item)\n elif item_type == \"food\":\n player.exp = (player.exp + 20)\n item_bool = True\n print(\n \"You ate the\", item,\n \", and it fills you with uncopywritten determination. Exp + 20\"\n )\n elif action == \"No\":\n print(\"fine then. You take nothing.\")\n else:\n print(\"You cant\", action, \"the\", item)\n print(\"Guess you don't want it\")\n return item_bool\n\n\nlimbo_info = \"A pale white forest lays before you with a pale blue glow srounding you and the forest. You feel a strange sensation around you as your body is enveloped in the strange blue light. \\n\\nYou can go to:\\nOld Town\\nCathedral\\nDecent\"\n\nold_town_info = \"A strange town in a strange place. You see mostly just houses, but there is a sign pointing down at a reasonbly kept up building called 'Bill and Dave's Item and Magic Shoppe'\\n\\nYou can go to:\\nCathedral\\nShop\\nDecent\"\n\ncathedral_info = \"Walking towards a clearing, you see a cathedral that has been burnt down, but the ash from the surrounding field had seemed to give the burnt wood a ghastly white tint. An old man stands at the pulpit. \\n\\nYou can got to: \\nOld Town\\nDecent\\nOld Man\"\n\nshop_info = \"You walk into the shop and notice two men bickering back and forth. One named Dave, the other Bill\"\n\nbill_info = \"\"\"Hi, I'm Bill. I have so many items that are way better than my brother's dumb magic stuff. Browse my wares.\n\nLesser Healing Potion - 20 gold\nHealing Potion - 30 gold\nGreater Healing Potion - 40 gold\nSteel Armor - 100 gold\nMythril Armor - 200 gold\nSteel Sword - 100 gold\nMythril Sword - 200 gold\n\"\"\"\n\n\ndef bills_shop(player: Player) -> None:\n purchase = \"\"\n while purchase != \"Q\":\n purchase = input(\"Purchase: \").title()\n if purchase == \"Lesser Healing Potion\" and player.gold >= 20:\n player.potions.append(\"Lesser Healing Potion\")\n player.gold = (player.gold - 20)\n elif purchase == \"Healing Potion\" and player.gold >= 30:\n player.potions.append(\"Healing Potion\")\n player.gold = (player.gold - 30)\n elif purchase == \"Greater Healing Potion\" and player.gold >= 40:\n player.potions.append(\"Greater Healing Potion\")\n player.gold = (player.gold - 40)\n elif purchase == \"Steel Armor\" and player.gold >= 100:\n player.armor.append(\"Steel Armor\")\n player.gold = (player.gold - 100)\n elif purchase == \"Mythril Armor\" and player.gold >= 200:\n player.armor.append(\"Mythril Armor\")\n player.gold = (player.gold - 200)\n elif purchase == \"Steel Sword\" and player.gold >= 100:\n player.weapons.append(\"Steel Sword\")\n player.gold = (player.gold - 100)\n elif purchase == \"Mythril Sword\" and player.gold >= 200:\n player.weapons.append(\"Mythril Sword\")\n player.gold = (player.gold - 200)\n else:\n print(\"invalid transaction\")\n print(\"Gold:\", player.gold)\n print(\"Exp:\", player.exp)\n print(\"Potions:\")\n for potion in player.potions:\n print(potion)\n print(\"\\nWeapons:\")\n for weapon in player.weapons:\n print(weapon)\n print(\"\\nArmor:\")\n for armors in player.armor:\n print(armors)\n print(\"\\nSpells:\")\n for spell in player.spells:\n print(spell)\n print(\"\\n\")\n\n\ndave_info = \"\"\"Im Dave, Nice to meet ya. Here's my wares but, be warned: I only trade knowledge.\n\nLesser Mana Potion - Exp 10\nMana Potion - Exp 20\nGreater Mana Potion - Exp 30\nFireball - Exp 40\nLightning - Exp 50\nFrostbite - Exp 60\nRagnarok - Exp 1000\n\"\"\"\n\n\ndef daves_shop(player: Player) -> None:\n purchase = \"\"\n while purchase != \"Q\":\n purchase = input(\"Purchase: \").title()\n if purchase == \"Lesser Mana Potion\" and player.exp >= 10:\n player.potions.append(\"Lesser Mana Potion\")\n player.exp = (player.exp - 10)\n elif purchase == \"Mana Potion\" and player.exp >= 20:\n player.potions.append(\"Mana Potion\")\n player.exp = (player.exp - 20)\n elif purchase == \"Greater Mana Potion\" and player.exp >= 30:\n player.potions.append(\"Greater Mana Potion\")\n player.exp = (player.exp - 30)\n elif purchase == \"Fireball\" and player.exp >= 40:\n player.spells.append(\"Fireball\")\n player.exp = (player.exp - 40)\n elif purchase == \"Lightning\" and player.exp >= 50:\n player.spells.append(\"Lightning\")\n player.exp = (player.exp - 50)\n elif purchase == \"Frostbite\" and player.exp >= 60:\n player.spells.append(\"Frostbite\")\n player.exp = (player.exp - 60)\n elif purchase == \"Ragnarok\" and player.exp >= 1000:\n player.spells.append(\"Ragnarok\")\n player.exp = (player.exp - 1000)\n else:\n print(\"invalid transaction\")\n print(\"\\nGold:\", player.gold)\n print(\"Exp:\", player.exp)\n print(\"Potions:\")\n for potion in player.potions:\n print(potion)\n print(\"\\nWeapons:\")\n for weapon in player.weapons:\n print(weapon)\n print(\"\\nArmor:\")\n for armors in player.armor:\n print(armors)\n print(\"\\nSpells:\")\n for spell in player.spells:\n print(spell)\n print(\"\\n\")\n\n\nold_man_info = f\"Welcome to the church of the Lord.\"\n\ndtl1_info = \"You approach this random flight of stairs that is decending downward in the earth. From it a pink and purple haze seeps out. Its light illmuminates the area around it in a magenta fog. You take your first steps into the stair well and the hatch doors swing shut.\\n\\nYou can go to:\\nLust R1.\"\n\ndungeon_lust_r1 = \"You enter a room with floors of stone. It is dimly lit with the purple haze and you reach for the wall. Upon touch your hand feels quite wet with the dampness of the walls extending to the humidity.\\n\\nYou can go to:\\nLust R2\"\n\ndungeon_lust_r2 = \"The halls now start to widen a bit futher ahead\\n\\nYou can go to:\\nLust R1\\nLust R3\"\n\ndungeon_lust_r3 = \"You get to a crossroads with three possible entrances. To the left you hear cackling. To the right: silence. Up in front, though, you feel immense power.\\nYou can go to:\\nLust R2\\nLust R4\\nLust R6\\nLust R8\"\n\ndungeon_lust_r4 = \"A room filled with mirrors and perfumes.\\nYou can go to:\\nLust R3\\nLust R5\"\n\ndungeon_lust_r5 = \"There is nothing but pillows here.\\nYou can go to:\\nLust R4\"\n\ndungeon_lust_r6 = \"There is nothing here.\\nYou can go to:\\nLust R3\\nLust R7\"\n\ndungeon_lust_r7 = \"A wild mess of a room lays before you with clothes thrown about, trash scattered everywhere, and a single mattress on the floor.\\nYou can go to:\\nLust R6\"\n\ndungeon_lust_r8 = \"A room in which you found a trusty sandwich.\\nYou can go to:\\nLust R3\\nLust R9\"\n\ndungeon_lust_r9 = \"\"\"You feel immense amount power coming from the door ahead of you.\\nYou can go to:\\nLust R8\\nLilith's Playroom\"\"\"\n\nlilith_playroom = \"A intresting room filled with lavish pillows, a decarative mirror,and other such neccesties for the Queen of Lust. You could probably live here if you wanted to due the niceness of the room.\\n\\nYou can go to:\\nLust R9\\nGluttony R1\"\n\ndungeon_glut_r1 = \"As you step down futher into the dungeon you smell rancid meat filling the lime green walls of stone.\\nYou can go to:\\nGluttony R6\\nGluttony R2\"\n\ndungeon_glut_r2 = \"A long corridor stands before you with rotten sausage links pinned to the green wall.\\nYou can go to:\\nGluttony R1\\nGluttony R3\"\n\ndungeon_glut_r3 = \"As you walk in through the hallway you come into a room with a butcher's block in the center of the room with a lot of questionable meat in boxes and on nearby tables.\\nYou can go to:\\nGluttony R2\"\n\ndungeon_glut_r4 = \"A dinning table with food lays before you. \\nYou can go to:\\nGluttony R6\\nGluttony %5\"\n\ndungeon_glut_r5 = \"In this room you found a wonderful plate of spaghett on a wonderful candle-lit table.\\nYou can go to:\\nGluttony R4\"\n\ndungeon_glut_r6 = \"A small room lays before you with the same rancid smell as the first room, but it has more of a fruity smell compared to the rest of the rooms (which have a more meaty smell). There are three doors.\\nYou can go to:\\nGluttony R1\\nGluttony R4\\nGluttony R7\"\n\ndungeon_glut_r7 = \"As you open the door up you see and swarm of flies eating lots of rotten fruit.\\nYou can go to:\\nGluttony R6\\nGluttony R8\"\n\ndungeon_glut_r8 = \"Along this hallway you spot several old paintings depicting fruit and various other foods, with yet still the smell of rancid fruit getting closer. \\nYou can go to:\\nGluttony R7\\nGluttony R10\\nGluttony R13\"\n\ndungeon_glut_r9 = \"A thanksgiving themed dining room lays before you, decorated with turkeys, pilgrims, and familes holding hands.\\nYou can go to:\\nGluttony R10\"\n\ndungeon_glut_r10 = \"You enter a long and narrow hallway. Lining the walls are rotten food of various kindsr. They range from fruit to meat and even milk? \\nYou can go to:\\nGluttony R8\\nGluttony R9\\nGluttony R11\"\n\ndungeon_glut_r11 = \"As you head down this narrow hallway you see the body of the large locust that you slayed. It is at least 8ft long in size and had glowing red eyes.. You can go to:\\nGluttony R10\"\n\ndungeon_glut_r12 = \"A chinese themed dining room lays before you\\nYou can go to:\\nGluttony R13\"\n\ndungeon_glut_r13 = \"This is the room where you found a nice and trusty fly swatter. Funnily enough, you see several flies in this room.\\nYou can go to:\\nGluttony R8\\nGluttony R12\\nGluttony R14\"\n\ndungeon_glut_r14 = \"\"\"As you proceed to the end a rather digusting and rancid smell is getting closer.\\nYou can go to:\\nGluttony R13\\nBeelzebub's Feast\"\"\"\n\nbeelzebubs_feast = \"A large dining hall fit for a king lays before you, although you don't see a delicious banquette. Instead you see corpses of past humans who have challenged the Great king of Gluttony.\"\n\n\ndef is_valid_transition(succ1: Enemies, succ2: Enemies, inc: Enemies,\n locust1: Enemies, locust2: Enemies, flies: Enemies,\n flies2: Enemies, lilith: Enemies, beelzebub: Enemies,\n player: Player, location: str, destination: str,\n item_bools: ItemPickup, dead: Death) -> bool:\n if location == \"Limbo\":\n return (destination == \"Old Town\" or destination == \"Cathedral\"\n or destination == \"Decent\")\n elif location == \"Old Town\":\n return (destination == \"Cathedral\" or destination == \"Decent\"\n or destination == \"Shop\")\n elif location == \"Shop\":\n return (destination == \"Bill\" or destination == \"Dave\"\n or destination == \"Old Town\")\n elif location == \"Dave\":\n return (destination == \"Bill\" or destination == \"Shop\")\n elif location == \"Bill\":\n return (destination == \"Dave\" or destination == \"Shop\")\n elif location == \"Old Man\":\n return destination == \"Cathedral\" or destination == \"Old Town\"\n elif location == \"Cathedral\":\n return (destination == \"Old Town\" or destination == \"Old Man\"\n or destination == \"Decent\")\n elif location == \"Decent\":\n return destination == \"Lust R1\"\n elif location == \"Lust R1\":\n return destination == \"Lust R2\"\n elif location == \"Lust R2\":\n return destination == \"Lust R3\" or destination == \"Lust R1\" or destination == \"Limbo\"\n elif location == \"Lust R3\":\n return destination == \"Lust R2\" or destination == \"Lust R4\" or destination == \"Lust R6\" or destination == \"Lust R8\"\n elif location == \"Lust R4\":\n return destination == \"Lust R5\" or destination == \"Lust R3\" or destination == \"Limbo\"\n elif location == \"Lust R5\":\n return destination == \"Lust R4\"\n elif location == \"Lust R6\":\n return destination == \"Lust R3\" or destination == \"Lust R7\"\n elif location == \"Lust R7\":\n return destination == \"Lust R6\" or destination == \"Limbo\"\n elif location == \"Lust R8\":\n return destination == \"Lust R9\" or destination == \"Lust R3\"\n elif location == \"Lust R9\":\n return destination == \"Lust R8\" or destination == \"\"\"Liliths Playroom\"\"\"\n elif location == \"\"\"Liliths Playroom\"\"\":\n return destination == \"Lust R9\" or destination == \"Gluttony R1\" or destination == \"Limbo\"\n elif location == \"Gluttony R1\":\n return destination == \"Gluttony R2\" or destination == \"Gluttony R6\"\n elif location == \"Gluttony R2\":\n return destination == \"Gluttony R1\" or destination == \"Gluttony R3\" or destination == \"Limbo\"\n elif location == \"Gluttony R3\":\n return destination == \"Gluttony R2\"\n elif location == \"Gluttony R4\":\n return destination == \"Gluttony R5\" or destination == \"Gluttony R6\" or destination == \"Limbo\"\n elif location == \"Gluttony R5\":\n return destination == \"Gluttony R4\"\n elif location == \"Gluttony R6\":\n return destination == \"Gluttony R4\" or destination == \"Gluttony R6\" or destination == \"Gluttony R7\"\n elif location == \"Gluttony R7\":\n return destination == \"Gluttony R8\" or destination == \"Gluttony R6\" or destination == \"Limbo\"\n elif location == \"Gluttony R8\":\n return destination == \"Gluttony R7\" or destination == \"Gluttony R13\" or destination == \"Gluttony R10\" or destination == \"Gluttony 7\"\n elif location == \"Gluttony R9\":\n return destination == \"Gluttony R10\"\n elif location == \"Gluttony R10\":\n return destination == \"Gluttony R11\" or destination == \"Gluttony R9\" or destination == \"Gluttony R8\"\n elif location == \"Gluttony R11\":\n return destination == \"Gluttony R10\" or destination == \"Limbo\"\n elif location == \"Gluttony R12\":\n return destination == \"Gluttony R13\"\n elif location == \"Gluttony R13\":\n return destination == \"Gluttony R14\" or destination == \"Gluttony R8\" or destination == \"Gluttony R12\"\n elif location == \"Gluttony R14\":\n return destination == \"Gluttony R13\" or destination == \"\"\"Beelzebubs Feast\"\"\" or destination == \"Limbo\"\n elif location == \"\"\"Beelsebubs Feast\"\"\":\n if destination == \"Limbo\":\n player_death(succ1, succ2, inc, locust1, locust2, flies, flies2,\n lilith, beelzebub, player, item_bools, dead)\n return destination == \"Limbo\" or destination == \"Gluttony R14\"\n return False\n\n\ndef print_info(player_name: str, location: str, player: Player, dead: Death,\n item_bools: ItemPickup, succ1: Enemies, succ2: Enemies,\n inc: Enemies, locust1: Enemies, locust2: Enemies,\n flies: Enemies, flies2: Enemies, lilith: Enemies,\n beelzebub: Enemies) -> None:\n if location == \"Limbo\":\n print(limbo_info)\n elif location == \"Old Town\":\n print(old_town_info)\n elif location == \"Cathedral\":\n print(cathedral_info)\n elif location == \"Bill\":\n print(bill_info)\n bills_shop(player)\n elif location == \"Dave\":\n print(dave_info)\n daves_shop(player)\n elif location == \"Shop\":\n print(shop_info)\n elif location == \"Old Man\":\n level_up(player)\n elif location == \"Decent\":\n print(dtl1_info)\n elif location == \"Lust R1\":\n print(dungeon_lust_r1)\n elif location == \"Lust R2\":\n if dead.succ1 == False:\n play_round(player_name, location, player, item_bools, dead, succ1)\n if player.player_health > 0:\n print(dungeon_lust_r2)\n elif location == \"Lust R3\":\n print(dungeon_lust_r3)\n elif location == \"Lust R4\":\n if dead.inc == False:\n play_round(player_name, location, player, item_bools, dead, inc)\n if player.player_health > 0:\n print(dungeon_lust_r4)\n elif location == \"Lust R5\":\n if item_bools.lr5 == False:\n item_bools.lr5 = item_pickup(player, item_bools, \"Lust R5\")\n for potion in player.potions:\n print(potion)\n print(dungeon_lust_r5)\n elif location == \"Lust R6\":\n print(dungeon_lust_r6)\n elif location == \"Lust R7\":\n if dead.succ2 == False:\n play_round(player_name, location, player, item_bools, dead, succ2)\n if player.player_health > 0:\n print(dungeon_lust_r7)\n elif location == \"Lust R8\":\n if item_bools.lr8 == False:\n item_bools.lr8 = item_pickup(player, item_bools, \"Lust R8\")\n print(dungeon_lust_r8)\n elif location == \"Lust R9\":\n print(dungeon_lust_r9)\n elif location == \"\"\"Liliths Playroom\"\"\":\n if dead.lilcounter < 1:\n play_round(player_name, location, player, item_bools, dead, lilith)\n dead.lilcounter = (dead.lilcounter + 1)\n if player.player_health > 0:\n print(lilith_playroom)\n elif location == \"Gluttony R1\":\n print(dungeon_glut_r1)\n elif location == \"Gluttony R2\":\n if dead.locust1 == False:\n play_round(player_name, location, player, item_bools, dead, flies)\n if player.player_health > 0:\n print(dungeon_glut_r2)\n elif location == \"Gluttony R3\":\n if item_bools.gr3 == False:\n item_bools.gr3 = item_pickup(player, item_bools, \"Gluttony R3\")\n print(dungeon_glut_r3)\n elif location == \"Gluttony R4\":\n if item_bools.gr4 == False:\n item_bools.gr4 = item_pickup(player, item_bools, \"Gluttony R4\")\n print(dungeon_glut_r4)\n elif location == \"Gluttony R5\":\n if item_bools.gr5 == False:\n item_bools.gr5 = item_pickup(player, item_bools, \"Gluttony R5\")\n print(dungeon_glut_r5)\n elif location == \"Gluttony R6\":\n print(dungeon_glut_r6)\n elif location == \"Gluttony R7\":\n if dead.flies == False:\n play_round(player_name, location, player, item_bools, dead, flies)\n if player.player_health > 0:\n print(dungeon_glut_r7)\n elif location == \"Gluttony R8\":\n print(dungeon_glut_r8)\n elif location == \"Gluttony R9\":\n if item_bools.gr9 == False:\n item_bools.gr9 = item_pickup(player, item_bools, \"Gluttony R9\")\n print(dungeon_glut_r9)\n elif location == \"Gluttony R10\":\n print(dungeon_glut_r10)\n elif location == \"Gluttony R11\":\n if dead.flies2 == False:\n play_round(player_name, location, player, item_bools, dead, flies2)\n if player.player_health > 0:\n print(dungeon_glut_r11)\n elif location == \"Gluttony R12\":\n if item_bools.gr12 == False:\n item_bools.gr12 = item_pickup(player, item_bools, \"Gluttony R12\")\n print(dungeon_glut_r12)\n elif location == \"Gluttony 13\":\n if item_bools.gr13 == False:\n item_bools.gr13 = item_pickup(player, item_bools, \"Gluttony R13\")\n print(dungeon_glut_r13)\n elif location == \"Gluttony R14\":\n if dead.locust2 == False:\n play_round(player_name, location, player, item_bools, dead,\n locust2)\n if player.player_health > 0:\n print(dungeon_glut_r14)\n elif location == \"\"\"Beelzebubs Feast\"\"\":\n if dead.beecounter < 1:\n play_round(player_name, location, player, item_bools, dead,\n beelzebub)\n dead.beecounter = (dead.beecounter + 1)\n if player.player_health > 0:\n print(beelzebubs_feast)\n\n\ndef input_destination_or_q(succ1: Enemies, succ2: Enemies, inc: Enemies,\n locust1: Enemies, locust2: Enemies, flies: Enemies,\n flies2: Enemies, lilith: Enemies,\n beelzebub: Enemies, player_name: str,\n player: Player, location: str, item_bools,\n dead) -> str:\n if player.player_health <= 0:\n player_death(succ1, succ2, inc, locust1, locust2, flies, flies2,\n lilith, beelzebub, player, item_bools, dead)\n restart = input(\n f\"What will {player_name} do now? Go back to limbo [Limbo] or quit[q]?\\n>\"\n )\n if restart == \"q\":\n location = \"Q\"\n elif restart == \"Limbo\":\n location = \"Limbo\"\n print(limbo_info)\n else:\n print(\"invaild input\")\n while True:\n print(f\"Where would {player_name} like to go? [q to quit]\")\n destination = input(\"> \").title()\n if destination == \"Q\" or is_valid_transition(\n succ1, succ2, inc, locust1, locust2, flies, flies2, lilith,\n beelzebub, player, location, destination, item_bools, dead):\n return destination\n else:\n print(\n f\"{player_name} cannot go to {destination.title()} from {location.title()}.\"\n )\n\n\ndef play_round(player_name: str, location: str, player: Player,\n item_bools: ItemPickup, dead: Death, enemy: Enemies) -> str:\n while enemy.health > 0 and player.player_health > 0:\n print(f\"{player_name} health:\", player.player_health)\n print(f\"{enemy.name} health:\", enemy.health)\n print(f\"{enemy.name} blocks your path!\")\n action = input(\n f\"What will {player_name} do?\\nAttack\\nMagic\\nItem\\n> \").title()\n if action == \"Attack\" or action == \"\":\n for weapon in player.weapons:\n print(weapon)\n attack1 = input(\"> \").title()\n if attack1 == \"\":\n enemy.health = (enemy.health - player.punch)\n elif attack1 == \"Legendary 24 In. Sub\":\n enemy.health = enemy.health - 1\n if attack1 == \"Iron Sword\" and \"Iron Sword\" in player.weapons:\n enemy.health = enemy.health - random.randint(10, 30)\n elif attack1 == \"Steel Sword\" and \"Steel Sword\" in player.weapons:\n enemy.health = enemy.health - random.randint(20, 40)\n elif attack1 == \"Mythril Sword\" and \"Mythril Sword\" in player.weapons:\n enemy.health = enemy.health - random.randint(30, 50)\n elif attack1 == \"Fly Swatter\" and \"Fly Swatter\" in player.weapons:\n if enemy.name == \"Hoard of Flies\" or enemy.name == \"Beelzebub\":\n enemy.health = enemy.health - random.randint(35, 55)\n else:\n enemy.health = enemy.health - random.randint(15, 25)\n else:\n print(\"Invalid attack\")\n elif action == \"Magic\":\n for spell in player.spells:\n print(spell)\n magic = input(\"> \").title()\n if magic == \"Fireball\" and player.mana >= 5 and \"Fireball\" in player.spells:\n print(f\"{player_name} cast Fireball!\")\n enemy.health = enemy.health - random.randint(20, 35)\n elif magic == \"Lightning\" and player.mana >= 10 and \"Lightning\" in player.spells:\n print(f\"{player_name} cast Lightning!\")\n enemy.health = enemy.health - random.randint(35, 45)\n elif magic == \"Frostbite\" and player.mana >= 20 and \"Frostbite\" in player.spells:\n print(f\"{player_name} cast Frostbite!\")\n enemy.health = enemy.health - random.randint(45, 55)\n elif magic == \"Ragnarok\" and player.mana >= 50 and \"Ragnarok\" in player.spells:\n print(\"You cast Ragnarok!\")\n enemy.health = enemy.health * 0\n elif magic == \"Dia\" and player.mana >= 10 and \"Dia\" in player.spells:\n print(\"You healed. + 30 HP\")\n player.player_health = (player.player_health + 30)\n if player.player_health > player.player_health_capacity:\n player.player_health = player.player_health_capacity\n else:\n print(f\"{player_name} can't cast {magic}\")\n elif action == \"Item\":\n for potion in player.potions:\n print(potion)\n use = input(\"What will you use?\").title\n if use == \"Lesser Healing Potion\":\n player.potions.remove(\"Lesser Healing Potion\")\n player.player_health = player.player_health + 25\n if player.player_health > player.player_health_capacity:\n player.player_health = player.player_health_capacity\n print(\"You healed 25 HP\")\n elif use == \"Healing Potion\":\n player.potions.remove(\"Healing Potion\")\n player.player_health = player.player_health + 55\n if player.player_health > player.player_health_capacity:\n player.player_health = player.player_health_capacity\n print(\"You healed 55 hp.\")\n elif use == \"Greater Healing Potion\":\n player.potions.remove(\"Greater Healing Potion\")\n player.player_health = player.player_health_capacity\n print(\"HP fully restored.\")\n elif use == \"Lesser Mana Potion\":\n player.potions.remove(\"Lesser Mana Potion\")\n player.mana = player.mana + 10\n if player.mana > player.mana_capacity:\n player.mana = player.mana_capacity\n print(\"You restored 10 mana.\")\n elif use == \"Mana Potion\":\n player.potions.remove(\"Mana Potion\")\n player.mana = player.mana + 30\n if player.mana > player.mana_capacity:\n player.mana = player.mana_capacity\n print(\"You restored 30 mana.\")\n elif use == \"Greater Mana Potion\":\n player.potions.remove(\"Greater Mana Potion\")\n player.mana = player.mana_capacity\n print(\"You restored all of your mana.\")\n elif use == \"Mysterious Potion\":\n chance = random.randint(0, 100)\n if chance < 1:\n player.exp = player.exp + 2000\n print(\"You gained 2000 EXP\")\n elif chance < 51:\n player.player_health_capacity = player.player_health_capacity + 30\n player.player_health = player.player_health + 30\n print(\"You gained 30 HP\")\n elif chance > 50:\n player.player_health = player.player_health - 40\n print(\"You lost 40 HP\")\n else:\n print(f\"{player_name} cant use {use} here!\")\n else:\n print(f\"{player_name} can't\", action, \"the enemy!!\")\n if enemy.health > 0:\n print(f\"{enemy.name} {enemy.attack}!\")\n player.player_health = (player.player_health - enemy.damage)\n print(f\"It deals {enemy.damage}\")\n elif enemy.health <= 0:\n print(f\"{enemy.name} has died\")\n if player.player_health <= 0:\n print(f\"{player_name} died.\")\n location = \"Limbo\"\n elif enemy.health <= 0:\n player.exp = player.exp + enemy.exp\n player.gold = player.gold + enemy.gold\n print(\"Exp:\", player.exp)\n print(\"Gold:\", player.gold)\n if enemy.name == \"Lilith\":\n player.potions.append(\"Greater Healing Potion\")\n elif enemy.name == \"Beelzebub\":\n player.exp = player.exp + 1000\n return location\n\n\ndef player_death(succ1: Enemies, succ2: Enemies, inc: Enemies,\n locust1: Enemies, locust2: Enemies, flies: Enemies,\n flies2: Enemies, lilith: Enemies, beelzebub: Enemies,\n player: Player, item_bools: ItemPickup, dead: Death) -> None:\n succ1.health = 50\n succ2.health = 60\n inc.health = 55\n locust1.health = 85\n locust2.health = 95\n flies.health = 100\n flies2.health = 300\n lilith.health = 100\n beelzebub.health = 200\n item_bools.lr5 = False\n item_bools.lr8 = False\n item_bools.gr3 = False\n item_bools.gr4 = False\n item_bools.gr5 = False\n item_bools.gr9 = False\n item_bools.gr12 = False\n item_bools.gr13 = False\n dead.succ1 = False\n dead.succ2 = False\n dead.inc = False\n dead.locust1 = False\n dead.locust2 = False\n dead.flies = False\n dead.flies2 = False\n dead.lilcounter = 0\n dead.beecounter = 0\n player.player_health = player.player_health_capacity\n\n\ndef level_up(player: Player) -> None:\n levelup = \"\"\n while levelup != \"No\":\n levelup = input(\n \"Would you like to gain the Lords knowledge? {Yes} or {No}\\n> \")\n if player.exp > 50 and levelup == \"Yes\":\n player.exp = player.exp - 50\n player.player_health_capacity = (player.player_health_capacity +\n 50)\n player.mana_capacity = (player.mana_capacity + 10)\n player.punch = (player.punch + 5)\n player.player_health = player.player_health_capacity\n print(player.player_health_capacity)\n print(player.mana_capacity)\n elif levelup == \"No\":\n print(\n \"Ok child, come again when you seek enlightment.\\nYou can go to:\\nCathedral\"\n )\n else:\n print(\"Sorry Child, come again when you have more knowledge.\")\n\n\ndef main() -> None:\n dead = Death(False, False, False, False, False, False, False, 0, 0)\n item_bools = ItemPickup(False, False, False, False, False, False, False,\n False)\n succ1 = Enemies(\"The Blonde Succubus\", 50, random.randint(15, 25),\n random.randint(25, 35), \"claws you\",\n random.randint(10, 15))\n inc = Enemies(\"The Incubus\", 55, random.randint(25, 30),\n random.randint(25, 35), \"claws you\", random.randint(10, 15))\n succ2 = Enemies(\"The Ginger Succubus\", 60, random.randint(15, 25),\n random.randint(25, 35), \"claws you\",\n random.randint(10, 15))\n locust1 = Enemies(\"The Green Locust\", 85, random.randint(35, 45),\n random.randint(45, 55), \"mauls you with its mandibles\",\n random.randint(12, 18))\n locust2 = Enemies(\"The Brown Locust\", 95, random.randint(35, 45),\n random.randint(45, 55), \"mauls you with its mandibles\",\n random.randint(20, 30))\n flies = Enemies(\"The hoard of Flies\", 100, random.randint(55, 60),\n random.randint(60, 70), \"forms a fist and punches you\",\n random.randint(14, 19))\n flies2 = Enemies(\"The Hoard of Flies\", 300, random.randint(55, 60),\n random.randint(60, 70),\n \"forms a hammer and grand-slam smashes you\",\n random.randint(14, 19))\n lilith = Enemies(\"Lilith\", 100, random.randint(100, 200),\n random.randint(200, 300), \"drains your soul\",\n random.randint(25, 30))\n beelzebub = Enemies(\n \"Beelzebub\", 200, random.randint(200, 250), random.randint(400, 600),\n \"spits stomach acid that melts your skin and smells so awful you gag\",\n random.randint(100, 150))\n player = Player(50, 50, 10, 20, [], [\"Iron Sword\"], [],\n [\"Dia\"], 10, 10, 5)\n location = \"Limbo\"\n player_name = playername()\n print(\"Welcome\", player_name)\n while True:\n\n print_info(player_name, location, player, dead, item_bools, succ1,\n succ2, inc, locust1, locust2, flies, flies2, lilith,\n beelzebub)\n destination = input_destination_or_q(succ1, succ2, inc, locust1,\n locust2, flies, flies2, lilith,\n beelzebub, player_name, player,\n location, item_bools, dead)\n if destination == \"Q\":\n break\n else:\n location = destination\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":35385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"332412521","text":"from me.att.gen1.my_attention_v3 import MyAttentionV1, MyAttentionV2, MyAttentionV3\nfrom me.att.gen2.my_attention_c1 import MyAttentionC1\nfrom me.layers import *\n\nhist_nmi = list()\n\n\ndef ppp(info):\n print(info)\n logger.info(info)\n\n\ndef is_nmi_decline(nmi):\n hist_nmi.append(nmi)\n if len(hist_nmi) <= 10:\n return False\n max_idx = np.argmax(hist_nmi)\n hist_sub = np.array(hist_nmi) - hist_nmi[max_idx]\n from_peak = hist_sub[max_idx:]\n return sum(from_peak) <= -0.6 or len(from_peak) >= 20\n\n\ndef run_gen_1(sess, model: MyAttentionV1):\n merged = tf.summary.merge_all()\n writer = tf.summary.FileWriter(log_path + '/gid={}'.format(args.gid), sess.graph)\n step_idx = 0\n \n for epoch in range(args.ep):\n print('epoch:{}'.format(epoch))\n \"\"\" train & predict \"\"\"\n for i, (p_batch, n_batches) in enumerate(sampler.shuffle_generate(args.bs, args.ns)):\n fd = model.get_fd_by_batches(p_batch, n_batches, dropout=0.7)\n model.train(sess, fd, epoch)\n if i % 100 == 0:\n ppp('b:{} L:{}'.format(i, model.get_loss(sess, fd)))\n writer.add_summary(sess.run(merged, feed_dict=fd), step_idx)\n step_idx += 1\n # if i % 20 == 0:\n # if b_idx == len(doc_batches) - 1:\n # info = 'original losses:{}\\nweighted losses:{}'.format(\n # *sess.run([model.orgn_losses, model.wght_losses], feed_dict=fd))\n # ppp(info)\n # print(' batch {} '.format(b_idx), '{:10} | '.format(round(float(loss), 6)))\n # if b_idx == 33 and print_embed:\n # # print(d_clu_likeli.shape, np.sum(d_clu_likeli, axis=1))\n # print('part of sorted weights:', np.sort(clu_weight, axis=1)[:10, :-6:-1])\n \n # if e_idx > 0 and e_idx % 4 == 0 and len(pos_batch) <= 8 and \\\n # len(doc_batches) * 0.8 <= b_idx_ < len(doc_batches) * 0.8 + 1:\n # alpha_list = sess.run(self.w_q_alpha, feed_dict=fd)\n # for idx, doc in enumerate(pos_batch):\n # tokens_list = [_ifd.id2word(tokenid) for tokenid in doc.tokenids]\n # pattern = '{:>8} ' * len(tokens_list)\n # attention_alpha = [round(float(v), 2) for v in alpha_list[idx].reshape([-1])]\n # print(pattern.format(*tokens_list))\n # print(pattern.format(*attention_alpha))\n # print()\n \"\"\" evaluate \"\"\"\n scores = model.evaluate(sampler.batches, sess)\n scores['e'] = epoch\n ppp(iu.dumps(scores))\n nmi = scores['nmi']\n if (epoch >= 5 and nmi <= 0.1) or (epoch >= 50 and nmi <= 0.3) or is_nmi_decline(nmi):\n ppp('early stop at epoch {}'.format(epoch))\n break\n # exit()\n # print('Save information')\n # topic_list = [d.topic for d in docarr]\n # w_alpha_list, c_alpha_list, doc_embed = list(), list(), list()\n # for idx, d in enumerate(docarr):\n # fd = {model.p_input_x: [d.tokenids]}\n # evals = [model.p_wq_alpha, model.d_convert, model.clu_weight]\n # wq_alpha, d_convert, clu_weight = sess.run(evals, feed_dict=fd)\n #\n # doc_embed.append(d_convert.reshape(-1))\n # w_alpha_list.append([d.tokens, wq_alpha])\n # c_alpha_list.append(clu_weight.reshape(-1))\n # word_embed, clu_embed = sess.run([model.word_embedding.get_w(), model.clu_embedding.get_w()])\n # package = [topic_list, c_alpha_list, w_alpha_list, doc_embed, word_embed, clu_embed, d_class.name]\n # np.save(args.lg + str(args.gid) + '{}.npy', np.array(package, dtype=object))\n\n\ndef build_gen_1(model_class):\n model = model_class(vocab_size, args.cn, args.ed, args.md)\n # if args.pre:\n w_embed, c_embed = d_class.load_word_cluster_embed()\n model.define_embed(w_embed, c_embed, True)\n # else:\n # print('not using pre-trained parameters')\n # w_embed, _ = d_class.load_word_cluster_embed()\n # c_embed = np.random.normal(size=(args.cn, args.ed), scale=args.sc)\n # model.w_embed = parse_variable(w_embed)\n # model.c_embed = parse_variable(c_embed)\n print('w_embed:{}, c_embed:{}'.format(w_embed.shape, c_embed.shape))\n model.define_inputs(args.ns)\n model.define_dense(args.sc)\n model.forward(args.l1, args.l2, args.l3, args.l4, args.tpk)\n model.define_optimizer(lr_kwargs)\n return model\n\n\nif __name__ == '__main__':\n from me.att.grid_search import *\n \n args = get_args()\n exclude_keys = {'pe', 'lg', 'gp', 'gi'}\n logger = lu.get_logger(log_path + entries2name(args.__dict__, exlude=exclude_keys, postfix='.txt'))\n d_class = name2object[args.dn]\n sampler = Sampler(d_class)\n vocab_size = sampler.ifd.vocabulary_size()\n lr_kwargs = dict(learning_rate=4e-3, global_step=0, decay_steps=50, decay_rate=0.95, staircase=True)\n \n gen1_class = {'v1': MyAttentionV1, 'v2': MyAttentionV2, 'c1': MyAttentionC1}\n m_class, build, run = gen1_class.get(args.vs), build_gen_1, run_gen_1\n if m_class == MyAttentionC1:\n sampler.fit_tfidf()\n m = build(m_class)\n s = get_session(args.gi, args.gp)\n run(s, m)\n","sub_path":"me/att/method_main.py","file_name":"method_main.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"324331084","text":"import numpy as np\nimport random\nfrom function import RVFL_train_val\nimport h5py\nfrom option import option as op\n\ndataset_name = \"abalone\"\n\ntemp = h5py.File(\"UCI data python\\\\\" + dataset_name + \"_R.mat\")\ndata = np.array(temp['data']).T\n\ndata = data[:, 1:]\ndataX = data[:, 0:-1]\n# do normalization for each feature\n\ndataX_mean = np.mean(dataX, axis=0)\ndataX_std = np.std(dataX, axis=0)\ndataX = (dataX - dataX_mean) / dataX_std\ndataY = data[:, -1]\ndataY = np.expand_dims(dataY, 1)\n\ntemp = h5py.File(\"UCI data python\\\\\" + dataset_name + \"_conxuntos.mat\")\nindex1 = np.array(temp['index1']).astype(np.int32) - 1\nindex2 = np.array(temp['index2']).astype(np.int32) - 1\nindex1 = np.squeeze(index1, axis=1)\nindex2 = np.squeeze(index2, axis=1)\n\ntrainX = dataX[index1, :]\ntrainY = dataY[index1, :]\ntestX = dataX[index2, :]\ntestY = dataY[index2, :]\nMAX_acc = np.zeros([4, 1])\nBest_N = np.zeros([4, 1]).astype(np.int32)\nBest_C = np.zeros([4, 1])\nBest_S = np.zeros([4, 1])\nS = np.linspace(-5, 5, 21)\n# # Look at the documentation of RVFL_train_val function file\noption1 = op()\noption2 = op()\noption3 = op()\noption4 = op()\n\nfor s in range(0, S.size):\n\n for N in range(3, 204, 20):\n\n for C in range(-5, 15):\n\n Scale = np.power(2, S[s])\n option1.N = N\n option1.C = 2 ** C\n option1.Scale = Scale\n option1.Scalemode = 3\n option1.bias = 0\n option1.link = 0\n\n option2.N = N\n option2.C = 2 ** C\n option2.Scale = Scale\n option2.Scalemode = 3\n option2.bias = 1\n option2.link = 0\n\n option3.N = N\n option3.C = 2 ** C\n option3.Scale = Scale\n option3.Scalemode = 3\n option3.bias = 0\n option3.link = 1\n\n option4.N = N\n option4.C = 2 ** C\n option4.Scale = Scale\n option4.Scalemode = 3\n option4.bias = 1\n option4.link = 1\n\n train_accuracy1, test_accuracy1 = RVFL_train_val(trainX, trainY, testX, testY, option1)\n train_accuracy2, test_accuracy2 = RVFL_train_val(trainX, trainY, testX, testY, option2)\n train_accuracy3, test_accuracy3 = RVFL_train_val(trainX, trainY, testX, testY, option3)\n train_accuracy4, test_accuracy4 = RVFL_train_val(trainX, trainY, testX, testY, option4)\n\n if test_accuracy1 > MAX_acc[\n 0]: # parameter tuning: we prefer the parameter which lead to better accuracy on the test data\n MAX_acc[0] = test_accuracy1\n Best_N[0] = N\n Best_C[0] = C\n Best_S[0] = Scale\n\n if test_accuracy2 > MAX_acc[\n 1]: # parameter tuning: we prefer the parameter which lead to better accuracy on the test data\n MAX_acc[1] = test_accuracy2\n Best_N[1] = N\n Best_C[1] = C\n Best_S[1] = Scale\n\n if test_accuracy3 > MAX_acc[\n 2]: # parameter tuning: we prefer the parameter which lead to better accuracy on the test data\n MAX_acc[2] = test_accuracy3\n Best_N[2] = N\n Best_C[2] = C\n Best_S[2] = Scale\n\n if test_accuracy4 > MAX_acc[\n 3]: # parameter tuning: we prefer the parameter which lead to better accuracy on the test data\n MAX_acc[3] = test_accuracy4\n Best_N[3] = N\n Best_C[3] = C\n Best_S[3] = Scale\n\ntemp = h5py.File(\"UCI data python\\\\\" + dataset_name + \"_conxuntos_kfold.mat\")\nindex = []\nfor i in range(8):\n index_temp = np.array([temp[element[i]][:] for element in temp['index']]).astype(np.int32) - 1\n index_temp = np.squeeze(index_temp, axis=0)\n index_temp = np.squeeze(index_temp, axis=1)\n index.append(index_temp)\n\nACC_CV = np.zeros([4, 4])\n\nfor i in range(4):\n trainX = dataX[index[2 * i], :]\n trainY = dataY[index[2 * i], :]\n testX = dataX[index[2 * i + 1], :]\n testY = dataY[index[2 * i + 1], :]\n\n option1.N = Best_N[0, 0]\n option1.C = 2 ** Best_C[0, 0]\n option1.Scale = Best_S[0, 0]\n option1.Scalemode = 3\n option1.bias = 0\n option1.link = 0\n\n option2.N = Best_N[1, 0]\n option2.C = 2 ** Best_C[1, 0]\n option2.Scale = Best_S[1, 0]\n option2.Scalemode = 3\n option2.bias = 1\n option2.link = 0\n\n option3.N = Best_N[2, 0]\n option3.C = 2 ** Best_C[2, 0]\n option3.Scale = Best_S[2, 0]\n option3.Scalemode = 3\n option3.bias = 0\n option3.link = 1\n\n option4.N = Best_N[3, 0]\n option4.C = 2 ** Best_C[3, 0]\n option4.Scale = Best_S[3, 0]\n option4.Scalemode = 3\n option4.bias = 1\n option4.link = 1\n\n train_accuracy1, ACC_CV[0, i] = RVFL_train_val(trainX, trainY, testX, testY, option1)\n train_accuracy2, ACC_CV[1, i] = RVFL_train_val(trainX, trainY, testX, testY, option2)\n train_accuracy3, ACC_CV[2, i] = RVFL_train_val(trainX, trainY, testX, testY, option3)\n train_accuracy4, ACC_CV[3, i] = RVFL_train_val(trainX, trainY, testX, testY, option4)\n\nprint(np.mean(ACC_CV, axis=0))\n","sub_path":"demo_abalone.py","file_name":"demo_abalone.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"397523893","text":"# -*- coding:utf-8 -*-\n\ntotal=1\ndef search(n):\n global total\n for i in range(n-1,0,-1):\n\n if n-i==1:\n total+=1\n\n else:\n total+=1\n search(n-i)\n return total\nprint(search(4))\n\n\n","sub_path":"personal/offer/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"204218058","text":"import requests\n\n\nurl = 'http://localhost:5000/api/search'\n# url = 'http://localhost:5000/search' # UI interface\nheaders = {'Content-Type': 'application/json'}\n\n\ndef test_empty_search():\n\n params = dict(query='', domain='[]', languages='[\"Python\"]')\n response = requests.get(url, params=params, headers=headers)\n\n print(response.status_code)\n assert response.status_code == 200\n print(response.json())\n","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"384489693","text":"\"\"\"Routine for decoding the CIFAR-10 binary file format.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport gzip\nimport re\nimport sys\nimport tarfile\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\nimport os\nfrom datetime import datetime\nimport os.path\nimport time\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\n# Process images of this size. Note that this differs from the original CIFAR\n# image size of 32 x 32. If one alters this number, then the entire model\n# architecture will change and any model would need to be retrained.\n\n\n# Global constants describing the CIFAR-10 data set.\n\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 15000\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 1000\n# Constants describing the training process.\nMOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.\nNUM_EPOCHS_PER_DECAY = 350.0 # Epochs after which learning rate decays.\nLEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\nINITIAL_LEARNING_RATE = 0.01 # Initial learning rate.\n\ndef read_cifar10(filename_queue):\n \"\"\"Reads and parses examples from CIFAR10 data files.\n\n Recommendation: if you want N-way read parallelism, call this function\n N times. This will give you N independent Readers reading different\n files & positions within those files, which will give better mixing of\n examples.\n\n Args:\n filename_queue: A queue of strings with the filenames to read from.\n\n Returns:\n An object representing a single example, with the following fields:\n height: number of rows in the result (32)\n width: number of columns in the result (32)\n depth: number of color channels in the result (3)\n key: a scalar string Tensor describing the filename & record number\n for this example.\n label: an int32 Tensor with the label in the range 0..9.\n uint8image: a [height, width, depth] uint8 Tensor with the image data\n \"\"\"\n \n\n class CIFAR10Record(object):\n pass\n result = CIFAR10Record()\n\n # Dimensions of the images in the CIFAR-10 dataset.\n # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the\n # input format.\n result.height = 256\n result.width = 320\n result.depth = 3\n with open('train.txt') as fid: \n content = fid.read() \n content = content.split('\\n') \n content = content[:-1]\n valuequeue = tf.train.string_input_producer(content,shuffle=True) \n value = valuequeue.dequeue() \n dir, label1,label2,label3,label4,label5,label6= tf.decode_csv(records=value, record_defaults=[['string'], [''],[''],[''],[''],[''],['']], field_delim=\" \") \n label1 = tf.string_to_number(label1, tf.float32)\n label2 = tf.string_to_number(label2, tf.float32)\n label3 = tf.string_to_number(label3, tf.float32)\n label4 = tf.string_to_number(label4, tf.float32)\n label5 = tf.string_to_number(label5, tf.float32)\n label6 = tf.string_to_number(label6, tf.float32)\n result.label=tf.pack([label1,label2,label3,label4,label5])\n print(dir)\n imagecontent = tf.read_file(dir) \n image = tf.image.decode_jpeg(imagecontent, channels=3) \n result.uint8image=image\n return result\n\n\ndef _generate_image_and_label_batch(image, label, min_queue_examples,\n batch_size, shuffle):\n \"\"\"Construct a queued batch of images and labels.\n\n Args:\n image: 3-D Tensor of [height, width, 3] of type.float32.\n label: 1-D Tensor of type.int32\n min_queue_examples: int32, minimum number of samples to retain\n in the queue that provides of batches of examples.\n batch_size: Number of images per batch.\n shuffle: boolean indicating whether to use a shuffling queue.\n\n Returns:\n images: Images. 4D tensor of [batch_size, height, width, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n \"\"\"\n # Create a queue that shuffles the examples, and then\n # read 'batch_size' images + labels from the example queue.\n print('generate')\n num_preprocess_threads = 8\n images=tf.placeholder(tf.float32)\n label_batch=tf.placeholder(tf.float32)\n if shuffle:\n images, label_batch = tf.train.shuffle_batch(\n [image, label],\n batch_size=64,\n num_threads=num_preprocess_threads,\n capacity=50000,\n min_after_dequeue=2800)\n else:\n images, label_batch = tf.train.batch(\n [image, label],\n batch_size=64,\n shapes=([256,320,3],[5]),\n num_threads=num_preprocess_threads,\n capacity=50000)\n # Display the training images in the visualizer.\n #tf.image_summary('images', images,max_images=64)\n print(images)\n return images, tf.reshape(label_batch, [batch_size,5])\ndef inputs():\n print('input')\n \"\"\"Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n \"\"\"\n batch_size=64\n filenames = './train.txt'\n num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN\n # Read examples from files\n read_input=tf.placeholder(tf.uint8)\n read_input = read_cifar10('train.txt')\n reshaped_image=tf.placeholder(tf.float32)\n reshaped_image = tf.cast(read_input.uint8image, tf.float32)\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(num_examples_per_epoch *\n min_fraction_of_examples_in_queue)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return _generate_image_and_label_batch(reshaped_image, read_input.label,\n min_queue_examples, 64,\n shuffle=False)\ndef _variable_on_cpu(name, shape, initializer):\n \"\"\"Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/gpu:0'):\n dtype = tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)\n return var\ndef inference(images):\n \"\"\"Build the CIFAR-10 model.\n\n Args:\n images: Images returned from distorted_inputs() or inputs().\n\n Returns:\n Logits.\n \"\"\"\n # We instantiate all variables using tf.get_variable() instead of\n # tf.Variable() in order to share variables across multiple GPU training runs.\n # If we only ran this model on a single GPU, we could simplify this function\n # by replacing all instances of tf.get_variable() with tf.Variable().\n #\n # conv1\n with tf.variable_scope('conv1') as scope:\n norm1=tf.placeholder(\"float\",shape=[None,256,320,3])\n conv1=tf.placeholder(\"float\")\n conv=tf.placeholder(\"float\")\n bias=tf.placeholder(\"float\")\n #norm1=images\n norm1 = tf.nn.lrn(images, 4, bias=255.0, alpha=0.0, beta=1.0,\n name='norm1')\n norm1=norm1-0.5\n tf.histogram_summary('norm1' + '/activations', norm1)\n kernel = tf.get_variable('weights',\n shape=[5, 5, 3, 24],\n initializer=tf.contrib.layers.xavier_initializer())\n conv = tf.nn.conv2d(norm1, kernel, [1, 2, 2, 1], padding='VALID')\n biases = _variable_on_cpu('biases', [24], tf.constant_initializer(0.1))\n weight=tf.reduce_sum(kernel)/(5*5*3*24)\n biases_ave=tf.reduce_sum(biases)/24\n bias = tf.nn.bias_add(conv, biases)\n conv1 = tf.nn.relu(bias)\n tf.scalar_summary('conv1' + '/weight', weight)\n tf.scalar_summary('conv1' + '/biases', biases_ave)\n tf.histogram_summary('conv1' + '/activations', conv1)\n tf.image_summary('conv1', images,max_images=24)\n #tf.image_summary('conv1', tf.transpose(conv1, [3, 1, 2, 0])[...,0:1],max_images=24)\n #_activation_summary(conv1)\n # conv2\n with tf.variable_scope('conv2') as scope:\n conv2=tf.placeholder(\"float\")\n conv=tf.placeholder(\"float\")\n bias=tf.placeholder(\"float\")\n kernel = tf.get_variable('weights',\n shape=[5, 5, 24, 36],\n initializer=tf.contrib.layers.xavier_initializer())\n conv = tf.nn.conv2d(conv1, kernel, [1, 2, 2, 1], padding='VALID')\n biases = _variable_on_cpu('biases', [36], tf.constant_initializer(0.1))\n weight=tf.reduce_sum(kernel)/(5*5*36*24)\n biases_ave=tf.reduce_sum(biases)/36\n bias = tf.nn.bias_add(conv, biases)\n conv2 = tf.nn.relu(bias)\n tf.scalar_summary('conv2' + '/weight', weight)\n tf.scalar_summary('conv2' + '/biases', biases_ave)\n tf.histogram_summary('conv2' + '/activations', conv2)\n tf.image_summary('conv2', tf.transpose(conv2, [3, 1, 2, 0])[...,0:1],max_images=36)\n #_activation_summary(conv2)\n # conv3\n with tf.variable_scope('conv3') as scope:\n conv3=tf.placeholder(\"float\")\n conv=tf.placeholder(\"float\")\n bias=tf.placeholder(\"float\")\n kernel = tf.get_variable('weights',\n shape=[5, 5, 36, 48],\n initializer=tf.contrib.layers.xavier_initializer())\n conv = tf.nn.conv2d(conv2, kernel, [1, 2, 2, 1], padding='VALID')\n biases = _variable_on_cpu('biases', [48], tf.constant_initializer(0.1))\n weight=tf.reduce_sum(kernel)/(5*5*36*48)\n biases_ave=tf.reduce_sum(biases)/48\n bias = tf.nn.bias_add(conv, biases)\n conv3 = tf.nn.relu(bias)\n tf.scalar_summary('conv3' + '/weight', weight)\n tf.scalar_summary('conv3' + '/biases', biases_ave)\n tf.histogram_summary('conv3' + '/activations', conv3)\n tf.image_summary('conv3', tf.transpose(conv3, [3, 1, 2, 0])[...,0:1],max_images=48)\n #_activation_summary(conv3)\n # conv4\n with tf.variable_scope('conv4') as scope:\n conv4=tf.placeholder(\"float\")\n conv=tf.placeholder(\"float\")\n bias=tf.placeholder(\"float\")\n kernel = tf.get_variable('weights',\n shape=[3, 3, 48, 64],\n initializer=tf.contrib.layers.xavier_initializer())\n conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding='VALID')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n weight=tf.reduce_sum(kernel)/(3*3*48*64)\n biases_ave=tf.reduce_sum(biases)/64\n bias = tf.nn.bias_add(conv, biases)\n conv4 = tf.nn.relu(bias)\n tf.scalar_summary('conv4' + '/weight', weight)\n tf.scalar_summary('conv4' + '/biases', biases_ave)\n tf.histogram_summary('conv4' + '/activations', conv4)\n tf.image_summary('conv4', tf.transpose(conv4, [3, 1, 2, 0])[...,0:1],max_images=64)\n #_activation_summary(conv4)\n # conv5\n with tf.variable_scope('conv5') as scope:\n conv5=tf.placeholder(\"float\")\n conv=tf.placeholder(\"float\")\n bias=tf.placeholder(\"float\")\n kernel = tf.get_variable('weights',\n shape=[3, 3, 64, 128],\n initializer=tf.contrib.layers.xavier_initializer())\n conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding='VALID')\n biases = _variable_on_cpu('biases', [128], tf.constant_initializer(0.1))\n weight=tf.reduce_sum(kernel)/(3*3*64*64)\n biases_ave=tf.reduce_sum(biases)/128\n bias = tf.nn.bias_add(conv, biases)\n conv5 = tf.nn.relu(bias)\n tf.scalar_summary('conv5' + '/weight', weight)\n tf.scalar_summary('conv5' + '/biases', biases_ave)\n tf.histogram_summary('conv5' + '/activations', conv5)\n tf.image_summary('conv5', tf.transpose(conv5, [3, 1, 2, 0])[...,0:1],max_images=64)\n # local3\n with tf.variable_scope('local3') as scope:\n # Move everything into depth so we can perform a single matrix multiply.\n local3=tf.placeholder(\"float\")\n dim=tf.placeholder(tf.int32)\n bias=tf.placeholder(\"float\")\n weights=tf.placeholder(\"float\")\n reshape = tf.reshape(conv5, [64,-1])\n dim = reshape.get_shape()[1].value\n weights = tf.get_variable('weights', shape=[dim, 500],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = _variable_on_cpu('biases', [500], tf.constant_initializer(0.1))\n #local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases,name=scope.name)\n bias = tf.matmul(reshape, weights)+biases\n local3=tf.nn.relu(bias)\n tf.scalar_summary('local3' + '/weight', tf.reduce_sum(weights)/(dim*100))\n tf.scalar_summary('local3' + '/biases', tf.reduce_sum(biases)/100)\n tf.histogram_summary('local3' + '/activations', local3)\n #_activation_summary(local3)\n\n # local4\n with tf.variable_scope('local4') as scope:\n local4=tf.placeholder(\"float\")\n weights=tf.placeholder(\"float\")\n weights = tf.get_variable('weights', shape=[500, 100],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = _variable_on_cpu('biases', [100], tf.constant_initializer(0.1))\n local4 = tf.nn.relu(tf.matmul(local3, weights) + biases)\n tf.scalar_summary('local4' + '/weight', tf.reduce_sum(weights)/(500*100))\n tf.scalar_summary('local4' + '/biases', tf.reduce_sum(biases)/100)\n tf.histogram_summary('local4' + '/activations', local4)\n #_activation_summary(local4)\n #local5\n with tf.variable_scope('local5') as scope:\n local5=tf.placeholder(\"float\")\n weights=tf.placeholder(\"float\")\n weights = tf.get_variable('weights', shape=[100, 20],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = _variable_on_cpu('biases', [20], tf.constant_initializer(0.1))\n local5 = tf.nn.relu(tf.matmul(local4, weights) + biases)\n tf.scalar_summary('local5' + '/weight', tf.reduce_sum(weights)/(20*100))\n tf.scalar_summary('local5' + '/biases', tf.reduce_sum(biases)/20)\n tf.histogram_summary('local5' + '/activations', local5)\n #_activation_summary(local5)\n with tf.variable_scope('local6') as scope:\n local6=tf.placeholder(\"float\")\n weights=tf.placeholder(\"float\")\n weights = tf.get_variable('weights', shape=[20, 5],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = _variable_on_cpu('biases', [5], tf.constant_initializer(0.1))\n local6 = tf.matmul(local5, weights) + biases\n #local6 = tf.tanh(local6)\n tf.scalar_summary('local6' + '/weight', tf.reduce_sum(weights)/(20))\n tf.scalar_summary('local6' + '/biases', tf.reduce_sum(biases))\n # tf.histogram_summary('local6' + '/activations', local6)\n #_activation_summary(local6)\n #local6=local6[...,0]\n return local6\ndef losss(logits, labels):\n \"\"\"Add L2Loss to all the trainable variables.\n\n Add summary for \"Loss\" and \"Loss/avg\".\n Args:queue\n logits: Logits from inference().\n labels: Labels from distorted_inputs or inputs(). 1-D tensor\n of shape [batch_size]\n\n Returns:\n Loss tensor of type float.\n \"\"\"\n loss=tf.placeholder(\"float\")\n loss = tf.reduce_sum(tf.pow(tf.sub(labels,logits), 2))/128\n # loss= tf.reduce_sum(tf.pow(labels-logits,2))\n # loss=tf.nn.l2_loss(labels,logits)\n tf.histogram_summary('labels' + '/activations', labels)\n tf.histogram_summary('local6' + '/activations', logits)\n tf.scalar_summary('loss', loss)\n tf.histogram_summary('local6-labels' + '/activations', tf.sub(logits,labels))\n return loss\n\ndef trainn(total_loss, global_step):\n \"\"\"Train CIFAR-10 model.\n\n Create an optimizer and apply to all trainable variables. Add moving\n average for all trainable variables.\n\n Args:\n total_loss: Total loss from loss().\n global_step: Integer Variable counting the number of training steps\n processed.\n Returns:\n train_op: op for training.\n \"\"\"\n # Variables that affect learning rate.\n num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / 64\n decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)\n\n # Decay the learning rate exponentially based on the number of steps.\n #lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE,\n # global_step,\n # decay_steps,\n # LEARNING_RATE_DECAY_FACTOR,\n # staircase=True)\n lr=0.001\n tf.scalar_summary('learning_rate', lr)\n # Generate moving averages of all losses and associated summaries.\n #loss_averages_op = tf.reduce_sum(total_loss)\n\n # Compute gradients.\n #with tf.control_dependencies([loss_averages_op]):\n opt = tf.train.GradientDescentOptimizer(lr)\n grads = opt.compute_gradients(total_loss)\n\n # Apply gradients.\n #tf.scalar_summary('grad', grads)\n #tf.histogram_summary('grads' + '/activations', grads)\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n\n '''# Add histograms for trainable variables.\n for var in tf.trainable_variables():\n tf.histogram_summary(var.op.name, var)\n\n # Add histograms for gradients.\n for grad, var in grads:\n if grad is not None:\n tf.histogram_summary(var.op.name + '/gradients', grad)\n\n # Track the moving averages of all trainable variables.\n variable_averages = tf.train.ExponentialMovingAverage(\n MOVING_AVERAGE_DECAY, global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n\n with tf.control_dependencies([apply_gradient_op, variables_averages_op]):\n train_op = tf.no_op(name='train')'''\n train_op=apply_gradient_op\n return train_op\ndef train():\n \"\"\"Train CIFAR-10 for a number of steps.\"\"\"\n with tf.Graph().as_default():\n global_step = tf.Variable(0, trainable=False)\n\n # Get images and labels for CIFAR-10.\n images=tf.placeholder(\"float\",shape=[None,256,320,3])\n labels=tf.placeholder(\"float\",shape=[None])\n local6=tf.placeholder(\"float\",shape=[None])\n images, labels = inputs()\n print('images')\n print(images)\n # Build a Graph that computes the logits predictions from the\n # inference model.\n logits = inference(images)\n\n # Calculate loss.\n loss = losss(logits, labels)\n\n # Build a Graph that trains the model with one batch of examples and\n # updates the model parameters.\n train_op = trainn(loss, global_step)\n\n # Create a saver.\n saver = tf.train.Saver(tf.all_variables())\n\n # Build the summary operation based on the TF collection of Summaries.\n summary_op = tf.merge_all_summaries()\n\n # Build an initialization operation to run below.\n init = tf.initialize_all_variables()\n\n # Start running operations on the Graph.\n tf_config=tf.ConfigProto(\n log_device_placement=False)\n tf_config.gpu_options.per_process_gpu_memory_fraction=0.9\n sess = tf.Session(config=tf_config)\n sess.run(init)\n\n # Start the queue runners.\n tf.train.start_queue_runners(sess=sess)\n\n summary_writer = tf.train.SummaryWriter('/home/fzyue/Desktop/caffeendtoend/1', sess.graph)\n\n for step in xrange(100000):\n start_time = time.time()\n _, loss_value = sess.run([train_op, loss])\n duration = time.time() - start_time\n\n assert not np.isnan(loss_value), 'Model diverged with loss = NaN'\n\n if step % 10 == 0:\n num_examples_per_step = 64\n examples_per_sec = num_examples_per_step / duration\n sec_per_batch = float(duration)\n\n format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '\n 'sec/batch)')\n print (format_str % (datetime.now(), step, loss_value,\n examples_per_sec, sec_per_batch))\n #print(labels)\n #print (sess.run(logits))\n\n if step % 100 == 0:\n summary_str = sess.run(summary_op)\n summary_writer.add_summary(summary_str, step)\n\n # Save the model checkpoint periodically.\n if step % 1000 == 0 or (step + 1) == 100000:\n checkpoint_path = os.path.join('/home/fzyue/Desktop/caffeendtoend/1', 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n #cifar10.maybe_download_and_extract()\n if tf.gfile.Exists('/home/fzyue/Desktop/caffeendtoend/1'):\n tf.gfile.DeleteRecursively('/home/fzyue/Desktop/caffeendtoend/1')\n tf.gfile.MakeDirs('/home/fzyue/Desktop/caffeendtoend/1')\n train()\nmain()\n","sub_path":"tensor_flow.py","file_name":"tensor_flow.py","file_ext":"py","file_size_in_byte":20308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"433663421","text":"import io, sys, json\nimport socket\nimport struct\nimport time\n#import picamera\n\n#------------------------------------------\n#setting up variables/constants/values/...\nmy_ip = '0.0.0.0'\nmy_port = 18768\n\n#folder = '/home/pi/coding/'\njson_file = 'rpicam.json'\n\ncam_mode = ('stil', 'video')\ncam_res_maxval = {2592: 1944, 1920: 1080}\ncam_shtr_spd_maxval = 6000000\ncam_iso_val = (0, 100, 200, 320, 400, 500, 640, 800)\ncam_exp_mode_val = ('off', 'auto', 'night', 'nightpreview',\n'backlight','spotlight', 'sports', 'snow', 'beach', 'verylong',\n'fixedfps', 'antishake', 'fireworks')\nexit_val = ('yes', 'no')\naction_val = ('preview', 'mo_detect', 'timelapse')\n\nstream = io.BytesIO()\ndonotexit = True\n#-------------------------------------------\n\n#------------------------------------------\n#Functions definitions start here\ndef settingup_values():\n #try:\n camopt = open(json_file, 'r')\n cam_opt = json.load(camopt)\n #print(cam_opt)\n camopt.close()\n #except:\n # print('Setting up standard values')\n # cam_opt = {\n # 'action': 'pic',\n # 'cam_res': (1296, 730),\n # 'cam_shtr_spd': 0,\n # 'cam_iso': 0,\n # 'cam_exp_mode': 'auto',\n # 'exit': 'no'}\n return cam_opt\n\ndef settingstofile(settings):\n filehnd = open(json_file, 'w')\n json.dump(settings, filehnd)\n filehnd.close()\n return\n\ndef checking_cmdstr(cmdstr):\n res = None\n if cmdstr == None or cmdstr == '':\n print('CMDSTR could not be received')\n return 'failed'\n else:\n cmdstr = str(cmdstr).split(',')\n for cmd in cmdstr:\n cmd = cmd.split(':')\n if len(cmd) > 1:\n cmd0 = cmd[0].strip()[1:-1]\n cmd1 = cmd[1].strip()\n if cmd1.startswith('\"'):\n cmd1 = cmd1[1:-1]\n else:\n print('Wrong data', cmd)\n continue\n if cmd0 in cam_opt:\n if cmd0 == 'cam_res':\n try:\n cmd1 = cmd1.split('x')\n width = int(cmd1[0].strip())\n height = int(cmd1[1].strip())\n if width <= 1920:\n if height <= 1080:\n #print(cmd0, 'before:', cam_opt['cam_res'])\n cam_opt[cmd0] = (width, height)\n #print(cmd0, 'after:', cam_opt['cam_res'])\n elif width <= 2592:\n if height <= 1944:\n #print(cmd0, 'before:', cam_opt['cam_res'])\n cam_opt[cmd0] = (width, height)\n #print(cmd0, 'after:', cam_opt['cam_res'])\n except:\n print('Changing resolution failed')\n break\n elif cmd0 == 'cam_shtr_spd':\n try:\n cmd1 = int(cmd1)\n if cmd1 < cam_shtr_spd_maxval:\n #print(cmd0, 'before:', cam_opt['cam_shtr_spd'])\n cam_opt[cmd0] = cmd1\n #print(cmd0, 'after:', cam_opt['cam_shtr_spd'])\n except:\n pass\n elif cmd0 == 'cam_iso':\n try:\n cmd1 = int(cmd1)\n if cmd1 in cam_iso_val:\n #print(cmd0, 'before:', cam_opt['cam_iso'])\n cam_opt[cmd0] = cmd1\n #print(cmd0, 'after:', cam_opt['cam_iso'])\n except:\n #pass\n print('CAM_ISO cmd1:', cmd1)\n elif cmd0 == 'cam_exp_mode':\n if cmd1 in cam_exp_mode_val:\n #print(cmd0, 'before:', cam_opt['cam_exp_mode'])\n cam_opt[cmd0] = cmd1\n #print(cmd0, 'after:', cam_opt['cam_exp_mode'])\n elif cmd0 == 'exit':\n if cmd1 in exit_val:\n cam_opt['exit'] = cmd1\n elif cmd0 == 'action':\n if cmd1 in action_val:\n res = cmd1\n else:\n pass\n return res\n\n#camera = picamera.PiCamera()\n#camera.led = False\ncam_opt = settingup_values()\n\n#------------------------------------\n#Starting sockets\nserver_socket = socket.socket()\ntry:\n server_socket.bind((my_ip, my_port))\nexcept:\n print('Address:', my_ip, 'already in use!')\n sys.exit()\nserver_socket.listen(0)\nprint('Server is now running')\n#Sockets are running now\n#------------------------------------\n\n#-------------------------------------\n#Main loop\nwhile donotexit:\n conn, clnaddr = server_socket.accept()\n print('Connection accepted!')\n camera.start_preview()\n while True:\n cmdlen = conn.recv(4)\n cmd_len = struct.unpack(''\n\n with open(file_path, 'wb') as handle:\n response = requests.get(des_url, stream=True)\n for block in response.iter_content(2048):\n handle.write(block)\n des_text.append(full_path)\n i = int(i) + 1\n item['description'] = ''.join(des_text)\n item['gallery'] = '||'.join(gallery_images)\n return item\n","sub_path":"Product_kaola/kaola_images/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"348965526","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018 IBM.\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\nfrom qiskit_aqua_ui import BaseController\nfrom ._model import Model\nfrom qiskit_aqua_ui import (EntryPopup, ComboboxPopup, TextPopup)\nimport tkinter as tk\nfrom tkinter import messagebox\nimport json\nimport ast\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Controller(BaseController):\n\n def __init__(self, guiprovider):\n super().__init__(guiprovider, Model())\n\n def on_section_select(self, section_name):\n self._sectionsView.show_remove_button(True)\n self._sectionView_title.set(section_name)\n if self.model.section_is_text(section_name):\n self._textView.populate(self.model.get_section_text(section_name))\n self._textView.section_name = section_name\n self._textView.show_add_button(False)\n self._textView.show_remove_button(False)\n self._textView.show_defaults_button(not self.model.default_properties_equals_properties(section_name))\n self._textView.tkraise()\n else:\n self._propertiesView.show_add_button(self.shows_add_button(section_name))\n self._propertiesView.populate(self.model.get_section_properties_with_substitution(section_name))\n self._propertiesView.section_name = section_name\n self._propertiesView.show_remove_button(False)\n self._propertiesView.show_defaults_button(not self.model.default_properties_equals_properties(section_name))\n self._propertiesView.tkraise()\n\n def on_section_defaults(self, section_name):\n from qiskit.chemistry.parser import InputParser\n try:\n self.model.set_default_properties_for_name(section_name)\n if section_name == InputParser.DRIVER:\n section_names = self.model.get_section_names()\n self._sectionsView.populate(section_names)\n missing = self.get_sections_names_missing()\n self._sectionsView.show_add_button(True if missing else False)\n\n self.on_section_select(section_name)\n return True\n except Exception as e:\n messagebox.showerror(\"Error\", str(e))\n\n return False\n\n def on_property_set(self, section_name, property_name, value):\n from qiskit.aqua.parser import JSONSchema\n try:\n self.model.set_section_property(section_name, property_name, value)\n except Exception as e:\n messagebox.showerror(\"Error\", str(e))\n return False\n\n try:\n self._propertiesView.populate(self.model.get_section_properties_with_substitution(section_name))\n self._propertiesView.show_add_button(self.shows_add_button(section_name))\n _show_remove = property_name != JSONSchema.PROVIDER and property_name != JSONSchema.NAME \\\n if section_name == JSONSchema.BACKEND else property_name != JSONSchema.NAME\n self._propertiesView.show_remove_button(_show_remove and self._propertiesView.has_selection())\n self._propertiesView.show_defaults_button(not self.model.default_properties_equals_properties(section_name))\n section_names = self.model.get_section_names()\n self._sectionsView.populate(section_names, section_name)\n missing = self.get_sections_names_missing()\n self._sectionsView.show_add_button(True if missing else False)\n return True\n except Exception as e:\n messagebox.showerror(\"Error\", str(e))\n\n return False\n\n def on_section_property_remove(self, section_name, property_name):\n try:\n self.model.delete_section_property(section_name, property_name)\n self._propertiesView.populate(self.model.get_section_properties_with_substitution(section_name))\n self._propertiesView.show_add_button(self.shows_add_button(section_name))\n self._propertiesView.show_remove_button(False)\n self._propertiesView.show_defaults_button(not self.model.default_properties_equals_properties(section_name))\n except Exception as e:\n self._outputView.write_line(str(e))\n\n def create_popup(self, section_name, property_name, parent, value):\n from qiskit.chemistry.parser import InputParser\n from qiskit.aqua.parser import JSONSchema\n from qiskit.chemistry.drivers import local_drivers\n values = None\n types = ['string']\n combobox_state = 'readonly'\n if InputParser.OPERATOR == section_name and JSONSchema.NAME == property_name:\n values = self.model.get_operator_section_names()\n elif InputParser.DRIVER == section_name and JSONSchema.NAME == property_name:\n values = local_drivers()\n elif JSONSchema.NAME == property_name and Model.is_pluggable_section(section_name):\n values = self.model.get_pluggable_section_names(section_name)\n elif JSONSchema.BACKEND == section_name and \\\n (JSONSchema.NAME == property_name or JSONSchema.PROVIDER == property_name):\n values = []\n if JSONSchema.PROVIDER == property_name:\n combobox_state = 'normal'\n for provider, _ in self.model.providers.items():\n values.append(provider)\n else:\n provider_name = self.model.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER)\n values = self.model.providers.get(provider_name, [])\n else:\n values = self.model.get_property_default_values(section_name, property_name)\n types = self.model.get_property_types(section_name, property_name)\n\n if values is not None:\n value = '' if value is None else str(value)\n values = [str(v) for v in values]\n widget = ComboboxPopup(self, section_name,\n property_name,\n parent,\n exportselection=0,\n state=combobox_state,\n values=values)\n widget._text = value\n if len(values) > 0:\n if value in values:\n widget.current(values.index(value))\n else:\n widget.current(0)\n\n return widget\n\n value = '' if value is None else value\n if 'number' in types or 'integer' in types:\n vcmd = self._validate_integer_command if 'integer' in types else self._validate_float_command\n vcmd = (vcmd, '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\n widget = EntryPopup(self,\n section_name,\n property_name,\n parent,\n value,\n validate='all',\n validatecommand=vcmd,\n state=tk.NORMAL)\n widget.selectAll()\n return widget\n\n if 'object' in types or 'array' in types:\n try:\n if isinstance(value, str):\n value = value.strip()\n if len(value) > 0:\n value = ast.literal_eval(value)\n\n if isinstance(value, dict) or isinstance(value, list):\n value = json.dumps(value, sort_keys=True, indent=4)\n except:\n pass\n\n widget = TextPopup(self,\n section_name,\n property_name,\n parent,\n value)\n widget.selectAll()\n return widget\n","sub_path":"qiskit_chemistry_ui/_controller.py","file_name":"_controller.py","file_ext":"py","file_size_in_byte":8329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"52533327","text":"# -*-coding:UTF-8 -*\n\n\"\"\"Latex module\nFlorian ABRIBAT\nDep'info - Mines Nancy 2013/2014\nflorian.abribat@depinfonancy.fr\"\"\"\n\nimport os\nfrom Drawing import Drawing\nimport SlideShow\n\n\nfrom BoundingBox import BoundingBox\n\n\ndef useStyle(svgCode, s):\n \"\"\"Changes the svg block header in order to include a style\"\"\"\n heightPos = svgCode.find(\"height\")\n svgCode = svgCode.replace(svgCode[heightPos:heightPos + 18], \"\", 1) #finds default \"height\" and deletes it\n widthPos = svgCode.find(\"width\")\n svgCode = svgCode.replace(svgCode[widthPos:widthPos + 18], \"\", 1) #finds default \"width\" and deletes it\n\n svgBlockPos = svgCode.find(\"= 0):\n indexID = svgCode.find(\"id='g\", indexID + 4, len(svgCode)) #next path id is found\n Latex.idCounter += 1\n\n #The length of the id is determined by searching the next ' in the substring svgCode[indexID+4:]\n s = svgCode[indexID + 4:]\n idLength = 0\n while (s[0] != \"\\'\" and indexID != -1):\n idLength += 1\n s = svgCode[indexID + 4 + idLength:]\n\n idString = svgCode[indexID + 4:indexID + 4 + idLength] #the old id to be replaced\n\n #we now count the occurrences of the old id in the svg block (2 paths may have the same id) in order to know how many times we will replace this id\n idOccurrences = 0\n currentIDIndex = 0\n while (currentIDIndex >= 0 and indexID >= 0):\n currentIDIndex = svgCode.find(idString, currentIDIndex + len(idString), len(svgCode))\n idOccurrences += 1\n\n if indexID >= 0:\n #indexID may be equal to -1 if the last id was reached in the last loop hence we control it in order not to change the beginning of the svg code\n svgCode = svgCode.replace(idString, \"p\" + str(Latex.idCounter),\n idOccurrences - 1) #the old id is replaced by the new one in all the svg block\n\n return svgCode\n\n\nclass Latex(Drawing):\n \"\"\"missing documentation\"\"\"\n \n idCounter = 0 #global variable that numbers the path id in function idChanges\n LaTeXCounter = 0 #global variable that counts numbers the LaTeX blocs generated (used in log file)\n\n def __init__(self, codeTeX, macros=list(), packages=list(), x=\"0px\", y=\"0px\", scale=None, width=None, height=None):\n \"\"\"Users enter the content of the document (which may be placed between begin{document} and end{document}) and optional personal macros and packages to be loaded.\n Macros files should be given with its extension and placed in the same directory as the source code for the presentation\n Width and height parameters must be given in pixels and scale in decimal value (in stead of \"50%\", give \"0.5\")\n This constructor creates the complete LaTeX code to be compiled in a temporary .tex file.\n module DVISVGM must be in the same directory as this python file\"\"\"\n\n self.listOfMacros = macros\n \"\"\"missing documentation\"\"\"\n\n packagesCode = \"\" #all the \"\\usepackage{...}\" commands to be included in the header\n for p in packages:\n packagesCode += \"\\\\usepackage{\" + p + \"}\"\n\n \"\"\"LaTeX code to be compiled (without macros) begins with a \\documentclass{article} followed by the list of packages.\n pagestyle must be empty in order to avoid page numbers at the bottom\"\"\"\n self.code = \"\\documentclass{article}\" + packagesCode + \"\\pagestyle{empty} \\\\begin{document}\" + codeTeX + \"\\end{document}\"\n\n self.scale = scale\n \"\"\"missing documentation\"\"\"\n self.w = width\n \"\"\"missing documentation\"\"\"\n self.h = height\n \"\"\"missing documentation\"\"\"\n\n\n self.bBox = BoundingBox(x=x,y=y,width=width,height=height)\n\n\n def toHtml(self):\n\n \"\"\"adds macros code to TeX code entered by user and converts it into SVG using LaTeX compiler installed on user's computer and dvisvgm package also installed on user's computer\"\"\"\n if (\n Latex.LaTeXCounter == 0): #if this is the 1st LaTeX occurence in the presentation we print a message to inform about log file\n print(\"In LaTeX module: see latex.log in the slideshow directory for output informations\")\n\n macrosCode = \"\" #code in macros files to be included in the LaTeX code to be compiled (by default, the list of macros is empty)\n for m in self.listOfMacros:\n try:\n mFile = open(\"../\" + m, 'r')\n mCode = mFile.read()\n mFile.close()\n macrosCode += mCode #for each macro entered, its code is included\n except FileNotFoundError: #if macro file is not found we print an error\n print(\"[LaTeX ERROR] Macro file \" + m + \" not found\")\n\n self.code = self.code[:23] + macrosCode + self.code[23:]\n\n svgCode = \"[LaTeX ERROR] Unrecognized Operating System\"\n if (os.name == \"posix\"):\n \"\"\"Case of a UNIX based OS (Linux, OSX, etc.)\"\"\"\n #1st, we write TeX code in a temporary tex file\n texFile = open(\"temp.tex\", 'w')\n texFile.write(self.code)\n texFile.close()\n\n #a log file is created (it will contain all LaTeX messages that were printed in shell)\n if (Latex.LaTeXCounter == 0):\n log = open(\"./latex.log\", 'w')\n else:\n log = open(\"./latex.log\", 'a')\n\n log.write(\n \"[LATEX BLOCK \" + str(Latex.LaTeXCounter) + \"]\\n\") #identification of the LaTeX block in the log file\n log.close()\n Latex.LaTeXCounter += 1\n\n #then the temporary tex file is compiled and produces a temporary dvi file\n #the shell messages are not printed in the shell but writen at the end of the log file\n os.system(\"latex --interaction=nonstopmode temp.tex>>./latex.log\")\n\n try: #we try to open temp.dvi in order to see if LaTeX compilation went well and created it\n dvi = open(\"temp.dvi\", 'r')\n dvi.close()\n except FileNotFoundError:\n print(\"[LaTeX ERROR] compilation error: no DVI file produced, see latex.log for more informations\")\n\n #dvisvgm creates a svg file from dvi file\n try:\n os.system(\"dvisvgm -n --verbosity=1 temp.dvi\")\n except IOError:\n print(\"[LaTeX ERROR] DVI to SVG package 'dvisvgm' converter not found! Install dvisvgm and try again\")\n\n #the content of the svg file is copied into \"svgCode\"\n try:\n svgFile = open(\"temp.svg\", 'r')\n\n svgCode = svgFile.read()\n\n svgFile.close()\n except FileNotFoundError:\n print(\"[LaTeX ERROR] DVI to SVG package 'dvisvgm' converter not found! Install dvisvgm and try again\")\n\n svgCode = idChanges(\n svgCode) #the paths id are changed in order to avoid getting the same id for 2 different paths (infinity bug)\n\n svgCode = useStyle(svgCode, self.bBox) #includes the style entered by user in svg block\n svgCode = resize(svgCode, widthUser=self.w, heightUser=self.h,\n scaleUser=self.scale) #sets the margins in order not to cut the head of characters\n\n #then we clean up all temporary files (tex, dvi, svg, aux, log)\n os.system(\"rm temp.*\")\n\n elif (os.name == \"nt\"):\n \"\"\"Case of a DOS based OS (MS Windows)\"\"\"\n #1st, we write TeX code in a temporary tex file\n texFile = open(\"temp.tex\", 'w')\n texFile.write(self.code)\n texFile.close()\n\n #a log file is created (it will contain all LaTeX messages that were printed in shell)\n if (Latex.LaTeXCounter == 0):\n log = open(\"./latex.log\", 'w')\n else:\n log = open(\"./latex.log\", 'a')\n\n log.write(\n \"[LATEX BLOCK \" + str(Latex.LaTeXCounter) + \"]\\n\") #identification of the LaTeX block in the log file\n log.close()\n Latex.LaTeXCounter += 1\n\n #then the temporary tex file is compiled and produces a temporary dvi file\n #the shell messages are not printed in the shell but writen at the end of the log file\n os.system(\"latex --interaction=nonstopmode temp.tex>>./latex.log\")\n\n try: #we try to open temp.dvi in order to see if LaTeX compilation went well and created it\n dvi = open(\"temp.dvi\", 'r')\n dvi.close()\n except FileNotFoundError:\n print(\"[LaTeX ERROR] compilation error: no DVI file produced, see latex.log for more informations\")\n\n #dvisvgm creates a svg file from dvi file\n try:\n latexClassPath = os.path.abspath(__file__)\n latexFileName = os.path.basename(__file__)\n dvisvgmExePath = latexClassPath[0:len(latexClassPath) - len(latexFileName)]\n os.system(dvisvgmExePath + \"dvisvgm.exe -n --verbosity=1 temp.dvi\")\n except IOError:\n print(\"[LaTeX ERROR] DVI to SVG package 'dvisvgm' converter not found! Install dvisvgm and try again\")\n\n #the content of the svg file is copied into \"svgCode\"\n try:\n svgFile = open(\"temp.svg\", 'r')\n\n svgCode = svgFile.read()\n\n svgFile.close()\n except FileNotFoundError:\n print(\"[LaTeX ERROR] DVI to SVG package 'dvisvgm' converter not found! Install dvisvgm and try again\")\n\n svgCode = idChanges(\n svgCode) #the paths id are changed in order to avoid getting the same id for 2 different paths (infinity bug)\n\n svgCode = useStyle(svgCode, self.bBox) #includes the style entered by user in svg block\n svgCode = resize(svgCode, widthUser=self.w, heightUser=self.h,\n scaleUser=self.scale) #sets the margins in order not to cut the head of characters\n\n #then we clean up all temporary files (tex, dvi, svg, aux, log)\n os.system(\"DEL temp.*\")\n\n if svgCode == \"[LaTeX ERROR] Unrecognized Operating System\":\n print(svgCode)\n\n return svgCode\n\n\n\"\"\"Here is an example whitch prints the result of a very well known Riemann series result using packages amsmath to print the sum symbol, mathpazo to use an original font, amsfonts to print natural integere set symbol and myFonderfulStyle as a style for final svg block.\nt = Latex(r\"\\[ \\sum_{n\\in \\mathbb{N}^*} \\cfrac{1}{n^2} = \\cfrac{\\pi^2}{6} \\]\", macros=[\"macroTest.tex\"], packages=[\"amsmath\", \"amsfonts\", \"mathpazo\"], x=\"10px\", y=\"50px\", scale = 3.14159265359)\nt.toHtml()\"\"\"\n","sub_path":"Python/SINP/trunk/Release/Latex.py","file_name":"Latex.py","file_ext":"py","file_size_in_byte":13493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"629936349","text":"\"\"\"ssh2net.core.cisco_iosxe.driver\"\"\"\nimport re\nfrom typing import Any, Dict\n\nfrom ssh2net.core.driver import BaseNetworkDriver, PrivilegeLevel\n\n\nIOSXE_ARG_MAPPER = {\n \"comms_prompt_regex\": r\"^[a-z0-9.\\-@()/:]{1,32}[#>$]$\",\n \"comms_return_char\": \"\\n\",\n \"comms_pre_login_handler\": \"\",\n \"comms_disable_paging\": \"terminal length 0\",\n}\n\nPRIVS = {\n \"exec\": (\n PrivilegeLevel(\n re.compile(r\"^[a-z0-9.\\-@()/:]{1,32}>$\", flags=re.M | re.I),\n \"exec\",\n None,\n None,\n \"privilege_exec\",\n \"enable\",\n True,\n \"Password:\",\n True,\n 0,\n )\n ),\n \"privilege_exec\": (\n PrivilegeLevel(\n re.compile(r\"^[a-z0-9.\\-@/:]{1,32}#$\", flags=re.M | re.I),\n \"privilege_exec\",\n \"exec\",\n \"disable\",\n \"configuration\",\n \"configure terminal\",\n False,\n False,\n True,\n 1,\n )\n ),\n \"configuration\": (\n PrivilegeLevel(\n re.compile(r\"^[a-z0-9.\\-@/:]{1,32}\\(config\\)#$\", flags=re.M | re.I),\n \"configuration\",\n \"priv\",\n \"end\",\n None,\n None,\n False,\n False,\n True,\n 2,\n )\n ),\n \"special_configuration\": (\n PrivilegeLevel(\n re.compile(r\"^[a-z0-9.\\-@/:]{1,32}\\(config[a-z0-9.\\-@/:]{1,16}\\)#$\", flags=re.M | re.I),\n \"special_configuration\",\n \"priv\",\n \"end\",\n None,\n None,\n False,\n False,\n False,\n 3,\n )\n ),\n}\n\n\nclass IOSXEDriver(BaseNetworkDriver):\n def __init__(self, **kwargs: Dict[str, Any]):\n \"\"\"\n Initialize SSH2Net IOSXEDriver Object\n\n Args:\n **kwargs: keyword args to pass to inherited class(es)\n\n Returns:\n N/A # noqa\n\n Raises:\n N/A # noqa\n \"\"\"\n super().__init__(**kwargs)\n self.privs = PRIVS\n self.default_desired_priv = \"privilege_exec\"\n self.textfsm_platform = \"cisco_ios\"\n","sub_path":"ssh2net/core/cisco_iosxe/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"217448278","text":"\"\"\"\nProof of concept parser to enter each webpage and check for a specific word\n\"\"\"\nimport requests\nimport re\nimport csv\nimport sys\nfrom bs4 import BeautifulSoup\n\nsource_url = \"https://deliveroo.co.uk/sitemap\"\n\n########## Functions for crawling, scraping, parsing ############\ndef restaurant_finder(location):\n \"\"\" Function to find each restaurant link on the main sitemap page \"\"\"\n href_links = []\n \n # use request to retrieve html source code, then BeautifulSoup to parse\n source_code = requests.get(source_url).text\n soup = BeautifulSoup(source_code, 'html.parser')\n \n # restaurants are stored in blocks and include 'menu' string in href\n search_string = 'menu/' + location\n for a in soup.findAll('a'):\n if search_string in a['href']:\n href_links.append(a)\n # if you want to search more locations than just one, repeat the\n # following block of code with the location string you want\n# elif 'menu/london/bexleyheath' in a['href']:\n# href_links.append(a)\n\n # print statements here are just to show the retrieved urls look right\n# print(\"href_links are: \")\n# print(href_links[0:6])\n# print(\"\") \n\n return href_links\n\ndef restaurant_checker(word, href_links):\n \"\"\" Function to check if the word is in each restaurant's page \"\"\"\n # create a dictionary to contain the restaurant and boolean\n restaurant_data = []\n \n # loop over the list of restaurant pages\n for link in href_links[0:10]: # change/remove indices to parse more restaurants\n # need to convert and extract info from links\n restaurant_dictionary = {'Name' : [], 'Sale' : [], 'URL' : [], 'Location' : []}\n restaurant_url = str(link['href'])\n restaurant_name = str(link.string)\n # use regex pattern to get locations out of href string \n res_pattern = \"menu/london/(.*?)/\" # change the pattern if not london based\n restaurant_location = re.search(res_pattern, restaurant_url).group(1)\n\n # parse each restaurants individual url\n total_url = \"https://deliveroo.co.uk\" + restaurant_url\n # use request to retrieve html source code, then BeautifulSoup to parse\n restaurant_source_code = requests.get(total_url).text\n soup2 = BeautifulSoup(restaurant_source_code, 'html.parser')\n # we want the text from the restaurant's page\n restaurant_text = soup2.get_text()\n print(\"Text found for \" + restaurant_name)\n \n # check if the text of the restaurant's page contains the word we want\n page_check = text_checker(word, restaurant_text) \n # add the restaurant name and boolean to the dictionary\n restaurant_dictionary['Name'] = restaurant_name\n restaurant_dictionary['Sale'] = page_check\n restaurant_dictionary['URL'] = total_url\n restaurant_dictionary['Location'] = restaurant_location\n restaurant_data.append(restaurant_dictionary)\n\n return restaurant_data\n\ndef text_checker(word, text):\n \"\"\" Function to check for a specific word in the text \"\"\"\n # using regex to find if the word is in the text, do not care about case\n word_list = re.findall(word, text, flags=re.IGNORECASE)\n if len(word_list) >= 1:\n result = True\n else:\n result = False\n return result\n\n################# CSV Stuff ############################\n\ndef csv_generator(restaurant_data, csv_name):\n csv_columns = ['Name', 'Sale', 'URL', 'Location']\n csv_file = csv_name\n try:\n with open(csv_file, 'w', newline='') as csvfile:\n res_writer = csv.DictWriter(csvfile, fieldnames=csv_columns)\n res_writer.writeheader()\n for data in restaurant_data:\n res_writer.writerow(data)\n print(\"\\nCSV successfully written to \" + csv_file)\n except IOError:\n print(\"I/O error occurred while writing csv\")\n\n############### Run Management #####################\n\ndef io_printer(test_word, location_choice, csv_name):\n \"\"\" Function to neatly print io statements \"\"\"\n print(\"Searching for \\\"\" + test_word + \"\\\"...\")\n print(\"Searching in \\\"\" + location_choice + \"\\\"...\")\n print(\"Output will be stored in \" + csv_name + \"...\\n\")\n return\n\n\n\ndef main():\n \n # IO Stuff\n # default values for test_word and csv_name\n test_word = \"T&Cs apply\"\n location_choice = \"london/bexleyheath\"\n csv_name = \"restaurant_test.csv\"\n\n\n if len(sys.argv) == 1:\n print(\"Default option selected...\")\n io_printer(test_word, location_choice, csv_name)\n elif len(sys.argv) == 2:\n try:\n location_choice = str(sys.argv[1])\n print(\"Custom option selected...\")\n io_printer(test_word, location_choice, csv_name)\n except:\n print(\"Something was wrong with your input, proceeding with default...\")\n print(\"Default option selected...\")\n io_printer(test_word, location_choice, csv_name) \n elif len(sys.argv) == 3:\n try:\n location_choice = str(sys.argv[1])\n csv_name = str(sys.argv[2]) + \".csv\"\n io_printer(test_word, location_choice, csv_name)\n except:\n print(\"Something was wrong with your input, proceeding with default\")\n print(\"Default option selected...\")\n io_printer(test_word, location_choice, csv_name)\n else:\n print(\"Something is wrong with your input, proceeding with default\")\n print(\"Default option selected...\")\n io_printer(test_word, location_choice, csv_name)\n\n # Running the Functions\n restaurant_html = restaurant_finder(location_choice)\n restaurant_data = restaurant_checker(test_word, restaurant_html)\n csv_generator(restaurant_data, csv_name)\n \n # loop over resulting dictionary and print values to check output\n# print(\"\\nResults of search for \" + test_word.lower() + \": \")\n# for item in restaurant_data:\n# print(item)\n\n\nmain()\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"532747596","text":"from django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nimport json\nimport joblib\n\nmodel = joblib.load(\"disaster/static/classifier.pkl\")\n\n\nclass ReactView(APIView):\n\n # serializer_class = ReactSerializer\n\n def get(self, request):\n # detail = [ {\"name\": detail.name,\"detail\": detail.detail}\n # for detail in React.objects.all()]\n data = request.data\n print(data)\n res = {\n \"data\": data,\n \"out\": \"\"\n }\n return Response(json.loads(json.dumps(res)))\n\n def post(self, request):\n data = request.data\n query = data['detail']\n classification_labels = model.predict([query])[0]\n # classification_results = dict(zip(df.columns[4:], classification_labels))\n res = {\"out_post\": \"done\", \"data\": classification_labels.tolist()}\n res = json.dumps(res)\n res = json.loads(res)\n return Response(res)\n","sub_path":"disaster/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"123723017","text":"from math import *\nfrom proteus.ctransportCoefficients import smoothedHeaviside\nfrom proteus import Domain\nfrom proteus import TransportCoefficients\nfrom proteus.TransportCoefficients import TwophaseNavierStokes_ST_LS_SO\nfrom proteus import LinearAlgebraTools\nfrom proteus import MeshTools\nimport beach_erosion_board_3dDomain\n#numerics options\nuseVANS2P=True\nuseNCLS =True\nuseVOF =True\n\nuseRDLS =True\nuseMCorr =True\n\napplyCorrection =True\napplyRedistancing=True\nrdtimeIntegration='osher'#'osher-psitc'#tte\nsloshbox_quad_order = 3 #need 4 for quadratics\n\ncheckMass = False\nuseBackwardEuler=True\nuseBackwardEuler_ls=True\n\nnonlinearSolverNorm = LinearAlgebraTools.l2NormAvg\n\nlag_ns_subgridError=True\nlag_ls_shockCapturing=True\nls_shockCapturingFactor=0.33#0.1\nrd_shockCapturingFactor=0.33#0.1\nns_shockCapturingFactor=0.33\n\nrd_freezeLS = True\nusePETSc=False#True\nnOverlap = 1\npartitioningType = MeshTools.MeshParallelPartitioningTypes.element\n#-P\"-ksp_type bcgsl -pc_type asm -pc_asm_type basic -pc_asm_overlap 1 -sub_ksp_type preonly -sub_pc_type lu -sub_pc_factor_mat_solver_package spooles -ksp_atol 1.0e-7 -ksp_rtol 1.0e-7 \"\n#\nuseStokes=False\nVOF = False\nnonconsrv = True\nif VOF:\n nonconsrv = True\nspaceOrder=1\n\n#spatial domain\nnd = 3\n#set up absorbing boundary at left side using volume averaged ns formulation\nspongeLayerWidth = 0.2\nuseSpongeLayer = True\n\ndomain = beach_erosion_board_3dDomain.beach_erosion_board_with_sponge_layer_3d(spongeLayerWidth=spongeLayerWidth,\n domainHeightPad=0.2,\n inflowLength=3.0,#0.45,3.0\n beachLength=4.48,\n beachSlope =0.1,\n h_c=0.054,#0.054,\n h_s=0.081,\n s =3.0,\n B = 0.0896,\n s_2= -0.2,\n backStepFraction=0.25,\n outflowLength=0.5,\n width = 0.3)\nnnx=3; nny=3\nnLevels = 1\nheight=domain.L[2]\nlength=domain.L[0]\nwidth =domain.L[1]\nL = domain.L\nconstraintFactor = 0.2\nvolumeConstraint = (((constraintFactor*height)**3)/6.0,)\ndx =0.05*height ; dy = dx ; dz = dx; he = dx;\ntriangleOptions=\"VpAfq1.25ena%f\" % (volumeConstraint)\n#triangleOptions=\"VpAq1.25en\" \n\n\ndomain.writeAsymptote(\"beach_erosion_board_3d\")\ndomain.writePoly(\"beach_erosion_board_3d\")\ndomain.writePLY(\"beach_erosion_board_3d\")\n\n\n\n#wave specification\nrunWaveProblem=True\n\n#source zone for generating waves\n#background water level\nwaterLevelBase = 0.529#domain.bathymetry([domain.x_be])+domain.h_s#backHeight#0.529#should be 0.529 #m\nwaveHeight=0.107#0.5#default 0.107#m\nwavePeriod= 1.549 #[s]\nwaveCelerity = 1.21#[m/s] don't know\nwaveNumber= 1.04/waterLevelBase #[1/m]\nwaveLength= 2.0*pi/waveNumber\nwaveFrequency = 2.0*pi/wavePeriod\n#source_height=max(5*dy,0.5*waterLevelBase)#max(5*dy,L[1])#max(5*dy,0.25*waterLevelBase)\nsource_height=0.1*waterLevelBase#max(5*dy,0.5*waterLevelBase)#max(5*dy,L[1])#max(5*dy,0.25*waterLevelBase)\nsource_zm =domain.x[2]+0.3*waterLevelBase\n#source_ym =domain.x[1]+0.5*L[1]#waterLevelBase\nsource_xm =0.75*domain.inflowLength#0.5*domain.inflowLength\nsource_length =max(3.0*dx,0.1)#better max(3.0*dx,0.2)\nOmega_s=[[source_xm,source_xm+source_length],\n [0,width],\n [source_zm-0.5*source_height,source_zm+0.5*source_height]]\n \nsourceVolume = 0.1*(Omega_s[0][1]-Omega_s[0][0])*(Omega_s[1][1]-Omega_s[1][0])*(Omega_s[2][1]-Omega_s[2][0])\nwaveFlag= 0 #0 -- monochromatic\n #1 -- second order stokes\n #2 -- solitary wave\n #-1 -- no internal wave\nsetWavesAtInflow = False#True\nif setWavesAtInflow:\n waveFlag = -1\n\ntopOpen = True#False\n\n\n#boundary conditions\n#slip on bottom, \n#outflow on sides\n#top open with grate --> p = 0, u = 0, v is free\n \n\n#\n#numerical fudge factors\nepsFact = 1.5\nepsFact_density = 1.5#0.33#1.5#1.5\nepsFact_viscosity = 1.5#0.33#1.5\nepsFact_redistance = 0.33#1.5\nepsFact_curvature=0.001\nepsFact_source = 0.5\nepsFact_vof=1.5\nepsFact_consrv_heaviside = 1.5\nepsFact_consrv_dirac = 1.5\nepsFact_consrv_diffusion = 10.0#1.5\n\n#physical parameters\n#water\nrho_0=998.2\nnu_0=1.004e-6\n#air\nrho_1=1.205\nnu_1= 1.500e-5\n#gravity\ng=[0.0,0.0,-9.8]\n#mwf play with density and viscosity ratios\n#rho_1 = rho_0/20.\n#nu_1 = nu_0*0.5\nturbulenceClosureFlag = None#1 Smagorinsky\nsmagorinskyConstant_0 = 0.1\nsmagorinskyConstant_1 = 0.5\n#surface tension\nsigma_01 = 0.0#72.8e-3\n\nimport math\nT =wavePeriod*5.0#*10.0#10.#*10.0#2.5#3.0#10.0\nnDTout = int(math.ceil(T/wavePeriod)*10+1)#51#101#None#2#None, can't be 1\nrunCFL = 0.33\n\ndt_init = min(0.01*wavePeriod,T)\nuseSpongeFunc = False\nspongeGrainSize= 0.01\nspongePorosity = 0.5\nkillNonlinearDragInSpongeLayer = True#True\ndef setSpongeLayer(x,porosity,meanGrain=None):\n porosity.fill(1.0) #fluid domain\n if meanGrain != None:\n meanGrain.fill(spongeGrainSize)\n #import pdb\n #pdb.set_trace()\n nPoints = len(x.flat)/3 #points always 3d\n for k in range(nPoints):\n if x.flat[k*3+0] <= spongeLayerWidth:\n porosity.flat[k]=spongePorosity\n #\n #\n #\n #mwf hack\n #porosity.flat[:] = obstaclePorosity\n#\nimport numpy\nif useSpongeLayer == True and useSpongeFunc:\n spongeLayerFunc = setSpongeLayer\nelif useSpongeLayer == True:\n spongeLayerFunc = None\n porosityTypes = numpy.array([1.0,spongePorosity])\n meanGrainSizeTypes = numpy.array([1.0,spongeGrainSize])\nelse:\n spongeLayerFunc = None\n porosityTypes = None\n meanGrainSizeTypes = None\n\n\n\n#try to vary free surface height at boundary\nepsForVOF=epsFact\nbcsTimeDependent = setWavesAtInflow \ndef getDBC_p_ns(x,flag):\n if flag == domain.boundaryTags['top']:\n return lambda x,t: 0.0\n\ndef getDBC_u_ns(x,flag):\n if flag == domain.boundaryTags['top']:\n return lambda x,t: 0.0\n\n \ndef getDBC_v_ns(x,flag):\n if flag == domain.boundaryTags['top']:\n return lambda x,t: 0.0\n\n\ndef getDBC_w_ns(x,flag):\n if not topOpen and flag == domain.boundaryTags['top']:\n return lambda x,t: 0.0\n\ndirichletConditions_ns = {0:getDBC_p_ns,\n 1:getDBC_u_ns,\n 2:getDBC_v_ns,\n 3:getDBC_w_ns}\n\nslip_walls = [domain.boundaryTags['bottom'],domain.boundaryTags['front'],domain.boundaryTags['back']]\noutflow_walls = [domain.boundaryTags['left'],domain.boundaryTags['right']]\ndef getAFBC_p_ns(x,flag):\n if flag in slip_walls:\n return lambda x,t: 0.0\n if not topOpen and flag == domain.boundaryTags['top']:\n return lambda x,t: 0.0\n \ndef getAFBC_u_ns(x,flag):\n if flag in slip_walls:\n return lambda x,t: 0.0\n \ndef getAFBC_v_ns(x,flag):\n if flag in slip_walls:\n return lambda x,t: 0.0\n\ndef getAFBC_w_ns(x,flag):\n if flag in slip_walls:\n return lambda x,t: 0.0\n\ndef getDFBC_u_ns(x,flag):\n #go ahead and enforce no diffusive flux on outflow too for VANS2P\n #need parallel boundaries as well\n return lambda x,t: 0.0\n if flag in slip_walls:# or flag in [domain.boundaryTags['top']]:\n return lambda x,t: 0.0\n if flag in outflow_walls:\n return lambda x,t: 0.0\ndef getDFBC_v_ns(x,flag):\n #need parallel boundaries as well\n return lambda x,t: 0.0\n if flag in slip_walls:# or flag in [domain.boundaryTags['top']]:\n return lambda x,t: 0.0\n #go ahead and enforce no diffusive flux on outflow too for VANS2P\n if flag in outflow_walls:\n return lambda x,t: 0.0\ndef getDFBC_w_ns(x,flag):\n #need parallel boundaries as well\n return lambda x,t: 0.0\n if flag in slip_walls:# or flag in [domain.boundaryTags['top']]:\n return lambda x,t: 0.0\n #go ahead and enforce no diffusive flux on outflow too for VANS2P\n if flag in outflow_walls:\n return lambda x,t: 0.0\n\nfluxBoundaryConditions_ns = {0:'outFlow',\n 1:'outFlow',\n 2:'outFlow',\n 3:'outFlow'}\n\nadvectiveFluxBoundaryConditions_ns = {0:getAFBC_p_ns,\n 1:getAFBC_u_ns,\n 2:getAFBC_v_ns,\n 3:getAFBC_w_ns}\n\ndiffusiveFluxBoundaryConditions_ns = {0:{},\n 1:{1:getDFBC_u_ns},#,2:getDFBC_u_ns,3:getDFBC_u_ns},\n 2:{2:getDFBC_v_ns},#3:getDFBC_v_ns},\n 3:{3:getDFBC_w_ns}}\n\n\n#try to vary free surface height at boundary\n\nclass AtRest:\n def __init__(self):\n pass\n def uOfXT(self,x,t):\n return 0.0\n\nclass Hydrostatic_p:\n def __init__(self):\n pass\n def uOfXT(self,x,t):\n if x[2] >= waterLevelBase:\n return -(domain.L[2]-x[2])*rho_1*g[2]\n else:\n return -((domain.L[2]-waterLevelBase)*rho_1 +\n (waterLevelBase-x[2])*rho_0)*g[2]\n\ninitialConditions_ns = {0:Hydrostatic_p(),\n 1:AtRest(),\n 2:AtRest(),\n 3:AtRest()}\n\n\nclass Flat_phi:\n def __init__(self):\n pass\n def uOfXT(self,x,t):\n return x[2] - waterLevelBase\n\nclass Flat_H:\n def __init__(self,eps=epsFact_consrv_heaviside*dy):\n self.eps=eps\n def uOfXT(self,x,t):\n return smoothedHeaviside(self.eps,x[2] - waterLevelBase)\n \ndef getDBC_vof(x,flag):\n if setWavesAtInflow:\n return freeSurfaceVOF_bc\n if flag in [domain.boundaryTags['top']]:\n return lambda x,t: 1.0\n #enforce air on right outflow boundary?\n if flag in [domain.boundaryTags['right']]:\n return lambda x,t: 1.0\n #\n if flag in [domain.boundaryTags['left']]:\n return lambda x,t: smoothedHeaviside(epsFact*dz,x[2]-waterLevelBase)\ndef getAFBC_vof(x,flag):\n #pass\n if flag == 0: #internal boundary\n return lambda x,t: 0.0\n \n if flag in slip_walls:# or flag in [domain.boundaryTags['top']]:\n return lambda x,t: 0.0\n","sub_path":"benchmarks/beach/beach_erosion_board_waves_3d.py","file_name":"beach_erosion_board_waves_3d.py","file_ext":"py","file_size_in_byte":10648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"397692430","text":"from model.cnn_model import *\nfrom model.cnn_image import *\nfrom model.evaluation import *\n\nimport time\nimport numpy as np\nimport torchvision\nimport torchvision.transforms as transforms\nimport torchvision.models as models\n\nimport os\nimport copy\nfrom os.path import join\nimport glob\n\ndef mkdir(path):\n folder = os.path.exists(path)\n if not folder: \n os.makedirs(path)\n return path\n\n\ndef generate_compare(cnn,imgs_pair,saving_path):\n loss = 0\n for i in imgs_pair:\n \n l = evaluation(cnn,i[0],i[1])\n loss +=l\n temp = i[0].split(\"/\",-1)\n name = temp[-1][:-6]\n print(name)\n with open(join(saving_path, 'npscores','scores'),'a+') as f:\n f.write(name + ' ' + str(loss) + '\\n')\n loss = 0\n print('data written')\n\n\nif __name__ == '__main__':\n # import pre-trained model \n cnn = models.vgg19(pretrained=True).features.to(device).eval()\n #get result images:\n g='../data/results_np'\n imgs_original = []\n imgs_generated = []\n x = glob.glob(os.path.join(g,'*'))\n for fname in x:\n for iname in os.listdir(fname):\n if iname[-5] == '0':\n imgs_original.append(join(fname,iname))\n elif int(iname[-5]) > 0:\n imgs_generated.append(join(fname,iname))\n imgs_pair = list(zip(imgs_original,imgs_generated))\n\n\n mkdir('../results/npscores/')\n\n # clean scores file\n if os.path.isfile('../results/npscores/scores'):\n os.remove('../results/npscores/scores')\n\n # compare generated\n generate_compare(cnn,imgs_pair,saving_path = '../results/',)\n\n ","sub_path":"neural-style-transfer/src/eva_executable.py","file_name":"eva_executable.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"251400014","text":"\n# coding: utf-8\n\nimport tensorflow as tf\nslim = tf.contrib.slim\ngraph_replace = tf.contrib.graph_editor.graph_replace\n\nimport sys, os\nsys.path.extend([os.path.expanduser('..')])\nfrom alasso import utils\n\nimport numpy as np\n\n# ## Parameters\n\n# Data params\ninput_dim = 784\noutput_dim = 10\n\n# Network params\nn_hidden_units = 2000\nactivation_fn = tf.nn.relu\n\n# Optimization params\nbatch_size = 256\nepochs_per_task = 20 \nlearning_rate=1e-3\n\nxi = 0.1\na_param = 1.8\na_prime = 1.0\nepsilon = 1.0e-6\nepsilon_prime = 0.0\nomega_smoothing = 1.0\n\n# Reset optimizer after each age\nreset_optimizer = False\n\n\n# ## Construct datasets\nn_tasks = 100\nn_repeat = 3\n\nfull_datasets, final_test_datasets = utils.construct_permute_mnist(num_tasks=n_tasks)\ntraining_datasets = full_datasets\nvalidation_datasets = final_test_datasets\n\n# ## Construct network, loss, and updates\ntf.reset_default_graph()\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth=True\nsess = tf.InteractiveSession(config=config)\nsess.run(tf.global_variables_initializer())\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nmodel = Sequential()\nmodel.add(Dense(n_hidden_units, activation=activation_fn, input_dim=input_dim))\nmodel.add(Dense(n_hidden_units, activation=activation_fn))\nmodel.add(Dense(output_dim, activation='softmax'))\n\nfrom alasso import protocols\nfrom alasso.optimizers import KOOptimizer\nfrom keras.optimizers import SGD, Adam, RMSprop\nfrom keras.callbacks import Callback\nfrom alasso.keras_utils import LossHistory\n\n\nprotocol_name, protocol = protocols.ALASSO_PROTOCOL(a_param=a_param, a_prime=a_prime, epsilon=epsilon, epsilon_prime=epsilon_prime, omega_smoothing=omega_smoothing, xi=xi)\nopt = Adam(lr=learning_rate, beta_1=0.9, beta_2=0.999)\nopt_name = 'adam'\noopt = KOOptimizer(opt, model=model, **protocol)\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=oopt, metrics=['accuracy'])\nmodel.model._make_train_function()\n\nhistory = LossHistory()\ncallbacks = [history]\n\nfile_prefix = \"data_%s_opt%s_lr%.2e_bs%i_ep%i_tsks%i\"%(protocol_name, opt_name, learning_rate, batch_size, epochs_per_task, n_tasks)\ndatafile_name = \"%s.pkl.gz\"%(file_prefix)\n\n\n# ## Train!\n\ndiag_vals = dict()\nall_evals = dict()\n\nruntime_param_table = [\n (1.0, 1.0),\n ]\n\ndef run_fits(param_indices, training_data, valid_data, eval_on_train_set=False):\n for param_index in param_indices:\n current_params = runtime_param_table[param_index]\n\n fs = []\n evals = []\n print(\"setting params\")\n print(\"param: %s\"%str(current_params))\n\n for repeat in range(n_repeat):\n sess.run(tf.global_variables_initializer())\n\n oopt.set_c(current_params[0])\n oopt.set_c_prime(current_params[1])\n\n oopt.init_task_vars()\n\n print(\" Repeat %i\"%repeat)\n for age, tidx in enumerate(range(n_tasks)):\n print(\" Age %i\"%age)\n\n current_training_data_input = training_data[tidx][0]\n current_training_data_gt = training_data[tidx][1]\n shuffle = True\n\n oopt.set_nb_data(len(current_training_data_input))\n stuffs = model.fit(current_training_data_input, current_training_data_gt, batch_size, epochs_per_task, callbacks=callbacks,\n verbose=0, shuffle=shuffle)\n oopt.update_task_metrics(current_training_data_input, current_training_data_gt, batch_size)\n oopt.update_task_vars()\n\n ftask = []\n for j in range(n_tasks):\n if eval_on_train_set:\n f_ = model.evaluate(training_data[j][0], training_data[j][1], batch_size, verbose=0)\n else:\n f_ = model.evaluate(valid_data[j][0], valid_data[j][1], batch_size, verbose=0)\n ftask.append(np.mean(f_[1]) / float(n_repeat))\n if repeat == 0:\n evals.append(ftask)\n else:\n for j in range(n_tasks):\n evals[tidx][j] = evals[tidx][j] + ftask[j]\n\n # Re-initialize optimizer variables\n if reset_optimizer:\n oopt.reset_optimizer()\n\n evals = np.array(evals)\n all_evals[param_index] = evals\n \n # backup all_evals to disk\n utils.save_zipped_pickle(all_evals, datafile_name)\n\nparam_indices = list(range(len(runtime_param_table)))\nprint(param_indices)\n\n# Run\nrun_fits(param_indices, training_datasets, validation_datasets)\n\n# backup all_evals to disk\nutils.save_zipped_pickle(all_evals, datafile_name)\n\n\n\n","sub_path":"permuted_mnist/train_100.py","file_name":"train_100.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"213356472","text":"def calculate_performance(maze, population):\n \"\"\"\n Analyzes all possible transition in maze environment and checks if there\n is a reliable classifier for it.\n :param maze: maze object\n :param population: list of classifiers\n :return: percentage of knowledge\n \"\"\"\n transitions = maze.env.get_all_possible_transitions()\n\n # Take into consideration only reliable classifiers\n reliable_classifiers = [c for c in population if c.is_reliable()]\n\n # Count how many transitions are anticipated correctly\n nr_correct = 0\n\n # For all possible destinations from each path cell\n for start, action, end in transitions:\n\n p0 = maze.env.maze.perception(*start)\n p1 = maze.env.maze.perception(*end)\n\n if any([True for cl in reliable_classifiers\n if cl.predicts_successfully(p0, action, p1)]):\n nr_correct += 1\n\n return {\n 'knowledge': nr_correct / len(transitions) * 100.0\n }\n","sub_path":"examples/acs2/maze/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"432909655","text":"import requests\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-u\", \"--url\", help=\"add [X] in url\")\nparser.add_argument(\"-f\", \"--file\", help=\"payload file path\")\nargs = parser.parse_args()\nurl = args.url\n\nprint(\"\"\"\n... [eXSSoz]======eXSSoz======[-][o][x]\n... | |\n... | Welcome to eXSSoz! |\n... | Version 0.1 |\n... | Add -h parameter to learn |\n... | how to use it |\n... | |\n... |=================================|\n... \"\"\")\nprint(\"\\n\")\n\nfile = open(args.file, \"r\")\n\nfor x in open(args.file).readlines():\n payload = file.readline()\n url2 = url.replace(\"[X]\", payload)\n r = requests.get(url2)\n print(\"URL:\", url2)\n print(\"Payload:\", payload)\n print(\"Status Code:\", r.status_code)\n print(\"Content-Length:\", r.headers['content-length'], \"\\n\")\n\nfile.close()","sub_path":"eXSSoz.py","file_name":"eXSSoz.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"184863327","text":"#!/usr/bin/env python\n\nimport socket\nimport csv, sys, time, os\n\nTCP_IP = '127.0.0.1'\nTCP_PORT = 5017\nBUFFER_SIZE = 1024\n\n#Remove old additions\nif os.path.isfile(\"./additions.csv\"):\n os.remove(\"./additions.csv\")\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((TCP_IP, TCP_PORT))\ns.send(sys.argv[1])\ns.close()\n\nwhile not os.path.isfile(\"./additions.csv\"):\n time.sleep(1) \n\n\n","sub_path":"Assets/StreamingAssets/Model/runmodel.py","file_name":"runmodel.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"630637740","text":"from collections import deque\r\nimport sys\r\nsys.setrecursionlimit(100000)\r\n\r\ndirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\r\na = [0]\r\ndef dfs(startV: int):\r\n queue = deque()\r\n queue.append(startV)\r\n \r\n while queue:\r\n x, y = queue.popleft()\r\n graphPaper[x][y] = 0\r\n a[0] += 1\r\n\r\n for move in dirs:\r\n moved_x, moved_y = x + move[0], y + move[1]\r\n\r\n if 0 <= moved_x < N and 0 <= moved_y < M and graphPaper[moved_x][moved_y] == 1:\r\n dfs((moved_x, moved_y))\r\n \r\n return a[0]\r\n \r\n\r\nM, N, K = map(int, sys.stdin.readline().split())\r\ngraphPaper = [[1] * M for _ in range(N)]\r\n\r\nfor _ in range(K):\r\n xs, ys, xe, ye = map(int, sys.stdin.readline().split())\r\n for i in range(xs, xe):\r\n for j in range(ys, ye):\r\n graphPaper[i][j] = 0\r\n\r\ncnt = 0\r\nareas = []\r\n\r\nfor i in range(N):\r\n for j in range(M):\r\n if graphPaper[i][j] == 1:\r\n a[0] = 0\r\n areas.append(dfs((i, j)))\r\n cnt += 1\r\n\r\nprint(cnt)\r\nfor area in sorted(areas):\r\n print(area, end=' ')","sub_path":"geonhokim/6.Depth_First_Search/영역구하기.py","file_name":"영역구하기.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"243854036","text":"#!/usr/bin/env python\n\n\"\"\"\nA script to open default camera by launching it as a node.\nLast Update on: 03/12/18\n\"\"\"\n\nfrom distutils.version import LooseVersion\nimport cv2\nimport rospy\nfrom cv_bridge import CvBridge # bridge openCV & ROS\nfrom sensor_msgs.msg import Image # data type\n\n\n#if LooseVersion(cv2.__version__).version[0] == 2:\n# if LooseVersion(cv2.__version__).version[0] == 3: # runs on openCV 3\n # Whatever OpenCV2 code\n\ncap = cv2.VideoCapture(0) # 0 = default camera\n\nwhile True:\n\n\tpub = rospy.Publisher(\"frames\", Image, queue_size = 10)\n\trospy.init_node(\"default_camera_pub\")\n\trate = rospy.Rate(10)\n\n\tret, img = cap.read()\n\n\tcv2.imshow(\"Camera\", img)\n\n\tbridge = CvBridge() # give frames to ROS environment\n\n\tros_image = bridge.cv2_to_imgmsg(img, \"bgr8\") # Encoding bgr8: CV_8UC3 color image with blue-green-red color order\n\tpub.publish(ros_image)\n\trate.sleep()\n\n\tkey = cv2.waitKey(20)\n\tif key == 27:\n\t break\n\ncv2.destroyAllWindows()\ncap.release()\n","sub_path":"src/colour_detection/src/scripts/open_cam.py","file_name":"open_cam.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"387090425","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls.defaults import patterns, include, url\nfrom django.contrib.auth.decorators import login_required\n\nfrom ralph.cmdb.views import (\n Add,\n AddRelation,\n CIChangesEdit,\n CIChangesView,\n CIGitEdit,\n CIGitView,\n CIIncidentsEdit,\n CIIncidentsView,\n CIProblemsEdit,\n CIProblemsView,\n CIPuppetEdit,\n CIPuppetView,\n CIRalphEdit,\n CIRalphView,\n CIRelationsEdit,\n CIRelationsView,\n CISOEventsEdit,\n CISOEventsView,\n CIZabbixEdit,\n CIZabbixView,\n EditRelation,\n Index,\n LastChanges,\n MainCIEdit,\n MainCIView,\n Search,\n ViewUnknown,\n)\nfrom ralph.cmdb.views_changes import (\n Change,\n Changes,\n Dashboard,\n DashboardDetails,\n Incidents,\n Problems,\n Reports,\n)\nfrom ralph.cmdb.views_changes import TimeLine\nfrom ralph.cmdb.views import Graphs\n\n\nurlpatterns = patterns(\n '', (r'^$', login_required(Index.as_view())),\n (r'^search$', login_required(Search.as_view())),\n\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)$', login_required(MainCIView.as_view()), name='ci_view'),\n\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/main/$', login_required(MainCIView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/relations/$', login_required(CIRelationsView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/git/$', login_required(CIGitView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/puppet/$', login_required(CIPuppetView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/ralph/$', login_required(CIRalphView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/ci_changes/$', login_required(CIChangesView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/zabbix/$', login_required(CIZabbixView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/problems/$', login_required(CIProblemsView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/incidents/$', login_required(CIIncidentsView.as_view()), name='ci_view'),\n url(r'^ci/view/(?P[a-z]{0,2}-?[0-9]+)/so/$', login_required(CISOEventsView.as_view()), name='ci_view'),\n\n (r'^ci/jira_ci_unknown/$', login_required(ViewUnknown.as_view())),\n\n url(r'^ci/edit/(?P\\w+)$', login_required(MainCIEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/main/$', login_required(MainCIEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/relations/$', login_required(CIRelationsEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/git/$', login_required(CIGitEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/puppet/$', login_required(CIPuppetEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/ralph/$', login_required(CIRalphEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/ci_changes/$', login_required(CIChangesEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/zabbix/$', login_required(CIZabbixEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/problems/$', login_required(CIProblemsEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/incidents/$', login_required(CIIncidentsEdit.as_view()), name='ci_edit'),\n url(r'^ci/edit/(?P\\w+)/so/$', login_required(CISOEventsEdit.as_view()), name='ci_edit'),\n\n (r'^ci/get_last_changes/(?P.*)$', login_required(LastChanges.as_view())),\n (r'^relation/add/(?P\\w+)$', login_required(AddRelation.as_view())),\n (r'^relation/delete/(?P\\w+)/(?P\\w+)$', login_required(EditRelation.as_view())),\n (r'^relation/edit/(?P\\w+)$', login_required(EditRelation.as_view())),\n (r'^add/$', login_required(Add.as_view())),\n (r'^rest/', include('ralph.cmdb.rest.urls')),\n (r'^changes/change/(?P\\w+)$', login_required(Change.as_view())),\n (r'^changes/changes$', login_required(Changes.as_view())),\n (r'^changes/incidents$', login_required(Incidents.as_view())),\n (r'^changes/problems$', login_required(Problems.as_view())),\n\n (r'^changes/timeline$', login_required(TimeLine.as_view())),\n (r'^changes/timeline_ajax$', login_required(TimeLine.get_ajax)),\n\n (r'^changes/dashboard$', login_required(Dashboard.as_view())),\n (r'^changes/dashboard_ajax$', login_required(Dashboard.get_ajax)),\n (r'^changes/dashboard_details/(?P[0-9]+)/(?P[0-9]+)/'\n '(?P[0-9]+)/(?P\\w+)$',\n login_required(DashboardDetails.as_view())),\n (r'^changes/reports$', login_required(Reports.as_view())),\n (r'^graphs$', login_required(Graphs.as_view())),\n)\n","sub_path":"src/ralph/cmdb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"101618200","text":"vacations = {}\n\nvacation_active = True\n\nwhile vacation_active:\n\tname = raw_input('\\nQual o seu nome? ')\n\tvacation = raw_input('\\nSe pudesse visitar um lugar do mundo, para onde iria? ')\n\n\tvacations[name] = vacation\n\n\tverificar = raw_input('\\nDeseja fazer a pesquisa novamente (yes/no)')\n\tif verificar == 'no':\n\t\tvacation_active = False\n\nprint('\\n--- Vacations ---')\nfor name, vacation in vacations.items():\n\tprint(name + ' quer ir para: ' + vacation)","sub_path":"input_while/vacation.py","file_name":"vacation.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"120608116","text":"aa = \"\"\"\n userLoginpwd: \"123456qqQQ\"\n captcha: ${resultData}\n userMobile: \"\"\n userLoginname: \"YL015359\"\n verify: \"\"\n userEmail: \"\"\n \"\"\"\n# print(aa)\n# pattern = r'\\\\$\\\\{(.+?)\\\\}'\n# m = re.compile(\"\\$\\{(.+?)\\}\")\n# # b = m.findall(aa)\n# # print(type(b))\n# ms = re.finditer(\"\\$\\{(.+?)\\}\",aa)\n# for match in ms:\n# print(match.group())\n\n#\na = \"${aaa}\"\n# print(re.sub('[${}]','',a))\n# b = {}\n# # b['a']=\"2\"\n# b.setdefault('a','2')\n# print(b)\n#\n# ass = {'captchaToken': 'A3E7371F3D714AF58ABD7B66332C4C84', 'captchaValue': '5237'}\n# bss = \"resultData\"\n# c = EnvParamter.getDict().setdefault(bss,ass)\n# print(c)\n# import jsonpath\n# csd = {'api': 'sc/captcha/captcha', 'result': '000000', 'msg': '', 'data': {'captchaToken': 'FC1D2F5DDA654567902275874EA3DCF6', 'captchaValue': '7383'}, 'gid': 'G2021011811354801000001', 'seqno': '2021011811354801000001', 'cid': '',\n# 'timestamp': 1610940949011}\n# df=re.sub('[\\[\\]]','',str(jsonpath.jsonpath(csd,\"$.data\")))\n# print(df)\n#\n# c = EnvParamter.getDict()\n# print(c)\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nenv_path = Path('.') / '.env'\nprint(load_dotenv(dotenv_path=env_path))","sub_path":"test/test02.py","file_name":"test02.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"59714722","text":"#Read the JSON documents and output the body of the article about the United Kingdom. Reuse the output in problems 21-29.\nimport gzip\nimport json\n\ndef read_json(file_path):\n with gzip.open(file_path,'rt') as f:\n for line in f:\n file_data = json.loads(line)\n if file_data['title'] == 'United Kingdom':\n return(file_data['text'])\n\nif __name__ == '__main__':\n file_path = '/users/kcnco/github/100knock2021/pan/chapter03/enwiki-country.json.gz'\n print(read_json(file_path))\n\nwith open('/users/kcnco/github/100knock2021/pan/chapter03/x20.txt','w') as f_name:\n f_name.write(text)\n","sub_path":"pan/chapter03/X20.py","file_name":"X20.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169217147","text":"import os\nfrom django.core.management.base import BaseCommand\nfrom resources.models import Book\n\nclass Command(BaseCommand):\n\n def populate_library(self):\n module_dir = os.path.dirname(__file__) # get current directory\n file_path = os.path.join(module_dir, 'library.txt')\n library_file = open(file_path, 'r')\n\n for entry in library_file.readlines():\n book = Book(title=entry)\n book.save()\n\n library_file.close()\n\n def handle(self, *args, **options):\n self.populate_library()\n","sub_path":"resources/management/commands/populate_resources_db.py","file_name":"populate_resources_db.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"648191707","text":"#!/usr/bin/env python3\n\n\nimport os\nimport sys\nimport time\nfrom pprint import pprint\n\nimport cv2\nimport numpy\nfrom trueface.face_attributes import FaceAttributes\nfrom trueface.recognition import FaceRecognizer\nfrom trueface.video import VideoStream\n\nwith open('token', 'r') as f:\n TOKEN = f.read().strip()\n\nFR = FaceRecognizer(\n ctx='cpu',\n fd_model_path='fd_model',\n params_path='emotion_model/model.params',\n license=TOKEN\n)\nFA = FaceAttributes(\n labels='emotion_model/labels.pickle',\n model='emotion_model/model.trueface',\n params='emotion_model/model.params'\n)\n\nEMOTIONS = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']\n\n\nclass EmotionProfile:\n def __init__(self, emotions):\n assert(type(emotions) is dict)\n\n for e in EMOTIONS:\n setattr(self, e, emotions.get(e, 0))\n\n def __repr__(self):\n emotions = ['\"%s\":%f' % (e, getattr(self, e)) for e in EMOTIONS]\n return '{%s}' % ','.join(sorted(emotions))\n\n\nclass Face:\n def __init__(self, face):\n assert(type(face) is dict)\n\n self.bbox = face['bounding_box']\n self.chip = face['chip']\n\n def get_emotions(self):\n emotions = FA.get_attributes(self.chip)\n\n if emotions:\n emotions = {k.decode().lower(): v for k, v in emotions.items()}\n\n return EmotionProfile(emotions)\n\n\ndef main(argv):\n rows = int(argv[1])\n cols = int(argv[2])\n\n raw_in = input()\n data = list(map(lambda x: int(x), raw_in.split(',')))\n\n frame = numpy.ndarray(\n shape=(rows, cols, 3),\n buffer=numpy.array(data, dtype=numpy.uint8),\n dtype=numpy.uint8)\n\n face = FR.find_biggest_face(\n frame,\n return_chips=True,\n return_binary=True,\n chip_size=96\n )\n if face:\n face = face[0]\n else:\n return\n\n face = Face(face)\n print(face.get_emotions())\n\n\nif __name__ == '__main__':\n try:\n sys.exit(main(sys.argv))\n except Exception as e:\n print(e)\n","sub_path":"process-img.py","file_name":"process-img.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"494665217","text":"from model.group import Group\nfrom random import randrange\nimport random\nimport allure\n\n\n@allure.story(\"Редактирование группы\")\ndef test_edit_group(app, db, check_ui):\n old_groups = db.get_group_list()\n group = Group(name=\"test_group_1\", header=\"test_1\", footer=\"test_comment_1\")\n if app.group.count() == 0:\n app.group.create(Group(name=\"test_grup\", header=\"test\", footer=\"test_comment\"))\n # случайно выберем группу для редактирования\n group_edit = random.choice(old_groups)\n id = group_edit.id\n # модифицируем группу по id\n app.group.modify_group_by_id(id, group)\n new_groups = db.get_group_list()\n assert len(old_groups) == len(new_groups)\n # удаляем у старой группы старые данные\n old_groups.remove(group_edit)\n # формируем данные новые\n new_list = Group(index=id, name=group.name, header=group.header, footer=group.footer)\n # добавляем их в старую группу. Теперь идем сравнивать\n old_groups.append(new_list)\n assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)\n # нужна проверка на UI?\n if check_ui:\n assert sorted(new_groups, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)\n\n\n","sub_path":"test/test_edit_group.py","file_name":"test_edit_group.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"630034737","text":"import os\n\nimport requests\nimport tarfile\n\nfrom pathlib import Path\n\nclass ModelLoader:\n URL = \"https://docs.google.com/uc?export=download\"\n\n @staticmethod\n def model_path(name: str):\n cache_path = Path.home() / Path(\".cache\", \"pycode2seq\")\n return os.path.join(cache_path, name)\n\n @staticmethod\n def load(name: str, file_id: str) -> str:\n path = ModelLoader.model_path(name)\n\n session = requests.Session()\n\n response = session.get(ModelLoader.URL, params={'id': file_id}, stream=True)\n token = ModelLoader._get_confirm_token(response)\n\n if token:\n params = {'id': file_id, 'confirm': token}\n response = session.get(ModelLoader.URL, params=params, stream=True)\n\n model_tar_path = os.path.join(path, \"model.tar.xz\")\n ModelLoader._save_response_content(response, model_tar_path)\n\n ModelLoader._extract_archive(model_tar_path, path)\n\n return path\n\n @staticmethod\n def _get_confirm_token(response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n\n return None\n\n @staticmethod\n def _save_response_content(response, destination):\n CHUNK_SIZE = 32768\n\n with open(destination, \"wb\") as f:\n for chunk in response.iter_content(CHUNK_SIZE):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\n @staticmethod\n def _extract_archive(archive_path: str, extract_path: str):\n tar = tarfile.open(archive_path)\n tar.extractall(extract_path)\n tar.close()\n","sub_path":"pycode2seq/inference/model/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329052890","text":"\nimport sys\nfrom cStringIO import StringIO\nimport unittest\n\nfrom metadata import Table\nfrom strings_star_relion import particles_3d_classify, one_micrograph_mc\n\n\nclass TestTable(unittest.TestCase):\n \"\"\"\n Our basic test class\n \"\"\"\n def _checkColumns(self, table, columnNames):\n for colName, col in zip(columnNames, table.getColumns()):\n self.assertEqual(colName, str(col))\n\n def test_read_particles(self):\n \"\"\"\n Read from a particles .star file\n \"\"\"\n t1 = Table()\n f1 = StringIO(particles_3d_classify)\n\n t1.readStar(f1)\n cols = t1.getColumns()\n\n self.assertEqual(len(t1), 16)\n self.assertEqual(len(cols), 25)\n\n # Check that all rlnEnabled is 1 and rlnMicrographId is increasing from 1 to 17\n for i, row in enumerate(t1):\n self.assertEqual(row.rlnEnabled, '1')\n self.assertEqual(int(row.rlnImageId), i + 1)\n\n f1.close()\n\n def test_read_blocks(self):\n \"\"\"\n Read an star file with several blocks\n \"\"\"\n t1 = Table()\n f1 = StringIO(one_micrograph_mc)\n\n # This is a single-row table (different text format key, value\n t1.readStar(f1, tableName='general')\n goldValues = [('rlnImageSizeX', '3710'),\n ('rlnImageSizeY', '3838'),\n ('rlnImageSizeZ', '19'),\n ('rlnMicrographMovieName', 'Movies/14sep05c_00024sq_00003hl_00002es.frames.out.mrc'),\n ('rlnMicrographBinning', '1.000000'),\n ('rlnMicrographOriginalPixelSize', '0.980000'),\n ('rlnMicrographDoseRate', '1.000000'),\n ('rlnMicrographPreExposure', '0.000000'),\n ('rlnVoltage', '300.000000'),\n ('rlnMicrographStartFrame', '1'),\n ('rlnMotionModelVersion', '1')\n ]\n\n self._checkColumns(t1, [k for k, v in goldValues])\n row = t1[0]\n for k, v in goldValues:\n self.assertEqual(getattr(row, k), v)\n\n t1.readStar(f1, tableName='global_shift')\n cols = t1.getColumns()\n\n self.assertEqual(len(t1), 19)\n self._checkColumns(t1, ['rlnMicrographFrameNumber',\n 'rlnMicrographShiftX',\n 'rlnMicrographShiftY'])\n\n t1.readStar(f1, tableName='local_motion_model')\n\n self.assertEqual(len(t1), 36)\n self._checkColumns(t1, ['rlnMotionModelCoeffsIdx',\n 'rlnMotionModelCoeff'])\n coeffs = [int(v) for v in t1.getColumnValues('rlnMotionModelCoeffsIdx')]\n self.assertEqual(coeffs, range(36))\n\n f1.close()\n\n def test_write_singleRow(self):\n t = Table()\n f1 = StringIO(one_micrograph_mc)\n t.readStar(f1, tableName='global_shift')\n t.writeStar(sys.stdout, tableName='global_shifts', singleRow=True)\n\n t = Table(columns=['rlnImageSizeX',\n 'rlnImageSizeY',\n 'rlnMicrographMovieName'])\n t.addRow(3710, 3838, 'Movies/14sep05c_00024sq_00003hl_00002es.frames.out.mrc')\n fn = '/tmp/test-single-row.star'\n with open(fn, 'w') as f:\n print(\"Writing star file to: \", fn)\n t.writeStar(f, singleRow=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"465169841","text":"import os\nimport datetime\n\nfrom flask import Flask, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import request\n\napp = Flask(__name__)\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\ndb_url = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')\napp.config['SQLALCHEMY_DATABASE_URI'] = db_url\napp.config['SQLALCHEMY_DATABASE_URI'] = False\n\ndb = SQLAlchemy(app)\n\n\nclass Post(db.Model):\n __tablename__ = 'post'\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String, nullable=False)\n content = db.Column(db.Text)\n cdate = db.Column(db.Date)\n\n\n@app.route(\"/\")\ndef list():\n query = db.session.query(Post)\n posts = query.order_by(Post.cdate.desc()).all()\n num = len(posts)\n return render_template(\"list.html\", num=num, posts=posts)\n\n\n@app.route(\"/new_form\", methods=['POST', 'GET'])\ndef new_form():\n if request.method == \"POST\":\n title = request.form['title']\n content = request.form['content']\n d = datetime.date.today()\n # 데이터베이스에 새로운 메세지를 추가한다.\n n_post = Post(title=title, comtent=content, cdate=d)\n db.session.add(n_post)\n db.session.commit()\n return render_template(\"new.html\")\n else:\n return render_template(\"new_form.html\")\n\n\n@app.route(\"/view\", methods=['POST', 'GET'])\ndef view():\n mid = request.args.get('mid', 1, type=int)\n # 데이터베이스에서 기존의 메세지를 읽는다.\n query = db.session.query(Post)\n query = query.filter(Post.id == mid)\n v_post = query.one()\n return render_template(\"view.html\", post=v_post)\n\n\n@app.route(\"/update\", methods=['POST', 'GET'])\ndef update():\n mid = request.args.get('mid', 1, type=int)\n # 데이터베이스에서 기존의 메세지를 읽을 준비한다.\n query = db.session.query(Post)\n query = query.filter(Post.id == mid)\n if request.method == \"POST\":\n query.update(\n {Post.title: request.form['title'],\n Post.content: request.form['content']}\n )\n db.session.commit()\n return render_template(\"update.html\")\n else: # 기존의 메세지 내용을 읽어서 보여주다\n u_post = query.one()\n return render_template(\"update_form.html\", post=u_post)\n\n\n@app.route(\"/delete\", methods=['POST', 'GET'])\ndef delete():\n mid = request.args.get('mid', 1, type=int)\n # 데이터베이스에서 기존의 메세지를 삭제한다.\n query = db.session.query(Post)\n query = query.filter(Post.id == mid)\n query.delete()\n db.session.commit()\n return render_template(\"update.html\")\n","sub_path":"ch07/app11/simpleapp.py","file_name":"simpleapp.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"185135340","text":"import redis\nimport argparse\nfrom PubSub import PubSub\nfrom rq import Queue\nimport RedisConfigHelper\nimport json\nimport logging\nimport boto\nimport os\nfrom utils import *\nimport logging_tree\nfrom redis import StrictRedis\n\nlogging.config.fileConfig(\"%s/%s\" % (os.getcwd(),\"logging.cfg\"))\nlogger = logging.getLogger()\n\n\n\nlogging_tree.printout()\n\n\nparser = argparse.ArgumentParser(description='Subscribes to a Redis PubSub Channel and Manage the MDM on Request')\nparser.add_argument('-c','--channel', help='Channel Name', required=True)\nparser.add_argument('-q','--queue', help='RedisQueue queue name to dispatch to', required=True)\n\nargs = vars(parser.parse_args())\n\n\n\n\nready = PubSub(redis.Redis(), args['channel'])\nmdmqueue = Queue(\"MDM\",connection=redis.Redis())\nconfig = RedisConfigHelper.RedisConfigHelper()\nr = StrictRedis()\n\naws = connectToAWS(\n key_id=config.getConfig('aws_access_key_id'),\n key_secret=config.getConfig('aws_secret_access_key')\n)\n\nreadyinstances = []\n\nlogger.info(\"Starting\")\n\ndef handler(data):\n logger.debug(\"Data received: %r\" % data)\n request = json.loads(data)\n logger.debug(\"Retrieving AWS instance for id %s\" % request['instanceid'])\n instance = aws.get_only_instances([request['instanceid']])[0]\n logger.debug(\"Instance retrieved: %s\" % instance)\n \n usecase = instance.__dict__['tags']['UseCase']\n if usecase == 'mdm':\n r.set('mdmready','true')\n # This is a special case....we are going to say the MDM is ready and push its info into the RedisConfig\n r.set('mdmprivip',instance.private_ip_address)\n r.set('mdmpubip',instance.ip_address)\n \n if usecase == 'sds':\n # Collect messages about ready SDS', and whenever the MDM does becomes ready (by checking for the existence of the relevant key in RedisConfig), then start dispatching jobs to the MDM RQ queue.\n logger.debug(\"Recording instance %s as ready, storing on the stack\")\n readyinstances.append(instance) \n \n if config.getConfig('mdmready') == 'true': #Now, at the end of the loop, if there are instances, lets run them....\n logger.debug(\"MDM is ready, running through additions from readyinstances \") \n for instance in readyinstances:\n logger.debug(\"Enqueuing instance %s \" % instance.id)\n mdmqueue.enqueue_call(\n func=addSDS,\n args=(instance,),\n timeout=600\n )\n readyinstances.remove(instance)\n else:\n logger.debug(\"MDM not yet ready, ready instances on the stack to be added: %s\" % readyinstances)\n \nlogger.debug(\"Entering subscription wait loop\") \nready.subscribe(handler)\n","sub_path":"mdmManager.py","file_name":"mdmManager.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326165892","text":"import sys,os\nsys.path.append(os.pardir)\nimport numpy as np\nfrom dataset.mnist import load_mnist\nimport pickle\n\n\n#simgoid函数\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef softmax(a):\n c = np.max(a)\n exp_a = np.exp(a-c)\n sum_exp_a = np.sum(exp_a)\n return exp_a/sum_exp_a\n\ndef get_data():\n (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True,flatten=True,one_hot_label=False )\n return x_test,t_test\n\ndef init_network():\n with open(\"sample_weight.pkl\",'rb') as f:\n network = pickle.load(f)\n\n return network\n\ndef predict(network,x):\n W1,W2,W3 = network['W1'],network['W2'],network['W3']\n b1,b2,b3 = network['b1'],network['b2'],network['b3']\n a1 = np.dot(x,W1) + b1\n z1 = sigmoid(a1)\n a2 = np.dot(z1,W2) + b2\n z2 = sigmoid(a2)\n a3 = np.dot(z2,W3) + b3\n y = softmax(a3)\n\n return y\n\n# if __name__=='__main__':\n# x,t = get_data()\n# network = init_network()\n# accuracy_cnt = 0\n# for i in range(len(x)):\n# y = predict(network,x[i])\n# p = np.argmax(y) #获取概率最高的元素的索引--索引和值是对应的\n# if p == t[i]:\n# accuracy_cnt += 1\n#\n# print(\"准确率为:\"+str(float(accuracy_cnt)/len(x)))\n\n\nif __name__=='__main__':\n '''批处理改造'''\n x,t = get_data()\n network = init_network()\n batch_size=100\n accuracy_cnt = 0\n print(x.shape)\n for i in range(0,len(x),batch_size):\n x_batch = x[i:i+batch_size]\n y_batch = predict(network,x_batch)\n p = np.argmax(y_batch,axis=1) #获取概率最高的元素的索引--索引和值是对应的\n accuracy_cnt += np.sum(p == t[i:i+batch_size])\n\n print(\"准确率为:\"+str(float(accuracy_cnt)/len(x)))\n","sub_path":"study2020/study2020/study_深度学习/ch03/neuralnet_mnist.py","file_name":"neuralnet_mnist.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273494033","text":"import pygame\nfrom SpriteSheet_Functions import SpriteSheet\nfrom Alien import Alien\nfrom Constants import *\n\nclass AlienExplosion(pygame.sprite.Sprite):\n animcycle = 4\n def __init__(self, Alien, sprite_sheet):\n \t#print \"Alien Explosion created!\"\n \tsuper(AlienExplosion, self).__init__()\n \tself.image = sprite_sheet.imgat(ALIEN_EXPLOSION_COORD)\n \tself.counter = 0\n \tself.maxcount = self.animcycle**2\n \tself.rect = self.image.get_rect()\n \tself.rect.center = Alien.rect.center\n\n \t#Il y a peut-etre une difference de 3 pixels entre l'alien et l'explosion\n \t#self.rect.x +=3\n \tAlien.kill()\n \n def update(self, *args):\n self.counter = self.counter + 1\n if self.counter == self.maxcount:\n self.kill()\n\n def __str__(self):\n \treturn \"AlienExplosion: x: %d and y: %d \" % (self.rect.x, self.rect.y)","sub_path":"AlienExplosion.py","file_name":"AlienExplosion.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"252667580","text":"# from HardCode.scripts.model_0.parameters.deduction_parameters.ecs_bounce.ecs_bounce import get_count_ecs\r\n# from HardCode.scripts.model_0.parameters.deduction_parameters.ecs_bounce.chq_bounce import get_count_cb\r\nfrom HardCode.scripts.Util import conn\r\n\r\n\r\ndef ecs_chq_count(user_id):\r\n connect = conn()\r\n parameters = connect.analysis.parameters.find_one({\"cust_id\":user_id})['parameters'][-1]\r\n count1 = parameters['ecs_bounce']\r\n count2 = parameters['chq_bounce']\r\n # count1 = get_count_ecs(user_id)\r\n # count2 , status2 = get_count_cb(user_id)\r\n\r\n ecs_check = False\r\n cb_check = False\r\n\r\n\r\n if count1 >= 4 :\r\n ecs_check = True\r\n\r\n if count2 >= 2:\r\n cb_check = True\r\n connect.close()\r\n variables = {\r\n 'ecs_check' :ecs_check,\r\n 'cb_check' : cb_check\r\n\r\n }\r\n\r\n values = {\r\n 'ecs_bounce' :count1,\r\n \"cheque_bounce\": count2\r\n }\r\n\r\n return variables,values","sub_path":"HardCode/scripts/model_0/channel2/deduction_checks/ecs_bounce_checks.py","file_name":"ecs_bounce_checks.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"501534539","text":"import pprint\nimport subprocess\nimport os\nimport sys\n\nfrom subprocess import PIPE\nfrom datastructure import OrderedSet\n\n\nIS_PY2 = sys.version_info[0] == 2\n\n\nclass Shell():\n def run_cmd(self, text):\n p = subprocess.Popen([self.SHELL_BIN_PATH], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n if IS_PY2:\n out, err = p.communicate(text)\n else:\n out, err = p.communicate(bytes(text, 'utf-8'))\n out = str(out, 'utf-8')\n err = str(err, 'utf-8')\n return(out, err)\n\n\nclass Bash(Shell):\n def __init__(self):\n self.SHELL_BIN_PATH = None\n self.set_shell_path()\n self.history = None\n self.get_history()\n\n def set_shell_path(self):\n path = subprocess.Popen(['which', 'bash'], stdout=PIPE).communicate()[0]\n self.SHELL_BIN_PATH = path.decode('utf-8').replace('\\n', '')\n\n def get_history(self):\n out, err = self.run_cmd('cat ~/.bash_history')\n hist_tokens = [tk for tk in out.split('\\n')[:1000] if 'cd' in tk]\n pprint.pprint(hist_tokens)\n\n if hist_tokens:\n hist_tokens.pop()\n\n oset = OrderedSet()\n oset.update(hist_tokens)\n self.history = oset\n \n\nclass Fish(Shell):\n def __init__(self):\n self.SHELL_BIN_PATH = None\n self.set_shell_path()\n self.history = None\n self.get_history()\n\n def set_shell_path(self):\n path = subprocess.Popen(['which', 'fish'], stdout=PIPE).communicate()[0]\n self.SHELL_BIN_PATH = path.decode('utf-8').replace('\\n', '')\n\n def _set_shell_path(self):\n fish_bin_dir = os.environ.get('__fish_bin_dir')\n path = None\n\n if not fish_bin_dir:\n for p in os.environ['PATH'].split(os.pathsep):\n proposed_path = os.path.join(p, 'fish')\n if os.access(proposed_path, os.X_OK):\n path = proposed_path\n break\n if not path:\n print('fish not found')\n sys.exit(-1)\n else:\n print('fish found at ' + path)\n\n else:\n path = os.path.join(fish_bin_dir, 'fish')\n \n if not os.access(path, os.X_OK):\n print('fish could not be executed at ' + path)\n sys.exit(-1)\n\n self.SHELL_BIN_PATH = path\n\n def get_history(self):\n out, err = self.run_cmd('for val in $history; echo -n $val \\\\x1e; end')\n hist_tokens = [tk for tk in out.split(' \\x1e') if 'cd' in tk]\n print(hist_tokens)\n \n if hist_tokens:\n hist_tokens.pop() # remove the command which started all this shit\n\n oset = OrderedSet()\n oset.update(hist_tokens)\n self.history = oset\n\n\nh = Bash()\npprint.pprint(h.history.at(0))\nprint(h.SHELL_BIN_PATH)\n \n \n","sub_path":"next.py","file_name":"next.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"113088142","text":"blocks = [int(v) for v in input().strip().split()]\nseen = set()\ncurr = tuple(v for v in blocks)\nsteps = 0\nwhile curr not in seen:\n seen.add(curr)\n largest = max(range(len(blocks)), key=lambda k: blocks[k])\n i = min([k for k in range(len(blocks)) if blocks[k] == blocks[largest]])\n hold = blocks[i]\n blocks[i] = 0\n while hold > 0:\n i = i + 1 if (i != len(blocks) - 1) else 0\n blocks[i] += 1\n hold -= 1\n steps += 1\n curr = tuple(blocks[j] for j in range(len(blocks)))\nprint(steps)\n","sub_path":"December06/mem1.py","file_name":"mem1.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"294668763","text":"from datetime import date\nimport unittest\n\nfrom monolith.tests.test_base import TestBase\nimport wtforms as f\n\nfrom monolith.app import app as tested_app\nfrom monolith.database import db, User, Message\nfrom monolith.views.messages import draft\n\n\nclass TestApp(TestBase):\n\n def test_draft(self):\n\n reply = self.login(self.sender, \"1234\")\n self.assertIn(b\"Hi\", reply.data)\n\n message = dict(\n receiver=self.receiver,\n date='2020-10-26T01:01',\n text='test_draft_2020-10-26T01:01',\n draft = True)\n\n reply = self.app.post(\"/draft\",\n data=message, follow_redirects = True)\n self.assertIn(message['text'].encode('utf-8'), reply.data)\n\n id = 0\n from monolith.app import app\n with app.app_context():\n id = db.session.query(Message).filter(Message.text == message['text']).first().id\n\n reply = self.app.get(\"/message/send/\" + str(id), follow_redirects=True)\n self.assertIn(message['text'].encode('utf-8'), reply.data)\n reply = self.app.post(\"/message/send/\" + str(id), data=message)\n self.logout()\n","sub_path":"monolith/tests/test_draft.py","file_name":"test_draft.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"134185663","text":"import unittest\nimport json\n\nfrom opencricket.chart.sentence_parser import SentenceParser\n\nclass TestHighestTeamScore(unittest.TestCase):\n\n def setUp(self):\n self.input = \"what is the highest score of england\"\n self.expected = '{\"scores\": {\"team\": {\"team1\": \"england\"}, \"what_is_the\": {\"word_is\": \"is\", \"word_what\": \"what\", \"word_the\": \"the\"}, \"word_score\": \"score\", \"word_extent\": \"highest\", \"word_of\": \"of\"}}'\n\n self.input_in_this_year = \"what is the highest score of england in this year\"\n self.expected_in_this_year = '{\"scores\": {\"word_year\": \"year\", \"word_this_last\": \"this\", \"word_in\": \"in\", \"team\": {\"team1\": \"england\"}, \"what_is_the\": {\"word_is\": \"is\", \"word_what\": \"what\", \"word_the\": \"the\"}, \"word_score\": \"score\", \"word_extent\": \"highest\", \"word_of\": \"of\"}}'\n\n def test_search(self):\n parser = SentenceParser(self.input)\n self.assertEqual(json.loads(self.expected), json.loads(parser.parse_sentence()))\n\n def test_search_in_this_year(self):\n parser = SentenceParser(self.input_in_this_year)\n self.assertEqual(json.loads(self.expected_in_this_year), json.loads(parser.parse_sentence()))\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"tests/test_highest_scores_of_team.py","file_name":"test_highest_scores_of_team.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407719175","text":"import os\nimport urllib\nimport csv\nfrom bs4 import BeautifulSoup\n\ndef writeToTXT(descriptopn, file_name):\n file_name = \"output/\" + str(patent_file_name) +\".txt\" \n with open(file_name, \"w\") as txt_file: \n #for patent_info in patent_infos: \n #txt_file.write(str(real_doc_id))\n txt_file.write(str(real_invention_title))\n txt_file.write(' ')\n txt_file.write(str(real_description))\n \npatent_dir = \"output_2017_xmls\"\nfile_list = os.listdir(patent_dir)\n#print(file_list)\n\nfor patent_file_name in file_list:\n full_path = patent_dir + \"/\" + patent_file_name\n if os.path.isfile(full_path):\n with open(full_path, \"r\") as patent_document_file:\n patent_contents = \" \".join(patent_document_file.readlines())\n\n \n soup = BeautifulSoup(patent_contents, \"xml\")\n doc_id = soup.find(\"document-id\").get_text()\n #print(doc_id)\n real_doc_id = \"\".join(doc_id.split())\n #print(real_doc_id)\n invention_title = soup.find(\"invention-title\").get_text()\n real_invention_title = \" \".join(invention_title.split())\n #abstract = soup.find(\"abstract\").get_text()\n description = soup.find(\"description\").get_text()\n real_description = \" \".join(description.split())\n \n #patent_infos = []\n #patent_info = []\n #patent_info.append(doc_id)\n #patent_info.append(invention_title)\n #patent_info.append(abstract)\n #patent_info.append(description)\n #print(patent_info)\n #patent_infos.append(patent_info)\n #patent_info = [] \n file_name = \"output/\" + str(patent_file_name)\n \n writeToTXT(description, file_name)\n \n","sub_path":"description_extractor.py","file_name":"description_extractor.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"103421359","text":"import os\nimport yaml\nimport lasio\nimport linecache\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport warnings\n\nfrom lognet.utilities.FileInput import FileInput\nfrom lognet.utilities.FileOutput import FileOutput\nfrom lognet.preprocess.FormationPrep import FormationPrep\nfrom lognet.loader.structured_data_loader import StructuredDataset\nfrom lognet.models.ModelFactory import ModelFactory\n\nwarnings.simplefilter('ignore', category=DeprecationWarning)\n\n# Load parameters\nparams = yaml.load(open('examples/trainformparams.yml'))\n\nfile_input = FileInput(params['las_file_path'], params['metadata_csv'])\nbasins, formations = file_input.generateFormationList(params['features'])\n\ncsv_output = FileOutput(params['prepdata_path'])\ntrain_output = {}\nfor bname in basins:\n train_output[bname] = FileOutput(os.path.join(params['prepdata_path'], bname))\n\nfile_path = file_input.getFilePath()\nfile_list = file_input.getFileList()\n\nif not os.path.exists(params['model_path']):\n os.mkdir(params['model_path'])\n\n# Compute imputation values\ncols = ['SRESCurve', 'NeutCurve', 'SonicCurve', 'GRCurve', 'CaliCurve']\nlogcols = ['SRESCurve', 'NeutCurve']\nindependent = ['DEPT', 'SonicCurve', 'GRCurve', 'LAT', 'LON', 'logNeutCurve','logSRESCurve','CaliCurve']\ndependent = ['FORMATION_NAME']\ndbins = np.arange(0, 28000, 2000)\nform_prep = FormationPrep(basins, formations, cols, dbins)\ncounter = 0\nbasin_dict = {}\n\nfor fname in file_list:\n\n try:\n las_file = lasio.read(os.path.join(file_path, fname))\n except:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), fname)\n\n file_info = file_input.getFormationInfo(fname)\n info_dict = dict(zip(cols, file_info[cols].values[0]))\n basin_name = file_info['Name'].values[0]\n features_df = form_prep.generateBinSum(las_file, info_dict, basin_name)\n\n if not isinstance(features_df, pd.core.frame.DataFrame):\n continue\n\n FormationPrep.addLatitudeLongitude(features_df, file_info)\n form_prep.assembleFormations(features_df, file_info)\n\n csv_file = fname.split('.')[0] + '.csv'\n if len(features_df) > 0:\n csv_output.write_csv(csv_file, features_df)\n counter += 1\n\nprint(f\"Number of csv files: {counter}\")\nform_prep.finalizeBinMean()\n\n# Preprocess data\ncsv_path = csv_output.getFilePath()\ncsv_list = [f for f in os.listdir(csv_path) if f.endswith('csv')]\nheader_file = os.path.join(csv_path, 'headers.txt')\nif not os.path.isfile(header_file):\n error_message = 'Path: ' + csv_path + ' does not contain headers.txt file'\n raise FileNotFoundError(error_message)\nline = linecache.getline(header_file, 1)\ncolumn_names = line.rstrip().split(',')\n\nfor fname in csv_list:\n try:\n csv_df = pd.read_csv(os.path.join(csv_path, fname), header=None, names=column_names)\n except:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), fname)\n basin_name = csv_df['BASIN'].values[0]\n \n form_prep.fillMissingValues(csv_df, basin_name)\n FormationPrep.computeLog(csv_df, logcols)\n csv_df = csv_df[independent + dependent]\n csv_df = csv_df.replace([np.inf, -np.inf], np.nan)\n csv_df = csv_df.dropna() \n train_output[basin_name].write_csv(fname, csv_df)\n\n# Train model\nbname = params['basin']\nbasin_path = train_output[bname].getFilePath()\nfull_file_list = [f for f in os.listdir(basin_path) if f.endswith('csv')]\nprint('Total number of csv files: ', len(full_file_list))\n\nheader_file = os.path.join(basin_path, 'headers.txt')\nif not os.path.isfile(header_file):\n error_message = 'Path: ' + basin_path + ' does not contain headers.txt file'\n raise FileNotFoundError(error_message)\n\n# Training\ntraining_list, validation_list = train_test_split(full_file_list, test_size=0.25, random_state=424242)\n\nprint('Logs in training dataset: ', len(training_list))\nprint('Logs in validation dataset: ', len(validation_list))\n\ntraining_dataset = StructuredDataset(basin_path, header_file, training_list, dependent)\nvalidation_dataset = StructuredDataset(basin_path, header_file, validation_list, dependent)\n\n# Training and validating\ntrain_model = ModelFactory.select(params['model_type'], params['model_path'], form_prep.getNumFormations())\nerror_metric = train_model.train(training_dataset, validation_dataset)\nprint(error_metric)","sub_path":"LogNet-master/LogNet-master/examples/train_formation.py","file_name":"train_formation.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"173424619","text":"import clr\nclr.AddReference(\"COAPI\")\nfrom COAPI import *\nfrom System import *\n\ndef Execute(conquer):\n\taddress = 0x40B465\n\tbyteValue = conquer.Memory.ReadByte(address)\n\tif byteValue == 0x75:\n\t\tnewByteValue = 0xEB\n\telse:\n\t\tnewByteValue = 0x75\n\tconquer.Memory.Write(address, newByteValue)","sub_path":"CoHook/Scripts/FlashTaskBar.py","file_name":"FlashTaskBar.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"87479968","text":"# -*- coding: utf-8 -*-\n\"\"\"Urls.\"\"\"\n\n# Django\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path\n\n# Current django project\nimport sports_manager.views.category as vcategory\nimport sports_manager.views.gymnasium as vgymnasium\nimport sports_manager.views.license as vlicense\nimport sports_manager.views.player as vplayer\nimport sports_manager.views.team as vteam\nimport sports_manager.views.timeslot as vtimeslot\nfrom sports_manager import views\n\napp_name = 'sports-manager'\nurlpatterns = [\n path(\"category/\",\n view=vcategory.CategoryListView.as_view(),\n name='category-list',\n ),\n path(\"category/create/\",\n view=vcategory.CategoryCreateView.as_view(),\n name='category-create',\n ),\n path(\"category//\",\n view=vcategory.CategoryDetailView.as_view(),\n name='category-detail',\n ),\n path(\"category//update/\",\n view=vcategory.CategoryUpdateView.as_view(),\n name='category-update',\n ),\n path(\"category//delete/\",\n view=vcategory.CategoryDeleteView.as_view(),\n name='category-delete',\n )\n]\n\nurlpatterns += [\n path(\"team/\",\n view=vteam.TeamListView.as_view(),\n name='team-list',\n ),\n path(\"team/create/\",\n view=vteam.TeamCreateView.as_view(),\n name='team-create',\n ),\n path(\"team//\",\n view=vteam.TeamDetailView.as_view(),\n name='team-detail',\n ),\n path(\"team//update/\",\n view=vteam.TeamUpdateView.as_view(),\n name='team-update',\n ),\n path(\"team//delete/\",\n view=vteam.TeamDeleteView.as_view(),\n name='team-delete',\n ),\n path(\"team//time-slot/\",\n view=vtimeslot.TeamTimeSlotListView.as_view(),\n name='team-time-slot-list',\n ),\n path(\"team//time-slot/create/\",\n view=vtimeslot.TeamTimeSlotCreateView.as_view(),\n name='team-time-slot-create',\n ),\n path(\"team//time-slot//update/\",\n view=vtimeslot.TeamTimeSlotUpdateView.as_view(),\n name='team-time-slot-update',\n ),\n path(\"team//time-slot//delete/\",\n view=vtimeslot.TeamTimeSlotDeleteView.as_view(),\n name='team-time-slot-delete',\n )\n]\n\nurlpatterns += [\n path(\"/license/\",\n view=vlicense.LicenseListView.as_view(),\n name='license-list',\n ),\n path(\"/license/create/\",\n view=vlicense.LicenseCreateView.as_view(),\n name='license-create',\n ),\n path(\"/license//\",\n view=vlicense.LicenseDetailView.as_view(),\n name='license-detail',\n ),\n\n path(\"/player/\",\n view=vplayer.PlayerListView.as_view(),\n name='player-list',\n ),\n path(\"/player/create/\",\n view=vplayer.create_new_player,\n name='player-create',\n ),\n]\n\nurlpatterns += [\n path(\"gymnasium/\",\n view=vgymnasium.GymnasiumListView.as_view(),\n name='gymnasium-list',\n ),\n path(\"gymnasium/create/\",\n view=vgymnasium.GymnasiumCreateView.as_view(),\n name='gymnasium-create',\n ),\n path(\"gymnasium//\",\n view=vgymnasium.GymnasiumDetailView.as_view(),\n name='gymnasium-detail',\n ),\n path(\"gymnasium//update/\",\n view=vgymnasium.GymnasiumUpdateView.as_view(),\n name='gymnasium-update',\n ),\n path(\"gymnasium//delete/\",\n view=vgymnasium.GymnasiumDeleteView.as_view(),\n name='gymnasium-delete',\n )\n]\n","sub_path":"sports_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"532645934","text":"# coding=utf-8\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport os\nimport time\n\nimport setuptools\n\nimport examplet\n\n\nLICENCE = open('LICENSE').read()\nREADME = open('README.md').read()\nREQUIREMENTS = open('requirements.txt').read().split('\\n')\nDEPENDENCY_LINKS = open('dependency_links.txt').read().split('\\n')\n\n\nsetuptools.setup(author='Artur Dębski',\n author_email='artur.debski@codilime.com',\n name=examplet.__name__,\n version=examplet.__version__,\n description=examplet.__doc__,\n license=LICENCE,\n long_description=README,\n dependency_links=DEPENDENCY_LINKS,\n install_requires=REQUIREMENTS,\n packages=setuptools.find_packages(),\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"248242126","text":"from flask import Flask, request\nimport json\napp=Flask(__name__) #function name is app \n# use to create the flask app and intilize it\n@app.route(\"/\", methods\t=['PUT']) #Defining route and calling methods. GET will be in caps intalized as an arrya\n# if giving the giving any configuration then function name will proceed with @ else it will use name alone for example we are using @app name to updae the config of @app name \ndef helloworld():\n\tcontent = request.get_json()\n\t# name= content[\"Name\"]\n\twith open('personal.json', 'w') as json_file:\n\t\tjson.dump(content, json_file)\n\treturn \"data saved\"\n\nif __name__ == '__main__':\n\t\tapp.run()\n# by default flask uses 5000 port and host as 0.0.0.0\n\n# Run steps\n#1. Run with python FirstAPI.py \n#2. Flask will auto. create a server & start the flask app in dev mode\n#3. U can call ur API with address http://0.0.0.0:5000/ \n#4. First install the flask by command \"pip3 install flask\" before running the code","sub_path":"api/PutAPI.py","file_name":"PutAPI.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"230666422","text":"num = int(input(\"Enter a number: \"))\n\ndef is_lucky(n):\n\n str_num = str(n)\n even_ind = odd_ind= 0\n i = 0\n j = 1\n\n while i < len(str_num):\n\n even_ind += int(str_num[i])\n i += 2\n\n while j < len(str_num):\n\n odd_ind += int(str_num[j])\n j += 2\n\n if even_ind == odd_ind:\n print(\"Yes\")\n else:\n print(\"No\")\n\nis_lucky(num)\n\n","sub_path":"Homework_2/lucky_number.py","file_name":"lucky_number.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"140839981","text":"import time\n\nfrom datetime import datetime, timedelta\nimport pandas as pd\n\nfrom data.huobi import HUOBIFutureHistory\n\n\ndef get_huobi_future_data():\n base_time = datetime.strptime('2020-05-13', '%Y-%m-%d')\n last_year = base_time - timedelta(days=7)\n begin = int(datetime.timestamp(last_year))\n end = int(datetime.timestamp(base_time))\n to = begin + 2000 * 60\n\n history = HUOBIFutureHistory('BTC', 'USDT')\n\n bars = list()\n if begin and end:\n while to < end:\n print(f'{begin}----{to}')\n try:\n response_data = history.req_data_by_time_range(begin, to)\n except Exception as e:\n print(e)\n continue\n bars.extend(history.construct(response_data))\n begin = to\n to += 2000 * 60\n time.sleep(1)\n\n df = pd.DataFrame(data=[bar.__dict__ for bar in bars])\n df.to_csv('data/csv/huobi_future_test_1year.csv')\n","sub_path":"jquant/data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10443539","text":"import cv2\nimport numpy as np\nimport os\n\ndef half_image_convertor(img):\n height = img.shape[0]\n width = img.shape[1]\n img2 = cv2.resize(img , (int(width*0.5), int(height*0.5)))\n return img2\n\ndef yellow_trimmer(frame):\n bgrLower = np.array([20, 20, 120])\n #bgrLower = np.array([100,60,75])\n #bgrUpper = np.array([250, 255, 255]) # 抽出する色の上限(BGR)\n bgrUpper = np.array([130,255,255])\n img_mask = cv2.inRange(frame, bgrLower, bgrUpper) # BGRからマスクを作成\n result = cv2.bitwise_and(frame, frame, mask=img_mask)\n return result# -*- coding: utf-8 -*-\n\n\n\nres = yellow_trimmer(cv2.imread(\"images/source/m1.JPG\"))\n\n \ncv2.imwrite(\"RGB_m1.jpg\",res)\n \ncv2.imshow(\"hi\",res)\ncv2.waitKey(0)\ncv2.destroyAllWindows() ","sub_path":"yellow_block/codes/RGB_finder.py","file_name":"RGB_finder.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"143898682","text":"import pandas as pd\nimport numpy as np\nfrom pandas_datareader import data\nimport yaml\nimport sys\nimport math \nsys.setrecursionlimit(20000)\n\n\ndef SharpeRatio(\n returns : np.array) -> float:\n return np.mean(returns, axis=0) / (np.std(returns, axis=0))\n\ndef hit_ratio(\n returns : np.array) -> float:\n return np.sum(returns > 0, axis=0) /len(returns)\n\ndef featureNormalizer(X):\n\tm = len(X)\n\tmean = np.mean(X)\n\tstd = np.std(X)\n\tX_norm = (X-mean)/std\n\treturn X_norm , mean , std\n\ndef getcolumn(\n df: pd.DataFrame,\n column_name: str)-> np.array:\n return df[column_name].to_numpy()\n\n\ndef LoadConfig(\n yamlpath: str)-> dict:\n config = yaml.load(\n open(yamlpath, 'r'), \n Loader=yaml.FullLoader) \n return config\n\n\ndef GetData(\n ticker : str,\n start_date : str,\n end_date : str)-> pd.DataFrame:\n \"\"\"Getting historic price data from yahoo finance.\n \n Arguments:\n ticker {str} \n start_date {str} \n end_date {str} \n \n Returns:\n pd.DataFrame --> the output price dataframe\n \"\"\"\n return data.DataReader(ticker,'yahoo', start_date, end_date)\n\n\ndef DSR(\n returns: np.array,\n t:int, \n decay=0.5\n )->float:\n a = ema_mean(returns,decay,t)\n b = ema_std(returns,decay,t)\n delta_a = ema_mean(returns, decay,t-1) - a\n delta_b = ema_mean(returns, decay,t-1) - b\n if a**2 > b:\n return (b * delta_a - 0.5 *a *delta_b)/ ( - (abs(b-a**2))**(1.5)) \n\n else: \n delta_a = ema_mean(returns, decay,t-1) - a\n delta_b = ema_mean(returns, decay,t-1) - b\n return (b * delta_a - 0.5 *a *delta_b)/ ((b-a**2)**(1.5))\n\ndef dDSRdR(\n returns: np.array,\n t : int,\n decay=0.5)->float:\n a = ema_mean(returns,decay,t-1)\n b = ema_std(returns,decay,t-1)\n if a**2 > b:\n return (b - a * returns[t]) / (- abs((b-a**2))**(1.5))\n else:\n return (b - a * returns[t]) / ((b-a**2)**(1.5))\n\ndef ema_mean(\nreturns: np.array,\ndecay: float,\nt: int)-> float :\n if t < 0:\n return returns[t]\n else:\n ema = returns[t-1] + decay*(\n returns[t]- ema_mean(\n returns,decay,t-1\n )\n )\n return ema\n\ndef ema_std(\nreturns: np.array,\ndecay: float,\nt: int)-> float:\n if t < 0:\n return 0\n elif t==1:\n return returns[t]\n else:\n ema = returns[t-1] + decay*(\n returns[t]**2- ema_mean(\n returns,decay,t-1\n )\n )\n return ema\n\n\n\n","sub_path":"agents/depreciated/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"77530551","text":"from sklearn import datasets\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.decomposition import PCA\r\npizzaDataset = pd.read_csv('Pizza.csv',names = ['Brand', 'mois', 'prot', 'fat', 'ash','sodium','carb','cal'], header=0, sep=\",\")\r\nX = pizzaDataset.drop([\"Brand\"], axis=1)\r\n# standardize data\r\nX_std = StandardScaler().fit_transform(X)\r\n# create covariance matrix\r\ncov_mat = np.cov(X_std.T)\r\nprint('Covariance matrix \\n%s' % cov_mat)\r\neig_vals, eig_vecs = np.linalg.eig(cov_mat)\r\nprint('Eigenvectors \\n%s' % eig_vecs)\r\nprint('\\nEigenvalues \\n%s' % eig_vals)\r\n# sort eigenvalues in decreasing order\r\neig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:, i]) for i in range(len(eig_vals))]\r\n# Selecting the number of Principal Components\r\ntot = sum(eig_vals)\r\nvar_exp = [(i / tot)*100 for i in sorted(eig_vals, reverse=True)]\r\ncum_var_exp = np.cumsum(var_exp)\r\nprint(\"Cummulative Variance Explained\", cum_var_exp)\r\n# Plotting the graphics\r\nplt.figure(figsize=(8, 7))\r\nplt.bar(range(7), var_exp, alpha=0.5, align='center',label='Individual explained variance')\r\nplt.step(range(7), cum_var_exp, where='mid',label='Cumulative explained variance')\r\nplt.ylabel('Explained variance ratio')\r\nplt.xlabel('Principal components')\r\nplt.legend(loc='best')\r\nplt.tight_layout()\r\nplt.show()\r\n","sub_path":"No. 2/18360029_Ibnu Wanafa_No. 2 Principal Component Analysis.py","file_name":"18360029_Ibnu Wanafa_No. 2 Principal Component Analysis.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606720915","text":"overtime_hours = 0\r\nhours = raw_input('Enter hours: ')\r\nrate = raw_input('Enter Rate: ')\r\n\r\nif (float(hours) <= 40.0) :\r\n pay = float(hours) * float(rate)\r\nelse :\r\n overtime_hours = float(hours) - 40.0 \r\n overtime_rate = float(rate) * 1.5\r\n pay = (40.0 * float(rate)) + (overtime_hours * float(rate) * 1.5)\r\n\r\nprint ('Pay: '), pay\r\n\r\n","sub_path":"exer31.py","file_name":"exer31.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"355653553","text":"#!/sur/bin/python\n# -*-coding:utf-8-*-\nfrom appium import webdriver\nfrom time import sleep\n\n\ndef test_1():\n d = {\n \"platformName\": \"Android\", #设备类型\n \"platformVersion\": \"5.1.1\", #安卓版本\n \"deviceName\": \"emulator-5554\", #序列号\n \"appPackage\": \"com.qk.butterfly\", #安装包名\n \"appActivity\": \".main.LauncherActivity\", #活动名\n \"noReset\": \"true\", #保护用户操作数据\n \"unicodeKeyboard\":\"true\" #启用键盘\n }\n dr = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\",desired_capabilities=d) # 与模拟机进行连接\n sleep(3)\n dr.find_element_by_id(\"com.qk.butterfly:id/v_login_pwd\").click() # 点击密码登录\n sleep(3)\n dr.find_element_by_id(\"com.qk.butterfly:id/et_login_phone\").click() #点击输入账号框\n sleep(2)\n dr.find_element_by_id(\"com.qk.butterfly:id/et_login_phone\").send_keys(\"13319264301\") # 输入账号\n dr.find_element_by_id(\"com.qk.butterfly:id/et_login_pwd\").click() #点击输入账号\n sleep(3)\n dr.find_element_by_id(\"com.qk.butterfly:id/et_login_pwd\").send_keys(\"g123456\")\n sleep(2)\n dr.find_element_by_id(\"com.qk.butterfly:id/tv_to_login\").click() #点击登录\n sleep(3)\n b = dr.find_element_by_id(\"android:id/tabhost\").find_element_by_class_name(\"android.widget.RelativeLayout\").click()\n # .find_element_by_class_name(\"android.widget.RelativeLayout\")\n # b[-1].click()\n\n\n\n","sub_path":"python文件/自动化/test_2.py","file_name":"test_2.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"189321625","text":"import requests\nimport os\n\ncheck_file = os.path.isfile(\"upbit_data_t1.json\")\n\n\n\nif check_file is True:\n file = open(\"upbit_data_t1.json\", 'w')\nif check_file is False:\n file = open(\"upbit_data_t1.json\", 'w+')\n\nfile = open(\"upbit_data_t1.json\", 'w')\n\ndef func1():\n market = {\"KRW-ADA\", \"KRW-BTC\", \"KRW-AXS\", \"KRW-DOGE\", \"KRW-ETC\", \"KRW-ETH\", \"KRW-LINK\", \"KRW-LTC\", \"KRW-MANA\", \"KRW-NEO\", \"KRW-TRX\", \"KRW-VET\", \"KRW-XRP\"}\n url = \"https://api.upbit.com/v1/candles/days\"\n for i in market:\n querystring = {\"market\":i,\"count\":\"20\"}\n headers = {\"Accept\": \"application/json\"}\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n file.write(response.text)\n #file.close()\n\nfunc1()\n\nfiles = open(\"upbit_data_t1.json\", 'r')\nlines = files.readlines()\nstring = \"Too many\"\n\nfor lines in lines:\n if string in lines:\n func1()\n else:\n print(\"Success\")\n break\n\nstart = open(\"upbit_data_t1.json\", \"r\", encoding=\"UTF-8\")\n\nfor line in start:\n line = line.strip()\n changes = line.replace(\"][\", \",\")\nstart.close()\n\nend = open(\"upbit_data_t1.json\", \"w\", encoding=\"UTF-8\")\nend.write(changes)\nend.close()\n","sub_path":"UpbitTest/crawler_t1.py","file_name":"crawler_t1.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"74738223","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.15-x86_64/egg/foxylib/tools/cache/cache_tools.py\n# Compiled at: 2019-12-09 00:23:12\n# Size of source mod 2**32: 6000 bytes\nimport json, os, sys\nfrom datetime import datetime\nfrom functools import wraps, partial, lru_cache\nimport dill, six\nfrom frozendict import frozendict\nfrom future.utils import lfilter\nfrom nose.tools import assert_is_not_none\nfrom foxylib.tools.file.file_tools import FileToolkit\nfrom foxylib.tools.log.logger_tools import FoxylibLogger\n\nclass CacheToolkit:\n\n @classmethod\n def func_pair_identical(cls):\n f = lambda x: x\n return (f, f)\n\n class JSON:\n\n @classmethod\n def func_pair(cls):\n return (cls.serialize, cls.deserialize)\n\n @classmethod\n def normalize(cls, j):\n if isinstance(j, dict):\n return frozendict({k:cls.normalize(v) for k, v in sorted(j.items())})\n if isinstance(j, (list, set)):\n return tuple([cls.normalize(x) for x in j])\n return j\n\n @classmethod\n def serialize(cls, v):\n return cls.serialize_natural(v)\n\n @classmethod\n def deserialize(cls, s):\n return cls.deserialize_natural(s)\n\n @classmethod\n def serialize_natural(cls, j):\n return cls.normalize(j)\n\n @classmethod\n def deserialize_natural(cls, s):\n return s\n\n @classmethod\n def serialize_dill(cls, j):\n return dill.dumps(cls.normalize(j))\n\n @classmethod\n def deserialize_dill(cls, s):\n return dill.loads(s)\n\n @classmethod\n def cache2hashable(cls, func=None, cache=None, f_pair=None):\n assert_is_not_none(cache)\n assert_is_not_none(f_pair)\n f_serialize, f_deserialize = f_pair\n\n def wrapper(func):\n\n def deserialize_and_func(*args, **kwargs):\n logger = FoxylibLogger.func2logger(deserialize_and_func)\n _args = tuple([f_deserialize(arg) for arg in args])\n _kwargs = {k:f_deserialize(v) for k, v in six.viewitems(kwargs)}\n return func(*_args, **_kwargs)\n\n cached_func = cache(deserialize_and_func)\n\n @wraps(func)\n def wrapped(*args, **kwargs):\n logger = FoxylibLogger.func2logger(wrapped)\n _args = tuple([f_serialize(arg) for arg in args])\n _kwargs = {k:f_serialize(v) for k, v in kwargs.items()}\n return cached_func(*_args, **_kwargs)\n\n wrapped.cache_info = cached_func.cache_info\n wrapped.cache_clear = cached_func.cache_clear\n return wrapped\n\n if func:\n return wrapper(func)\n return wrapper\n\n @classmethod\n def cache2timed(cls, func=None, cache=None, timedelta=None):\n assert_is_not_none(cache)\n assert_is_not_none(timedelta)\n\n def dt_pivot2outdated(dt_pivot):\n if not dt_pivot:\n return True\n dt_now = datetime.now()\n return dt_now - dt_pivot > timedelta\n\n def wrapper(f):\n dt_pivot = None\n cached_func = cache(f)\n\n @wraps(f)\n def wrapped(*_, **__):\n nonlocal dt_pivot\n if dt_pivot2outdated(dt_pivot):\n cached_func.cache_clear()\n dt_pivot = datetime.now()\n v = cached_func(*_, **__)\n return v\n\n return wrapped\n\n if func:\n return wrapper(func)\n return wrapper\n\n @classmethod\n def f_or_file2utf8(cls, f, filepath):\n logger = FoxylibLogger.func2logger(cls.f_or_file2utf8)\n FileToolkit.dirpath2mkdirs(os.path.dirname(filepath))\n utf8 = FileToolkit.filepath2utf8(filepath)\n if utf8:\n return utf8\n utf8 = f()\n if utf8 is not None:\n FileToolkit.utf82file(utf8, filepath)\n return utf8\n\n @classmethod\n def f_utf82filed(cls, func=None, f_filepath=None):\n assert_is_not_none(f_filepath)\n\n def wrapper(f):\n\n @wraps(f)\n def wrapped(*_, **__):\n f_partial = partial(f, *_, **__)\n filepath = f_filepath(*_, **__)\n return cls.f_or_file2utf8(f_partial, filepath)\n\n return wrapped\n\n if func:\n return wrapper(func)\n return wrapper\n\n @classmethod\n def f_or_file2iter(cls, f, filepath):\n logger = FoxylibLogger.func2logger(cls.f_or_file2iter)\n f_str = lambda : '\\n'.join(list(f()))\n utf8 = cls.f_or_file2utf8(f_str, filepath)\n if utf8 is None:\n return\n return utf8.splitlines()\n\n @classmethod\n def f_iter2filed(cls, func=None, f_filepath=None):\n assert_is_not_none(f_filepath)\n\n def wrapper(f):\n\n @wraps(f)\n def wrapped(*_, **__):\n f_partial = partial(f, *_, **__)\n filepath = f_filepath(*_, **__)\n l = cls.f_or_file2iter(f_partial, filepath)\n return l\n\n return wrapped\n\n if func:\n return wrapper(func)\n return wrapper\n\n\nf_or_file2utf8 = CacheToolkit.f_or_file2utf8\nf_utf82filed = CacheToolkit.f_utf82filed\nf_or_file2iter = CacheToolkit.f_or_file2iter\nf_iter2filed = CacheToolkit.f_iter2filed","sub_path":"pycfiles/foxylib-0.3.96-py3.7/cache_tools.cpython-37.py","file_name":"cache_tools.cpython-37.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"139214744","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\GrTiPy\\Christoffel_All.py\n# Compiled at: 2018-11-01 04:07:43\n# Size of source mod 2**32: 873 bytes\nimport numpy as np\nfrom sympy import *\n\ndef Christoffel_All(d, x, g, ginverse):\n christoffel = [[[[] for k in range(d)] for j in range(d)] for i in range(d)]\n christoffel = [[[[] for k in range(d)] for j in range(d)] for i in range(d)]\n for n in range(d):\n for a in range(d):\n for b in range(d):\n summation = 0.0\n for i in range(d):\n summation = summation + ginverse[n][i] * (diff(g[i][a], x[b]) + diff(g[i][b], x[a]) - diff(g[a][b], x[i]))\n\n christoffel[n][a][b] = summation / 2\n\n for n in range(0, d):\n for a in range(0, d):\n for b in range(0, d):\n M = print('christoffel[', x[n], ',', x[a], ',', x[b], ']=', expand(simplify(christoffel[n][a][b])))\n\n return M","sub_path":"pycfiles/GrTiPy-0.1.0-py3.5/Christoffel_All.cpython-35.py","file_name":"Christoffel_All.cpython-35.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"75580782","text":"#!/usr/bin/env python\n\n# Copyright (c) 2016 GoSecure Inc.\n\nfrom construct import *\nfrom definitions import *\n\ndef unserialize_zend_function():\n return Zend_Op_Array(\"op_array\")\n\ndef unserialize_class():\n return Zend_Class_Entry(\"class\")\n\ndef Empty():\n return Struct(\"Empty\")\n\ndef Z_Val(name, callback = None, unserialize = True):\n\n if not callback:\n callback = Empty\n\n return Struct(name,\n Zend_Value(\"value\"),\n Struct(\"u1\",\n Byte(\"type\"),\n Byte(\"type_flags\"),\n Byte(\"const_flags\"),\n Byte(\"reserved\")\n ),\n ULInt32(\"u2\"),\n\n If(lambda z: z.u1.type == 6 and unserialize,\n Pointer(lambda z: z.value.w1 + Struct.sizeof(Meta), Zend_String(\"string\"))\n ),\n If(lambda z: z.u1.type == 17 and unserialize,\n Pointer(lambda z: z.value.w1 + Struct.sizeof(Meta), callback()))\n )\n\ndef Pointer_To(name, structure):\n structure.name = \"value\"\n return Struct(name,\n ULInt32(\"position\"),\n IfThenElse(structure.name, lambda z: z.position == 0,\n Empty(),\n Pointer(lambda z: z.position + Struct.sizeof(Meta), structure))\n )\n\ndef Zend_Class_Entry(name):\n return Struct(name,\n Bytes(\"padding\", 3),\n Byte(\"type\"),\n Pointer_To(\"name\", Zend_String(\"name\")),\n ULInt32(\"parent_pos\"),\n ULInt32(\"refcount\"),\n ULInt32(\"ce_flags\"),\n ULInt32(\"default_properties_count\"),\n ULInt32(\"default_static_members_count\"),\n ULInt32(\"default_properties_table_pos\"),\n ULInt32(\"default_static_members_table_pos\"),\n ULInt32(\"static_members_table_pos\"),\n Hash_Table(\"function_table\", unserialize_zend_function),\n Hash_Table(\"properties_table\"),\n Hash_Table(\"constants_table\"),\n Pointer_To(\"constructor\", Zend_Function(\"constructor\")))\n\ndef Zend_Function(name):\n return Struct(name,\n Byte(\"type\"),\n Bytes(\"arg_flags\", 3),\n ULInt32(\"fn_flags\"),\n Pointer_To(\"function_name\", Zend_String(\"function_name\")),\n ULInt32(\"scope_pos\"),\n ULInt32(\"prototype_pos\"),\n ULInt32(\"num_args\"),\n ULInt32(\"required_num_args\"),\n Pointer_To(\"arg_info\", Zend_String(\"arg_info\")))\n\ndef Bucket(name, callback = None):\n return Struct(name,\n Z_Val(\"val\", callback),\n ULInt32(\"h\"),\n ULInt32(\"key_pos\"),\n If(lambda z: z.val.u1.type != 0,\n Pointer(lambda z: z.key_pos + Struct.sizeof(Meta), Zend_String(\"key\")))\n )\n\ndef Hash_Table(name, callback = None):\n return Struct(name,\n Zend_Refcounted_H(\"gc\"),\n ULInt32(\"flags\"),\n ULInt32(\"nTableMask\"),\n ULInt32(\"bucket_pos\"),\n ULInt32(\"nNumUsed\"),\n ULInt32(\"nNumOfElements\"),\n ULInt32(\"nTableSize\"),\n ULInt32(\"nInternalPointer\"),\n ULInt32(\"nNextFreeElement\"),\n ULInt32(\"pDestructor\"),\n Pointer(lambda z: z.bucket_pos + Struct.sizeof(Meta),\n Array(lambda z: z.nNumUsed,\n Bucket(\"buckets\", callback)\n )))\n\ndef Zend_Value(name):\n return Struct(name,\n ULInt32(\"w1\"),\n ULInt32(\"w2\"))\n\n\ndef Zend_Refcounted_H(name):\n return Struct(name,\n ULInt32(\"refcount\"),\n ULInt32(\"typeinfo\"))\n\n\ndef Zend_String(name):\n return Struct(name,\n Zend_Refcounted_H(\"gc\"),\n ULInt32(\"h\"),\n ULInt32(\"len\"),\n String(\"val\", lambda zs: zs.len))\n\ndef Zend_Arg_Info(name):\n return Struct(name,\n Pointer_To(\"name\", Zend_String(\"name\")),\n Pointer_To(\"class_name\", Zend_String(\"class_name\")),\n Byte(\"type_hint\"),\n Byte(\"pass_by_reference\"),\n Byte(\"allow_null\"),\n Byte(\"is_variadic\"))\n\ndef Z_Node_Op(name):\n return Struct(name,\n ULInt32(\"val\"))\n\ndef Zend_Op(name):\n return Struct(name,\n ULInt32(\"handler\"),\n Z_Node_Op(\"op1\"),\n Z_Node_Op(\"op2\"),\n Z_Node_Op(\"result\"),\n ULInt32(\"extended_value\"),\n ULInt32(\"lineno\"),\n Byte(\"opcode\"),\n Byte(\"op1_type\"),\n Byte(\"op2_type\"),\n Byte(\"result_type\"))\n\ndef Zend_Op_Array(name):\n return Struct(name,\n Byte(\"type\"),\n Bytes(\"arg_flags\", 3),\n ULInt32(\"fn_flags\"),\n Pointer_To(\"function_name\", Zend_String(\"function_name\")),\n ULInt32(\"scope_pos\"),\n Pointer_To(\"prototype\", Zend_String(\"prototype\")),\n ULInt32(\"num_args\"),\n ULInt32(\"required_num_args\"),\n Pointer_To(\"arg_info\", Zend_Arg_Info(\"arg_info\")),\n ULInt32(\"refcount\"),\n ULInt32(\"this_var\"),\n ULInt32(\"last\"),\n ULInt32(\"opcodes_pos\"),\n Pointer(lambda z: z.opcodes_pos + Struct.sizeof(Meta),\n Array(lambda z: z.last,\n Zend_Op(\"opcodes\")\n )\n ),\n ULInt32(\"last_var\"),\n ULInt32(\"T\"),\n ULInt32(\"vars_pos_pos\"),\n Pointer(lambda z: z.vars_pos_pos + Struct.sizeof(Meta),\n Array(lambda z: z.last_var,\n Struct(\"vars\",\n ULInt32(\"pos\"),\n Pointer(lambda v: v.pos + Struct.sizeof(Meta), Zend_String(\"var\")))\n )\n ),\n ULInt32(\"last_live_range\"),\n ULInt32(\"last_try_catch\"),\n ULInt32(\"live_range_pos\"),\n ULInt32(\"try_catch_array_pos\"),\n Pointer_To(\"static_variables\", Hash_Table(\"static_variables\")),\n Pointer_To(\"filename\", Zend_String(\"filename\")),\n ULInt32(\"line_start\"),\n ULInt32(\"line_end\"),\n Pointer_To(\"doc_comment\", Zend_String(\"doc_comment\")),\n ULInt32(\"early_binding\"),\n ULInt32(\"last_literals\"),\n ULInt32(\"literals_pos\"),\n Pointer(lambda z: z.literals_pos + Struct.sizeof(Meta),\n Array(lambda z: z.last_literals,\n Z_Val(\"literals\")\n )\n ),\n ULInt32(\"cache_size\"),\n ULInt32(\"runtime_size\"),\n Array(4, ULInt32(\"reserved\")))\n\nScript = Struct(\"script\",\n Pointer_To(\"filename\", Zend_String(\"filename\")),\n Zend_Op_Array(\"main_op_array\"),\n Hash_Table(\"function_table\", unserialize_zend_function),\n Hash_Table(\"class_table\", unserialize_class))\n\nMeta = Struct(\"meta\",\n String(\"magic\", 8),\n String(\"system_id\", 32),\n ULInt32(\"mem_size\"),\n ULInt32(\"str_size\"),\n ULInt32(\"script_offset\"),\n ULInt32(\"timestamp\"),\n ULInt32(\"checksum\"))\n\nOPcache = Struct(\"OPcache\",\n Meta,\n Script)\n\nclass OPcodeParser():\n \"\"\" Parser for everything related to opcodes \"\"\"\n\n @staticmethod\n def get_opcode_name(opcode):\n \"\"\" Get the name for a given op number \"\"\"\n\n return OPCODES[opcode]\n\n def __init__(self, opcache):\n \"\"\" Keep track of the file stream for parsing\n\n Arguments :\n opcache : An OPcache instance to be used as context\n \"\"\"\n\n self.stream = opcache.stream\n\n def parse_jmp(self, opcode, op_array):\n \"\"\" Parse jump instructions\n\n Arguments :\n opcode : An opcode struct\n op_array : The op array of the opcode\n \"\"\"\n\n zend_op_size = Struct.sizeof(Zend_Op(\"\"))\n op1_val = opcode['op1']['val']\n op2_val = opcode['op2']['val']\n opcodes_pos = op_array['opcodes_pos']\n\n # Unconditional jump (no second operand)\n if opcode['opcode'] == 42:\n op1 = \"->\" + str((op1_val - opcodes_pos) / zend_op_size)\n op2 = \"None\"\n\n # Other jump instructions\n else:\n op1 = self.parse_zval(op2_val, opcode['op1_type'])\n op2 = \"->\" + str((op2_val - opcodes_pos) / zend_op_size)\n\n return (op1, op2, \"None\")\n\n def parse_operands(self, opcode, op_array):\n \"\"\" Parse the two operands and the result\n\n Arguments :\n opcode : An opcode struct\n op_array : The op array of the opcode\n \"\"\"\n\n # OP number and name\n op_no = opcode['opcode']\n\n # Treat jump instructions differently\n if 42 <= op_no and op_no <= 47:\n (op1, op2, result) = self.parse_jmp(opcode, op_array)\n\n else:\n op1 = self.parse_zval(opcode['op1'].val, opcode['op1_type'])\n op2 = self.parse_zval(opcode['op2'].val, opcode['op2_type'])\n result = self.parse_zval(opcode['result'].val, opcode['result_type'])\n\n return (op1, op2, result)\n\n def parse_zval(self, offset, op_type):\n \"\"\" Parse a zval at a offset for a given operand type\n\n Arguments :\n offset : The offset of the zval\n op_type : The type of the operand\n \"\"\"\n\n # Size to add to the offset\n size_of_meta = Struct.sizeof(Meta)\n\n # If the offset is invalid, consider the operand as unused\n try:\n zval = Z_Val(\"val\", unserialize=False).parse(self.stream[offset + size_of_meta:])\n except:\n return \"None\"\n\n # Get the type of the z_val and the two possible values\n type = zval['u1']['type']\n w1 = zval['value']['w1']\n w2 = zval['value']['w2']\n\n # Interpret the z_val\n if op_type == IS_CONST:\n if type == IS_STRING:\n return repr(Zend_String(\"val\").parse(self.stream[w1 + size_of_meta:])['val'])\n\n if type == IS_LONG:\n return str(w1)\n\n if type == IS_NULL:\n return \"None\"\n\n if op_type == IS_TMP_VAR:\n return \"~\" + str(w2)\n\n if op_type == IS_VAR:\n return \"$\" + str(w2)\n\n if op_type == IS_UNUSED:\n return \"None\"\n\n if op_type == IS_CV:\n return \"!\" + str(w2)\n\n return \"None\"\n\n\n\nclass OPcacheParser():\n \"\"\" Parses a given OPcache file \"\"\"\n\n def __init__(self, file_path):\n \"\"\" Parses a given OPcache file\n Arguments :\n file_path : The path of the file to parse\n \"\"\"\n\n with open(file_path, \"r\") as file:\n self.stream = file.read()\n\n self.parsed = OPcacheParser.parse_stream(self.stream)\n\n def __getitem__(self, index):\n return self.parsed[index]\n\n @staticmethod\n def parse_stream(stream):\n\n return OPcache.parse(stream)\n","sub_path":"opcache_parser.py","file_name":"opcache_parser.py","file_ext":"py","file_size_in_byte":11908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"651968903","text":"#################################\n#Напишите программный код, который будет создавать новый список,\n#содержащий в качестве элементов квадратные корни всех чисел из списка [2, 4, 9, 16, 25]:\n#1) на основе цикла for\n#2) на основе функции map\n#3) в виде генератора списка\n\nimport math\nlst = [2, 4, 9, 16, 25]\na = []\nfor i in lst:\n a.append(round(math.sqrt(i), 2))\n\nprint('1:', a)\n##################################\n\nlst2 = [2, 4, 9, 16, 25]\ndef f(x):\n return round(math.sqrt(x), 2)\n\nb = list(map(f, lst))\nprint('2:', b)\n################################\n\nlst3 = [2, 4, 9, 16, 25]\nc = [round(math.sqrt(i)) for i in lst3]\nprint('3:', c)","sub_path":"lesson_6/new_list.py","file_name":"new_list.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"558600392","text":"pkgname = \"python-cffi\"\npkgver = \"1.15.1\"\npkgrel = 0\nbuild_style = \"python_module\"\nhostmakedepends = [\"python-setuptools\", \"libffi-devel\"]\nmakedepends = [\"python-devel\", \"libffi-devel\"]\ndepends = [\"python-pycparser\"]\ncheckdepends = [\"python-pycparser\", \"python-pytest\"]\npkgdesc = \"C FFI for Python\"\nmaintainer = \"q66 \"\nlicense = \"MIT\"\nurl = \"https://cffi.readthedocs.io\"\nsource = f\"$(PYPI_SITE)/c/cffi/cffi-{pkgver}.tar.gz\"\nsha256 = \"d400bfb9a37b1351253cb402671cea7e89bdecc294e8016a707f6d1d8ac934f9\"\n# do_check needs fixing up more\noptions = [\"!check\"]\n\n\ndef do_check(self):\n self.do(\n \"python\",\n \"-m\",\n \"pytest\",\n env={\n \"PYTHONPATH\": str(\n list((self.cwd / \"build\").glob(\"lib.*\"))[0].relative_to(\n self.cwd\n )\n )\n },\n )\n\n\ndef post_install(self):\n self.install_license(\"LICENSE\")\n","sub_path":"main/python-cffi/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"621874117","text":"from starlette.config import Config\nfrom starlette.datastructures import Secret\n\nAPP_VERSION = \"0.0.1\"\nAPP_NAME = \"Sentiment prediction\"\nAPI_PREFIX = \"/api\"\n\nconfig = Config(\".env\")\n\n##############\n# API CONFIG #\n##############\nAPI_KEY: Secret = config(\"API_KEY\", cast=Secret)\nIS_DEBUG: bool = config(\"IS_DEBUG\", cast=bool, default=False)\n\n################\n# MODEL CONFIG #\n################\nDEFAULT_MODEL_PATH: str = config(\"DEFAULT_MODEL_PATH\")\n","sub_path":"smart_compose/api/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"545483690","text":"# Eric Waugh, Lex Dath, Jacob Sivo\r\n\r\nimport sys\r\nfrom pygame import *\r\nfrom RedoneTrexAnimationClass import *\r\nfrom RedoneTricAnimationClass import *\r\nfrom Health import HealthBar\r\nfrom TitleScreen import *\r\nfrom EndScreenClass import *\r\npygame.init()\r\n\r\ndef main():\r\n Game = True\r\n titleScreen = True\r\n\r\n while Game:# While Loop For Game\r\n Title = TitleScreen()# Set Up Title Screens and Windows plus Music\r\n WindowWidth = 790\r\n WindowHeight = 450\r\n windowSurface = pygame.display.set_mode((WindowWidth, WindowHeight), 0, 32)\r\n mainClock = pygame.time.Clock()\r\n pygame.display.set_caption('Jurastic Measures')\r\n soundTitle = pygame.mixer.Sound('Music/JurassicPark.wav')\r\n soundGame = pygame.mixer.Sound('Music/Doomsday.wav')\r\n endScreenSound = pygame.mixer.Sound('Music/BIB.wav')\r\n soundTitle.play(-1)\r\n\r\n while titleScreen:# Shows Title Screen until Player Presses Space then the Game Starts\r\n Title.drawTitle(windowSurface)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_SPACE:\r\n soundTitle.stop()\r\n titleScreen = False\r\n\r\n #\r\n # Set Up Variables\r\n #\r\n\r\n TrexX = 100\r\n TrexY = 260\r\n TricX = 600\r\n TricY = 260\r\n ground = 260\r\n gravity = 1\r\n Trex = TRexAnimate()\r\n Tric = TriceratopsAnimate()\r\n WinScreen = EndScreen()\r\n\r\n #\r\n # Set Up BackGround Images\r\n #\r\n\r\n ForeGround6 = pygame.image.load('LevelBackground/Foreground6.png')\r\n ForeGround5 = pygame.image.load('LevelBackground/Foreground5.png')\r\n ForeGround4 = pygame.image.load('LevelBackground/Foreground4.png')\r\n ForeGround3 = pygame.image.load('LevelBackground/Foreground3.png')\r\n ForeGround2 = pygame.image.load('LevelBackground/Foreground2.png')\r\n ForeGround1 = pygame.image.load('LevelBackground/Foreground.png')\r\n Background = pygame.image.load('LevelBackground/BorderBars.png')\r\n bgXSize, bgYSize = ForeGround1.get_size()\r\n bgX, bgY = int(-bgXSize // 4.5), 119\r\n bbX, bbY = 0, 0\r\n leftRockEdge = 55\r\n rightRockEdge = 65\r\n rightEdgePlusRockMax = 75\r\n bgXRightMax = -1*(bgXSize - WindowWidth)\r\n bgXLeftMax = 0\r\n bgXMove = 0\r\n TRANSP = (0, 0, 0, 0)\r\n decreasingHitBoxSizeXSize = 19\r\n\r\n #\r\n # Set up for invisible sprite for Trex\r\n #\r\n\r\n Sprite1 = 'TrexImages/T-Rex.png'\r\n SPR1 = pygame.image.load(Sprite1).convert_alpha()\r\n spr1XSize, spr1YSize = SPR1.get_size()\r\n spr1XSizeBox = spr1XSize\r\n spr1XSizeBox -= decreasingHitBoxSizeXSize\r\n TrexSurface = pygame.Surface((spr1XSize, spr1YSize), flags=SRCALPHA, depth=32)\r\n TrexSurface.fill(TRANSP)\r\n\r\n #\r\n # Set up for invisiable sprite for Triceratops\r\n #\r\n\r\n Sprite2 = 'TriceratopsImages/Triceratops.png'\r\n SPR2 = pygame.image.load(Sprite2).convert_alpha()\r\n spr2XSize, spr2YSize = SPR2.get_size()\r\n spr2XSizeBox = spr2XSize\r\n spr2XSizeBox -= decreasingHitBoxSizeXSize\r\n TricSurface = pygame.Surface((spr2XSize, spr2YSize), flags=SRCALPHA, depth=32)\r\n TricSurface.fill(TRANSP)\r\n\r\n #\r\n # Set Up for animation\r\n #\r\n\r\n LEFT = 'left'\r\n RIGHT = 'right'\r\n\r\n #\r\n # Rate of movement and attack\r\n #\r\n\r\n TrexWALKRATE = 5\r\n TrexSPRINTRATE = int(TrexWALKRATE * 1.6)\r\n TrexJumpRate = 9\r\n TrexJumpRateReSet = 9\r\n TrexHealth = 100\r\n TrexHealthDamageRate = 8.75\r\n TricWALKRATE = 3\r\n TricSPRINTRATE = int(TricWALKRATE * 1.6)\r\n TricJumpRate = 7\r\n TricJumpRateReSet = 7\r\n TricHealth = 100\r\n TricHealthDamageRate = 6.25\r\n bgXMoveRate = 2\r\n\r\n #\r\n # Set Up For Health Bars\r\n #\r\n\r\n TrexHealthBarX = 175\r\n TricHealthBarX = 525\r\n\r\n #\r\n # Setting animation variables\r\n #\r\n\r\n TrexDirection, TricDirection = RIGHT, LEFT\r\n Bite, Horn = 0, 0\r\n ForeGroundRightMax = ForeGroundLeftMax = touching = TrexWall = TricWall = TricRock = TrexRock = False\r\n TrexMoveLeft = TrexMoveRight = TrexWalking = BiteAttack = TrexJump = TrexRunning = TrexBlock = TrexDead = False\r\n TricMoveLeft = TricMoveRight = TricWalking = HornAttack = TricJump = TricRunning = TricBlock = TricDead = False\r\n TimeForFrame = 30\r\n TrexDeadCounter = TricDeadCounter = 0\r\n PlayGame = True\r\n TricWin = TrexWin = False\r\n soundGame.play(-1)\r\n\r\n while PlayGame:\r\n\r\n #Blits Background and Health Bars\r\n windowSurface.blit(ForeGround6, (bgX, bgY))\r\n windowSurface.blit(ForeGround5, (bgX, bgY))\r\n windowSurface.blit(ForeGround4, (bgX, bgY))\r\n windowSurface.blit(ForeGround3, (bgX, bgY))\r\n windowSurface.blit(ForeGround2, (bgX, bgY))\r\n windowSurface.blit(ForeGround1, (bgX, bgY))\r\n windowSurface.blit(Background,(bbX, bbY))\r\n HealthBars = HealthBar(TrexHealth, TricHealth, TrexHealthBarX, TricHealthBarX, windowSurface)\r\n HealthBars.DrawHB()\r\n\r\n #\r\n # Sets up Health Bars for damage\r\n #\r\n\r\n if TricHealth <= 0:\r\n HealthBars.DrawHB()\r\n if TricDeadCounter >= 60:\r\n print(1)\r\n pygame.time.delay(200)\r\n TrexWin = True\r\n PlayGame = False\r\n\r\n if TrexHealth <= 0:\r\n HealthBars.DrawHB()\r\n if TrexDeadCounter >= 60:\r\n pygame.time.delay(200)\r\n TricWin = True\r\n PlayGame = False\r\n\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n #\r\n # Trex Movement\r\n #\r\n\r\n if not TrexJump and not TrexBlock and not TrexDead:\r\n left = event.key == K_a\r\n if left:\r\n TrexMoveLeft = True\r\n TrexMoveRight = False\r\n TrexDirection = LEFT\r\n TrexWalking = True\r\n bgXMove = bgXMoveRate\r\n touching = False\r\n\r\n if not TrexJump and not TrexBlock and not TrexDead:\r\n if event.key == K_d:\r\n TrexMoveLeft = False\r\n TrexMoveRight = True\r\n TrexDirection = RIGHT\r\n TrexWalking = True\r\n bgXMove = -bgXMoveRate\r\n\r\n if not TrexRunning and not TrexBlock and not TrexJump and not TrexDead:\r\n TrexAttack = pygame.key.get_pressed()\r\n if TrexAttack[K_e]:\r\n if Bite == 0:\r\n BiteAttack = True\r\n Bite = TimeForFrame\r\n\r\n if not TrexDead:\r\n if event.key == K_f:\r\n BiteAttack = False\r\n TrexRunning = True\r\n if TrexMoveLeft:\r\n TrexDirection = LEFT\r\n if TrexMoveRight:\r\n TrexDirection = RIGHT\r\n\r\n if not TrexBlock and not TrexDead:\r\n TRexJump = pygame.key.get_pressed()\r\n if TRexJump[K_w]:\r\n TrexJump = True\r\n BiteAttack = False\r\n\r\n if not TrexJump and not TrexDead:\r\n if event.key == K_s:\r\n TrexBlock = True\r\n TrexMoveLeft = False\r\n TrexMoveRight = False\r\n BiteAttack = False\r\n TrexRunning = False\r\n TrexJump = False\r\n\r\n #\r\n # Triceratops Movement\r\n #\r\n\r\n if not TricJump and not TricBlock and not TricDead:\r\n if event.key == K_LEFT:\r\n TricMoveLeft = True\r\n TricMoveRight = False\r\n TricDirection = LEFT\r\n TricWalking = True\r\n bgXMove = bgXMoveRate\r\n\r\n if not TricJump and not TricBlock and not TricDead:\r\n if event.key == K_RIGHT:\r\n TricMoveLeft = False\r\n TricMoveRight = True\r\n TricDirection = RIGHT\r\n TricWalking = True\r\n bgXMove = -bgXMoveRate\r\n touching = False\r\n\r\n if not TricRunning and not TricBlock and not TricJump and not TricDead:\r\n TRicAttack = pygame.key.get_pressed()\r\n if TRicAttack[K_RCTRL]:\r\n if Horn == 0:\r\n HornAttack = True\r\n Horn = TimeForFrame\r\n\r\n if not TricDead:\r\n if event.key == K_KP0:\r\n HornAttack = False\r\n TricRunning = True\r\n if TricMoveLeft:\r\n TricDirection = LEFT\r\n if TricMoveRight:\r\n TricDirection = RIGHT\r\n\r\n if not TricBlock and not TricDead:\r\n TRicJump = pygame.key.get_pressed()\r\n if TRicJump[K_UP]:\r\n TricJump = True\r\n HornAttack = False\r\n\r\n if not TricJump and not TricDead:\r\n if event.key == K_DOWN:\r\n TricBlock = True\r\n TricMoveLeft = False\r\n TricMoveRight = False\r\n HornAttack = False\r\n TricRunning = False\r\n TricJump = False\r\n\r\n elif event.type == KEYUP:\r\n # Trex Stop Movement\r\n if not TrexMoveRight:\r\n if event.key == K_a:\r\n TrexMoveLeft = False\r\n TrexDirection = LEFT\r\n TrexWalking = False\r\n bgXMove = 0\r\n if not TrexMoveLeft:\r\n if event.key == K_d:\r\n TrexMoveRight = False\r\n TrexDirection = RIGHT\r\n TrexWalking = False\r\n bgXMove = 0\r\n\r\n if event.key == K_f:\r\n TrexRunning = False\r\n if TrexMoveLeft:\r\n TrexDirection = LEFT\r\n if TrexMoveRight:\r\n TrexDirection = RIGHT\r\n if event.key == K_s:\r\n TrexBlock = False\r\n\r\n #\r\n # Triceratops Stop Movement\r\n #\r\n\r\n if not TricMoveRight:\r\n if event.key == K_LEFT:\r\n TricMoveLeft = False\r\n TricDirection = LEFT\r\n TricWalking = False\r\n bgXMove = 0\r\n\r\n if not TricMoveLeft:\r\n if event.key == K_RIGHT:\r\n TricMoveRight = False\r\n TricDirection = RIGHT\r\n TricWalking = False\r\n bgXMove = 0\r\n\r\n if event.key == K_KP0:\r\n TricRunning = False\r\n if TricMoveLeft:\r\n TricDirection = LEFT\r\n if TricMoveRight:\r\n TricDirection = RIGHT\r\n if event.key == K_DOWN:\r\n TricBlock = False\r\n #\r\n # Trex Animation\r\n #\r\n\r\n Trex.playAnimation()\r\n #\r\n # Trex Animation\r\n #\r\n\r\n if TrexHealth <= 0:\r\n TrexDead = True\r\n TrexMoveLeft = False\r\n TrexMoveRight = False\r\n TrexWalking = False\r\n TrexRunning = False\r\n TrexBlock = False\r\n BiteAttack = False\r\n TrexJump = False\r\n\r\n if TrexMoveRight or TrexMoveLeft or BiteAttack or TrexJump or TrexBlock or TrexDead:\r\n if TrexWalking and(TrexMoveRight or TrexMoveLeft) and not BiteAttack and not TrexRunning and not TrexJump:\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, True, False, False, False, False, False, False)\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, True, False, False, False, False, False, False)\r\n TrexRate = TrexWALKRATE\r\n\r\n if BiteAttack and not TrexWalking:\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TrexRate = 0\r\n elif touching:\r\n TrexRate = 0\r\n bgXMove = 0\r\n else:\r\n TrexRate = bgXMove\r\n TrexX += TrexRate\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, False, True, False, False, False, False, False)\r\n if Bite <= TimeForFrame:\r\n Bite -= 1\r\n if Bite == (TimeForFrame - TimeForFrame):\r\n BiteAttack = False\r\n\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, False, True, False, False, False, False, False)\r\n if Bite <= TimeForFrame:\r\n Bite -= 1\r\n if Bite == (TimeForFrame - TimeForFrame):\r\n BiteAttack = False\r\n\r\n if TrexWalking and BiteAttack and(TrexMoveRight or TrexMoveLeft) and not TrexRunning:\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, True, True, False, False, False, False, False)\r\n if Bite <= TimeForFrame:\r\n Bite -= 1\r\n if Bite == (TimeForFrame - TimeForFrame):\r\n BiteAttack = False\r\n\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, True, True, False, False, False, False, False)\r\n if Bite <= TimeForFrame:\r\n Bite -= 1\r\n if Bite == (TimeForFrame - TimeForFrame):\r\n BiteAttack = False\r\n\r\n TrexRate = TrexWALKRATE\r\n\r\n if TrexRunning and(TrexMoveRight or TrexMoveLeft) and not TrexJump:\r\n Bite = 0\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, False, False, True, False, False, False, False)\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, False, False, True, False, False, False, False)\r\n TrexRate = TrexSPRINTRATE\r\n\r\n if TrexJump:\r\n Bite = 0\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TrexRate = 0\r\n elif touching:\r\n TrexRate = 0\r\n bgXMove = 0\r\n else:\r\n TrexRate = bgXMove\r\n TrexX += TrexRate\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, False, False, False, True, False, False, False)\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, False, False, False, True, False, False, False)\r\n if TrexMoveLeft or TrexMoveRight:\r\n if not touching:\r\n if TrexRunning:\r\n TrexRate = int(TrexSPRINTRATE//1.75)\r\n else:\r\n TrexRate = int(TrexWALKRATE//1.5)\r\n\r\n if TrexBlock:\r\n Bite = 0\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TrexRate = 0\r\n elif touching:\r\n TrexRate = 0\r\n bgXMove = 0\r\n else:\r\n TrexRate = bgXMove\r\n TrexX += TrexRate\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, False, False, False, False, True, False, False)\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, False, False, False, False, True, False, False)\r\n\r\n if TrexDead:\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TrexRate = 0\r\n elif touching:\r\n TrexRate = 0\r\n bgXMove = 0\r\n else:\r\n TrexRate = bgXMove\r\n TrexX += TrexRate\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, False, False, False, False, False, False, True)\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, False, False, False, False, False, False, True)\r\n\r\n TrexDeadCounter += 1\r\n\r\n if TrexMoveLeft:\r\n TrexX -= TrexRate\r\n if TrexMoveRight:\r\n TrexX += TrexRate\r\n if TrexJump:\r\n if TrexY <= ground:\r\n TrexY = TrexY - TrexJumpRate\r\n TrexJumpRate = TrexJumpRate - gravity\r\n if TrexY == ground:\r\n TrexJump = False\r\n TrexJumpRate = TrexJumpRateReSet\r\n\r\n else:\r\n\r\n #\r\n # Trex Standing\r\n #\r\n\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TrexRate = 0\r\n elif touching:\r\n TrexRate = 0\r\n bgXMove = 0\r\n else:\r\n TrexRate = bgXMove\r\n TrexX += TrexRate\r\n if TrexDirection == LEFT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, LEFT, False, False, False, False, False, True, False)\r\n elif TrexDirection == RIGHT:\r\n Trex.Animation(windowSurface, TrexX, TrexY, RIGHT, False, False, False, False, False, True, False)\r\n\r\n #\r\n # Triceratops Animation\r\n #\r\n\r\n Tric.playAnimation()\r\n\r\n if TricHealth <= 0:\r\n TricDead = True\r\n TricMoveLeft = False\r\n TricMoveRight = False\r\n TricWalking = False\r\n TricRunning = False\r\n TricBlock = False\r\n HornAttack = False\r\n TricJump = False\r\n\r\n if TricMoveRight or TricMoveLeft or HornAttack or TricJump or TricBlock or TricDead:\r\n if TricWalking and(TricMoveRight or TricMoveLeft) and not HornAttack and not TricRunning and not TricJump:\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, True, False, False, False, False, False, False)\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, True, False, False, False, False, False, False)\r\n TricRate = TricWALKRATE\r\n\r\n if HornAttack and not TricWalking:\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TricRate = 0\r\n elif touching:\r\n TricRate = 0\r\n bgXMove = 0\r\n else:\r\n TricRate = bgXMove\r\n TricX += TricRate\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, False, True, False, False, False, False, False)\r\n if Horn <= TimeForFrame:\r\n Horn -= 1\r\n if Horn == (TimeForFrame - TimeForFrame):\r\n HornAttack = False\r\n elif TricDirection == RIGHT:\r\n TricX += TricRate\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, False, True, False, False, False, False, False)\r\n if Horn <= TimeForFrame:\r\n Horn -= 1\r\n if Horn == (TimeForFrame - TimeForFrame):\r\n HornAttack = False\r\n\r\n if HornAttack and TricWalking and (TricMoveRight or TricMoveLeft) and not TricRunning:\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, True, True, False, False, False, False, False)\r\n if Horn <= TimeForFrame:\r\n Horn -= 1\r\n if Horn == (TimeForFrame - TimeForFrame):\r\n HornAttack = False\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, True, True, False, False, False, False, False)\r\n if Horn <= TimeForFrame:\r\n Horn -= 1\r\n if Horn == (TimeForFrame - TimeForFrame):\r\n HornAttack = False\r\n\r\n if TricRunning and(TricMoveRight or TricMoveLeft) and not TricJump:\r\n Horn = 0\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, False, False, True, False, False, False, False)\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, False, False, True, False, False, False, False)\r\n TricRate = TricSPRINTRATE\r\n if TricJump:\r\n Horn = 0\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TricRate = 0\r\n elif touching:\r\n TricRate = 0\r\n bgXMove = 0\r\n else:\r\n TricRate = bgXMove\r\n TricX += TricRate\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, False, False, False, True, False, False, False)\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, False, False, False, True, False, False, False)\r\n if TricMoveLeft or TricMoveRight:\r\n if not touching:\r\n if TricRunning:\r\n TricRate = int(TricSPRINTRATE//1.75)\r\n else:\r\n TricRate = int(TricWALKRATE//1.5)\r\n\r\n if TricBlock:\r\n Horn = 0\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TricRate = 0\r\n elif touching:\r\n TricRate = 0\r\n bgXMove = 0\r\n else:\r\n TricRate = bgXMove\r\n TricX += TricRate\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, False, False, False, False, True, False, False)\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, False, False, False, False, True, False, False)\r\n\r\n if TricDead:\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TricRate = 0\r\n elif touching:\r\n TricRate = 0\r\n bgXMove = 0\r\n else:\r\n TricRate = bgXMove\r\n TricX += TricRate\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, False, False, False, False, False, False, True)\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, False, False, False, False, False, False, True)\r\n TricDeadCounter += 1\r\n else:\r\n if bgX == bgXRightMax or bgX == bgXLeftMax:\r\n TricRate = 0\r\n elif touching:\r\n TricRate = 0\r\n bgXMove = 0\r\n else:\r\n TricRate = bgXMove\r\n TricX += TricRate\r\n if TricDirection == LEFT:\r\n Tric.Animation(windowSurface, TricX, TricY, LEFT, False, False, False, False, False, True, False)\r\n elif TricDirection == RIGHT:\r\n Tric.Animation(windowSurface, TricX, TricY, RIGHT, False, False, False, False, False, True, False)\r\n\r\n if TricMoveLeft:\r\n TricX -= TricRate\r\n if TricMoveRight:\r\n TricX += TricRate\r\n if TricJump:\r\n if TricY <= ground:\r\n TricY = TricY - TricJumpRate\r\n TricJumpRate = TricJumpRate - gravity\r\n if TricY == ground:\r\n TricJump = False\r\n TricJumpRate = TricJumpRateReSet\r\n\r\n #\r\n # Trex Sprite Stuff\r\n #\r\n\r\n spr1XPos, spr1YPos = TrexX, TrexY\r\n TrexSurface.blit(windowSurface, (spr1XPos, spr1YPos))\r\n\r\n #\r\n # Tric Sprite Stuff\r\n #\r\n\r\n spr2XPos, spr2YPos = TricX, TricY\r\n TrexSurface.blit(windowSurface, (spr2XPos, spr2YPos))\r\n\r\n #\r\n # BackGroundLimits\r\n #\r\n\r\n if TricMoveRight and TrexMoveLeft:\r\n if TrexWall and TricWall:\r\n bgXMove = 0\r\n if TrexJump ^ TricJump:\r\n bgXMove = 0\r\n bgX = bgX + bgXMove\r\n if bgX <= bgXRightMax:\r\n bgX = bgXRightMax\r\n elif bgX <= bgXRightMax + rightEdgePlusRockMax:\r\n ForeGroundRightMax = True\r\n elif bgX >= bgXRightMax + rightEdgePlusRockMax:\r\n ForeGroundRightMax = False\r\n if bgX > bgXLeftMax:\r\n bgX = bgXLeftMax\r\n elif bgX > -leftRockEdge:\r\n ForeGroundLeftMax = True\r\n elif bgX < -leftRockEdge:\r\n ForeGroundLeftMax = False\r\n\r\n #\r\n # Trex Limits\r\n #\r\n\r\n if not ForeGroundLeftMax:\r\n if spr1XPos <= 0:\r\n TrexX = 0\r\n TrexWall = True\r\n else:\r\n TrexWall = False\r\n elif TrexDirection == LEFT and TrexMoveLeft and TrexWall:\r\n if spr1XPos <= leftRockEdge:\r\n TrexX = leftRockEdge + bgX\r\n TrexRock = True\r\n elif TrexDirection == RIGHT:\r\n TrexRock = False\r\n elif TrexDirection == LEFT and TrexMoveLeft and TrexRock:\r\n if spr1XPos <= leftRockEdge + bgX:\r\n TrexX = leftRockEdge + bgX\r\n elif TrexDirection == LEFT and TrexMoveLeft and not TrexRock:\r\n if spr1XPos <= leftRockEdge + bgX:\r\n TrexX = leftRockEdge + bgX\r\n else:\r\n TrexWall = False\r\n\r\n #\r\n # Tric Limits\r\n #\r\n\r\n if not ForeGroundRightMax:\r\n if spr2XPos >= WindowWidth - spr2XSizeBox:\r\n TricX = WindowWidth - spr2XSizeBox\r\n TricWall = True\r\n else:\r\n TricWall = False\r\n elif TricDirection == RIGHT and TricMoveRight and TricWall:\r\n if spr2XPos >= WindowWidth - spr2XSize - rightRockEdge:\r\n TricX = WindowWidth - spr2XSize - rightRockEdge + (-bgXRightMax + bgX)\r\n TricRock = True\r\n elif TricDirection == LEFT:\r\n TricRock = False\r\n elif TricDirection == RIGHT and TricMoveRight and TricRock:\r\n if spr2XPos >= WindowWidth - spr2XSize - rightRockEdge:\r\n TricX = WindowWidth - spr2XSize - rightRockEdge + (-bgXRightMax + bgX)\r\n elif TricDirection == RIGHT and TricMoveRight and not TricRock:\r\n if spr2XPos >= WindowWidth - spr2XSize - rightRockEdge + (-bgXRightMax + bgX):\r\n TricX = WindowWidth - spr2XSize - rightRockEdge + (-bgXRightMax + bgX)\r\n else:\r\n TricWall = False\r\n\r\n #\r\n # Hit Boxes Set Up\r\n #\r\n\r\n if spr1XPos + spr1XSizeBox >= spr2XPos:\r\n touching = True\r\n if spr2XPos >= spr1XPos + spr1XSizeBox and TricMoveRight:\r\n touching = False\r\n if touching:\r\n TrexX = TrexX - TrexRate\r\n TricX = TricX + TricRate\r\n bgX = bgX - bgXMove\r\n if touching and BiteAttack and TrexDirection == RIGHT:\r\n if Bite == int(TimeForFrame//1.75):\r\n if TricBlock:\r\n TricHealth -= int(TricHealthDamageRate//4)\r\n elif TricJump:\r\n if TricY <= 235:\r\n TricHealth -= 0\r\n else:\r\n TricHealth -= TricHealthDamageRate\r\n else:\r\n TricHealth -= TricHealthDamageRate\r\n if touching and HornAttack and TricDirection == LEFT:\r\n if Horn == int(TimeForFrame//1.75):\r\n if TrexBlock:\r\n TrexHealth -= int(TrexHealthDamageRate//3)\r\n elif TrexJump:\r\n if TrexY <= 225:\r\n TrexHealth -= 0\r\n else:\r\n TrexHealth -= TrexHealthDamageRate\r\n else:\r\n TrexHealth -= TrexHealthDamageRate\r\n pygame.display.update()\r\n mainClock.tick(TimeForFrame)\r\n\r\n #\r\n # Set up for Win Screens\r\n #\r\n\r\n if TrexWin or TricWin:\r\n soundGame.stop()\r\n endScreenSound.play(-1)\r\n while TrexWin:\r\n WinScreen.TrexWin(windowSurface, True)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_SPACE:\r\n titleScreen = True\r\n endScreenSound.stop()\r\n TrexWin = False\r\n while TricWin:\r\n WinScreen.TricWin(windowSurface, True)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_SPACE:\r\n titleScreen = True\r\n endScreenSound.stop()\r\n TricWin = False\r\nmain()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"old_assets/Jurrastic Measures(Main Code).py","file_name":"Jurrastic Measures(Main Code).py","file_ext":"py","file_size_in_byte":33524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"341779030","text":"#test\n#Import libraries required for modelling\nimport numpy as np\nimport pickle\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\n\n# Setting up step function for power change\n# Note that for the purposes of DRL this could be any signal\ndef del_p_L_1_func(t):\n if (t < 15):\n del_p_L = 0.00\n else:\n del_p_L = 0.01\n return del_p_L\n\ndef del_p_L_2_func(t):\n if (t < 1):\n del_p_L = 0.00\n else:\n del_p_L = 0.00\n return del_p_L\n\n# Setting up first order model for power system\ndef int_power_system_sim(x_sys, t,\n control_sig_1, control_sig_2, # control sig\n K_sg_1, T_sg_1, K_t_1, T_t_1, K_gl_1, T_gl_1, # area one\n K_sg_2, T_sg_2, K_t_2, T_t_2, K_gl_2, T_gl_2, # area two\n T12): # tie line\n # area 1 simulation\n x_2_dot = (1/T_sg_1)*(K_sg_1*control_sig_1 - x_sys[0])\n x_3_dot = (1/T_t_1)*(K_t_1*x_sys[0] - x_sys[1])\n x_4_dot = (K_gl_1/T_gl_1)*(x_sys[1] - x_sys[3] - del_p_L_1_func(t)) - (1/T_gl_1)*x_sys[2]\n\n # tie line simulation\n x_5_dot = 2*np.pi*T12*(x_sys[2] - x_sys[6])\n\n # area 2 simulation\n x_7_dot = (1/T_sg_2)*(K_sg_2*control_sig_2 - x_sys[4])\n x_8_dot = (1/T_t_2)*(K_t_2*x_sys[4] - x_sys[5])\n x_9_dot = (K_gl_2/T_gl_2)*(x_sys[5] + x_sys[3] - del_p_L_2_func(t)) - (1/T_gl_2)*x_sys[6]\n\n return x_2_dot, x_3_dot, x_4_dot, x_5_dot, x_7_dot, x_8_dot, x_9_dot\n\n# Setting up first order model for controller\ndef int_control_system_sim(x_control_sys, t,\n frequency_sig_1, frequency_sig_2, # freq sig\n tie_line_sig, # tie line sig\n R_1, K_i_1, b_1, # area one\n R_2, K_i_2, b_2): # area two\n\n # controller 1 simulation\n x_1_dot = K_i_1*(tie_line_sig + b_1*frequency_sig_1)\n\n # controller 2 simulation\n x_6_dot = K_i_2*(-tie_line_sig + b_2*frequency_sig_2)\n\n return x_1_dot, x_6_dot\n\n\n##################################################################\n# Main function that is executed when file called from terminal\n##################################################################\ndef main():\n ###############################################\n # Initialise system parameters\n ###############################################\n\n # Set model constants for area 1\n K_i_1 = -0.671\n b_1 = 0.425\n K_sg_1 = 1\n T_sg_1 = 0.08\n R_1 = 2.4\n K_t_1 = 1\n T_t_1 = 0.3\n K_gl_1 = 120\n T_gl_1 = 20\n\n # Set model constants for area 2\n K_i_2 = -0.671\n b_2 = 0.425\n K_sg_2 = 1\n T_sg_2 = 0.08\n R_2 = 2.4\n K_t_2 = 1\n T_t_2 = 0.3\n K_gl_2 = 120\n T_gl_2 = 20\n\n # Synchronising coefficient on tie line\n T12 = 0.1\n ###############################################\n\n ###############################################\n # Initialise simulation\n ###############################################\n\n # Set timesteps for sinulation to integrate over\n delta_t = 0.01 # time step size (seconds)\n t_max = 30 # max sim time (seconds)\n\n # Set variable initial conditions\n x_1_0 = 0.0 # x_control_sys[0]\n x_2_0 = 0.0 # x_sys[0]\n x_3_0 = 0.0 # x_sys[1]\n x_4_0 = 0.0 # x_freq_1\n x_5_0 = 0.0 # x_sys[3]\n x_6_0 = 0.0 # x_control_sys[1]\n x_7_0 = 0.0 # x_sys[4]\n x_8_0 = 0.0 # x_sys[5]\n x_9_0 = 0.0 # x_freq_2\n\n x_sys = (x_2_0, x_3_0, x_4_0, x_5_0, x_7_0, x_8_0, x_9_0) # initialise sys\n x_freq_1 = x_4_0 # initialise freq_1\n x_freq_2 = x_9_0 # initialise freq_2\n x_tie_line = x_5_0 # initialise tieline\n x_control_sys = (x_1_0, x_6_0) # initialise int control input\n x_control = (x_1_0 - (1/R_1)*x_4_0, x_6_0 - (1/R_2)*x_9_0) # initialise controller signal\n\n # initialise empty list to store simulation output\n out_s_1 = [x_freq_1]\n out_s_2 = [x_freq_2]\n control_s_1 = [x_control_sys[0]]\n control_s_2 = [x_control_sys[1]]\n demand = [0]\n\n # initialise the time\n t = 0\n time = [t]\n\n while t < t_max:\n\n # step foward in time\n t_step = t + delta_t\n\n ##############################################################\n # step the system simulation forward in time\n ##############################################################\n\n # arguement tuple\n arg_sys = (x_control[0], x_control[1], # control signals\n K_sg_1, T_sg_1, K_t_1, T_t_1, K_gl_1, T_gl_1, # area one\n K_sg_2, T_sg_2, K_t_2, T_t_2, K_gl_2, T_gl_2, # area two\n T12) # tie line\n\n # time step simulation\n x_sys_vals = integrate.odeint(int_power_system_sim, # ode system\n x_sys, # initial cond\n np.array([t, t_step]), # time step\n args=arg_sys) # model args\n\n # save the new init values for the system\n x_2 = x_sys_vals[1,0]\n x_3 = x_sys_vals[1,1]\n x_freq_1 = x_sys_vals[1,2] # (area 1 frequency)\n x_tie_line = x_sys_vals[1,3] # (tie line power)\n x_7 = x_sys_vals[1,4]\n x_8 = x_sys_vals[1,5]\n x_freq_2 = x_sys_vals[1,6] # (area 2 frequency)\n\n # create new x_sys\n x_sys = (x_2, x_3, x_freq_1, x_tie_line, x_7, x_8, x_freq_2)\n ##############################################################\n\n ##############################################################\n # step the control simulation forward in time\n ##############################################################\n\n # arguement tuple\n arg_control = (x_freq_1, x_freq_2, # freq sig\n x_tie_line, # tie line sig\n R_1, K_i_1, b_1, # area one\n R_2, K_i_2, b_2)\n\n # time step simulation\n x_control_vals = integrate.odeint(int_control_system_sim, # ode system\n x_control_sys, # initial cond\n np.array([t, t_step]), # time step\n args=arg_control) # model args\n\n # save the new init values for the controller\n x_control_sys = (x_control_vals[1,0], x_control_vals[1,1])\n\n # create new x_control\n x_control = (x_control_sys[0] - (1/R_1)*x_freq_1,\n x_control_sys[1] - (1/R_2)*x_freq_2)\n ##############################################################\n\n # save the output\n out_s_1.append(x_freq_1)\n out_s_2.append(x_freq_2)\n control_s_1.append(x_control[0])\n control_s_2.append(x_control[1])\n demand.append(del_p_L_1_func(t))\n\n # ste t to the next time step\n t = t_step\n time.append(t)\n\n plt.subplot(311)\n plt.plot(time, out_s_1)\n plt.plot(time, out_s_2)\n plt.subplot(312)\n plt.plot(time, control_s_1)\n plt.subplot(313)\n plt.plot(time, control_s_2)\n plt.show()\n\n dump = [time, out_s_1, out_s_2, control_s_1, control_s_2, demand]\n\n with open('dump.pkl', 'wb') as f:\n pickle.dump(dump, f)\n\n# Execute the main() function if run from the terminal\nif __name__ == '__main__':\n main()","sub_path":"01_development/02_two_area_models/02_PI_control/02_two_area_model_PI_control_seg_iterative.py","file_name":"02_two_area_model_PI_control_seg_iterative.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"394827200","text":"import pycuda.autoinit\nfrom pycuda import gpuarray\nimport pycuda.driver as drv\nfrom skcuda import cublas\nimport numbers\nimport numpy as np\nfrom pycuda.reduction import ReductionKernel\nfrom pycuda.elementwise import ElementwiseKernel\nfrom pycuda.compiler import SourceModule\nfrom skcuda import misc, linalg\n\n_global_cublas_allocator = drv.mem_alloc\n_global_cublas_handle = cublas.cublasCreate()\n\nsigmoid_float_ker = ElementwiseKernel(\n f\"float *Y, float *x\",\n \"Y[i] = 1.0 / (1.0 + exp (-x[i]) )\",\n \"sigmoid_float\")\n\nsigmoid_double_ker = ElementwiseKernel(\n f\"double *Y, double *x\",\n \"Y[i] = 1.0 / (1.0 + exp (-x[i]) )\",\n \"sigmoid_double\")\n\ntanh_float_ker = ElementwiseKernel(\n f\"float *Y, float *x\",\n \"\"\"\n Y[i] = tanh(x[i])\n \"\"\",\n \"tanh_float\")\n\ntanh_double_ker = ElementwiseKernel(\n f\"double *Y, double *x\",\n \"\"\"\n double pos_exp = exp (x[i]);\n double neg_exp = exp (-x[i]);\n Y[i] = (pos_exp - neg_exp) / (pos_exp + neg_exp)\n \"\"\",\n \"tanh_double\"\n)\n\nexp_sum_float_ker = ReductionKernel(np.float32, neutral=\"0.0\",\n reduce_expr=\"a+b\", map_expr=\"exp (x[i])\",\n arguments=f\"float *x\"\n )\n\nsoftmax_float_ker = ElementwiseKernel(\n f\"float *Y, float *x, float s\",\n \"Y[i] = exp (x[i]) / s\",\n \"softmax_float\"\n)\n\nexp_sum_double_ker = ReductionKernel(np.float32, neutral=\"0.0\",\n reduce_expr=\"a+b\", map_expr=\"exp (x[i])\",\n arguments=f\"double *x\"\n )\n\nsoftmax_double_ker = ElementwiseKernel(\n f\"double *Y, double *x, double s\",\n \"Y[i] = exp (x[i]) / s\",\n \"softmax_double\"\n)\n\nexp_float_ker = ElementwiseKernel(\n arguments=f\"float *inp, float *out\",\n operation=f\"out[i] = exp(inp[i])\",\n name='exp_float_ker',\n)\n\nexp_double_ker = ElementwiseKernel(\n arguments=f\"double *inp, double *out\",\n operation=f\"out[i] = exp(inp[i])\",\n name='exp_double_ker',\n)\n\nsquare_float_ker = ElementwiseKernel(\n f\"float *Y, float *x\",\n \"Y[i] = x[i] * x[i]\",\n \"square_float_ker\")\n\nsquare_double_ker = ElementwiseKernel(\n f\"double *Y, double *x\",\n \"Y[i] = x[i] * x[i]\",\n \"square_double_ker\")\n\nsigmoid_grad_float_ker = ElementwiseKernel(\n arguments=f\"float *inp, float *out\",\n operation=\"out[i] = inp[i] * (1.0 - inp[i])\",\n name=\"sigmoid_grad_float_ker\",\n)\n\nsigmoid_grad_double_ker = ElementwiseKernel(\n arguments=f\"double *inp, double *out\",\n operation=\"out[i] = inp[i] * (1.0 - inp[i])\",\n name=\"sigmoid_grad_double_ker\",\n)\n\ntanh_grad_float_ker = ElementwiseKernel(\n arguments=\"float *inp, float *out\",\n operation=\"out[i] = 1.0 - inp[i] * inp[i]\",\n name=\"tanh_grad_float_ker\",\n)\n\ntanh_grad_double_ker = ElementwiseKernel(\n arguments=\"double *inp, double *out\",\n operation=\"out[i] = 1.0 - inp[i] * inp[i]\",\n name=\"tanh_grad_double_ker\",\n)\n\nrelu_float_ker = ElementwiseKernel(\n arguments=\"float *inp, float *out\",\n operation=\"out[i] = (inp[i] > 0) ? inp[i] : 0\",\n name=\"relu_float_ker\",\n)\n\nrelu_double_ker = ElementwiseKernel(\n arguments=\"double *inp, double *out\",\n operation=\"out[i] = (inp[i] > 0) ? inp[i] : 0\",\n name=\"relu_double_ker\",\n)\n\nrelu_grad_float_ker = ElementwiseKernel(\n arguments=\"float *inp, float *out\",\n operation=\"out[i] = (inp[i] > 0) ? 1 : 0\",\n name=\"relu_grad_float_ker\",\n)\n\nrelu_grad_double_ker = ElementwiseKernel(\n arguments=\"double *inp, double *out\",\n operation=\"out[i] = (inp[i] > 0) ? 1 : 0\",\n name=\"relu_grad_double_ker\",\n)\n\n# random kernel\n\nrandom_ker_template = \"\"\"\n#include \n#define ULL unsigned long long\nextern \"C\" {\n __global__ void random_%(p)s_array(%(p)s *arr, int array_len, %(p)s p) {\n curandState cr_state; \n int tid = blockIdx.x * blockDim.x + threadIdx.x;\n int num_iters = (array_len - 1) / blockDim.x + 1;\n curand_init( (ULL) clock() + (ULL) tid, (ULL) 0, (ULL) 0, &cr_state);\n %(p)s x;\n for (int j = 0; j < num_iters; j++) {\n int i = j * blockDim.x + tid;\n if (i < array_len) {\n x = curand_uniform%(p_curand)s(&cr_state);\n if (x < p) arr[i] = 0;\n else arr[i] = 1.0 / (1 - p);\n }\n }\n }\n}\n\"\"\"\n\nrandom_float_func = SourceModule(\n no_extern_c=True,\n source=random_ker_template % {'p': 'float', 'p_curand': ''}\n).get_function('random_float_array')\n\nrandom_double_func = SourceModule(\n no_extern_c=True,\n source=random_ker_template % {'p': 'double', 'p_curand': '_double'}\n).get_function('random_double_array')\n\nrandom_lstm_ker_template = \"\"\"\n#include \n#define ULL unsigned long long\nextern \"C\" {\n __global__ void random_lstm_%(p)s_array(%(p)s *array, int dim, float p) {\n curandState cr_state; \n int row = blockIdx.x * blockDim.x + threadIdx.x;\n curand_init( (ULL) clock() + (ULL) row, (ULL) 0, (ULL) 0, &cr_state);\n float x = curand_uniform(&cr_state); \n %(p)s v;\n if (x < p) v = 0;\n else v = 1;\n for (int i = row * dim; i < (row + 1) * dim; i++) {\n array[i] = v;\n }\n return;\n }\n}\n\"\"\"\n\nrandom_lstm_int_func = SourceModule(\n no_extern_c=True,\n source=random_lstm_ker_template % {'p': 'int'}\n).get_function('random_lstm_int_array')\n\nrandom_lstm_float_func = SourceModule(\n no_extern_c=True,\n source=random_lstm_ker_template % {'p': 'float'}\n).get_function('random_lstm_float_array')\n\nrandom_lstm_double_func = SourceModule(\n no_extern_c=True,\n source=random_lstm_ker_template % {'p': 'double'}\n).get_function('random_lstm_double_array')\n\nnorm_float_gpu = ReductionKernel(\n dtype_out=np.float32,\n neutral='0',\n reduce_expr=\"a + b\",\n map_expr=\"x[i] * x[i]\",\n arguments=\"float *x\",\n name='norm',\n)\n\nnorm_double_gpu = ReductionKernel(\n dtype_out=np.float64,\n neutral='0',\n reduce_expr=\"a + b\",\n map_expr=\"x[i] * x[i]\",\n arguments=\"double *x\",\n name='norm',\n)\n\nnorm_int_gpu = ReductionKernel(\n dtype_out=np.int32,\n neutral='0',\n reduce_expr=\"a + b\",\n map_expr=\"x[i] * x[i]\",\n arguments=\"int *x\",\n name='norm',\n)\n\n\ndef ones(shape: tuple, dtype: np.dtype, order: str = 'C', allocator=drv.mem_alloc):\n \"\"\"\n Return an array of the given shape and dtype filled with ones.\n\n Parameters\n ----------\n shape : tuple\n Array shape.\n dtype : data-type\n Data type for the array.\n order : {'C', 'F'}, optional\n Create array using row-major or column-major format.\n allocator : callable, optional\n Returns an object that represents the memory allocated for\n the requested array.\n\n Returns\n -------\n out : pycuda.gpuarray.GPUArray\n Array of ones with the given shape, dtype, and order.\n \"\"\"\n\n out = gpuarray.GPUArray(shape, dtype, allocator, order=order)\n o = np.ones((), dtype)\n out.fill(o)\n return out\n\n\ndef sum_gpu(\n x_gpu: gpuarray.GPUArray,\n axis: int = None,\n out: gpuarray.GPUArray = None,\n keepdims: bool = False,\n calc_mean: bool = False,\n ddof: int = 0\n) -> gpuarray.GPUArray:\n \"\"\"\n Compute the sum along the specified axis.\n\n Parameters\n ----------\n ddof\n calc_mean\n x_gpu : pycuda.gpuarray.GPUArray\n Array containing numbers whose sum is desired.\n axis : int (optional)\n Axis along which the sums are computed. The default is to\n compute the sum of the flattened array.\n out : pycuda.gpuarray.GPUArray (optional)\n Output array in which to place the result.\n keepdims : bool (optional, default False)\n If True, the axes which are reduced are left in the result as\n dimensions with size one.\n\n Returns\n -------\n out : pycuda.gpuarray.GPUArray\n sum of elements, or sums of elements along the desired axis.\n \"\"\"\n assert isinstance(ddof, numbers.Integral)\n\n if axis is None or len(x_gpu.shape) <= 1:\n out_shape = (1,) * len(x_gpu.shape) if keepdims else ()\n if calc_mean is False:\n return gpuarray.sum(x_gpu).reshape(out_shape)\n else:\n return gpuarray.sum(x_gpu).reshape(out_shape) / (x_gpu.dtype.type(x_gpu.size - ddof))\n\n if axis < 0:\n axis += 2\n if axis > 1:\n raise ValueError('invalid axis')\n\n if x_gpu.flags.c_contiguous:\n n, m = x_gpu.shape[1], x_gpu.shape[0]\n lda = x_gpu.shape[1]\n trans = \"n\" if axis == 0 else \"t\"\n sum_axis, out_axis = (m, n) if axis == 0 else (n, m)\n else:\n n, m = x_gpu.shape[0], x_gpu.shape[1]\n lda = x_gpu.shape[0]\n trans = \"t\" if axis == 0 else \"n\"\n sum_axis, out_axis = (n, m) if axis == 0 else (m, n)\n\n if calc_mean:\n alpha = (1.0 / (sum_axis - ddof))\n else:\n alpha = 1.0\n if x_gpu.dtype == np.complex64:\n gemv = cublas.cublasCgemv\n elif x_gpu.dtype == np.float32:\n gemv = cublas.cublasSgemv\n elif x_gpu.dtype == np.complex128:\n gemv = cublas.cublasZgemv\n elif x_gpu.dtype == np.float64:\n gemv = cublas.cublasDgemv\n else:\n raise Exception('invalid dtype')\n\n alloc = _global_cublas_allocator\n ons = ones((sum_axis,), x_gpu.dtype, allocator=alloc)\n\n if keepdims:\n out_shape = (1, out_axis) if axis == 0 else (out_axis, 1)\n else:\n out_shape = (out_axis,)\n\n if out is None:\n out = gpuarray.empty(out_shape, x_gpu.dtype, alloc)\n else:\n assert out.dtype == x_gpu.dtype\n assert out.size >= out_axis\n\n gemv(_global_cublas_handle, trans, n, m,\n alpha, x_gpu.gpudata, lda,\n ons.gpudata, 1, 0.0, out.gpudata, 1)\n return out\n\n\ndef tanh_gpu(x: gpuarray.GPUArray) -> gpuarray.GPUArray:\n tanh = tanh_float_ker if x.dtype == np.float32 else tanh_double_ker\n y = pycuda.gpuarray.empty_like(x)\n tanh(y, x)\n return y\n\n\ndef tanh_grad_gpu(x: gpuarray.GPUArray) -> gpuarray.GPUArray:\n tanh_grad = tanh_grad_float_ker if x.dtype == np.float32 else tanh_grad_double_ker\n y = gpuarray.empty_like(x)\n tanh_grad(x, y)\n return y\n\n\ndef sigmoid_gpu(x: gpuarray.GPUArray, out: gpuarray.GPUArray = None) -> gpuarray.GPUArray:\n sigmoid = sigmoid_float_ker if x.dtype == np.float32 else sigmoid_double_ker\n if out is None:\n y = pycuda.gpuarray.empty_like(x)\n else:\n y = out\n sigmoid(y, x)\n return y\n\n\ndef sigmoid_grad_gpu(x: gpuarray.GPUArray, out: gpuarray.GPUArray = None) -> gpuarray.GPUArray:\n sigmoid_grad = sigmoid_grad_float_ker if x.dtype == np.float32 else sigmoid_grad_double_ker\n if out is None:\n y = gpuarray.empty_like(x)\n else:\n y = out\n sigmoid_grad(x, y)\n return y\n\n\ndef relu_gpu(x: gpuarray.GPUArray):\n relu = relu_float_ker if x.dtype == np.float32 else relu_double_ker\n y = gpuarray.empty_like(x)\n relu(x, y)\n return y\n\n\ndef relu_grad_gpu(x: gpuarray.GPUArray):\n relu_grad = relu_grad_float_ker if x.dtype == np.float32 else relu_grad_double_ker\n y = gpuarray.empty_like(x)\n relu_grad(x, y)\n return y\n\n\ndef softmax_gpu(x: gpuarray.GPUArray, out: gpuarray.GPUArray = None) -> gpuarray.GPUArray:\n if x.dtype == np.float32:\n exp_sum = exp_sum_float_ker\n softmax = softmax_float_ker\n else:\n exp_sum = exp_sum_double_ker\n softmax = softmax_double_ker\n if y is None:\n y = pycuda.gpuarray.empty_like(x)\n else:\n y = out\n s = exp_sum(x).get()\n softmax(y, x, s)\n return y\n\n\n# expand gpu\nexpand_dim1_template = \"%(p)s *in, %(p)s *out, int copies\"\nexpand_dim1_float_ker = ElementwiseKernel(\n arguments=expand_dim1_template % {'p': 'float'},\n operation=\"for (int n = 0; n < copies; n++) out[i * copies + n] = in[i]\",\n name=\"expand_dim1_float_ker\",\n)\nexpand_dim1_double_ker = ElementwiseKernel(\n arguments=expand_dim1_template % {'p': 'double'},\n operation=\"for (int n = 0; n < copies; n++) out[i * copies + n] = in[i]\",\n name=\"expand_dim1_double_ker\",\n)\n\nexpand_dim1_v2_template = \"%(p)s *out, %(p)s *inp, int copies\"\nexpand_dim1_float_v2_ker = ElementwiseKernel(\n arguments=expand_dim1_v2_template % {'p': 'float'},\n operation=\"out[i] = inp[i / copies]\",\n name=\"expand_dim1_float_v2\",\n)\n\nexpand_dim1_double_v2_ker = ElementwiseKernel(\n arguments=expand_dim1_v2_template % {'p': 'double'},\n operation=\"out[i] = inp[i / copies]\",\n name=\"expand_dim1_double_v2\",\n)\n\nexpand_dim0_template = \"%(p)s *in, %(p)s *out, int copies, int width\"\nexpand_dim0_float_ker = ElementwiseKernel(\n arguments=expand_dim0_template % {'p': 'float'},\n operation=\"for (int n = 0; n < copies; n++) out[n * width + i] = in[i]\",\n name=\"expand_dim0_float_ker\",\n)\nexpand_dim0_double_ker = ElementwiseKernel(\n arguments=expand_dim0_template % {'p': 'double'},\n operation=\"for (int n = 0; n < copies; n++) out[n * width + i] = in[i]\",\n name=\"expand_dim0_double_ker\",\n)\n\nexpand_dim0_v2_template = \"%(p)s *out, %(p)s *inp, int width\"\nexpand_dim0_float_v2_ker = ElementwiseKernel(\n arguments=expand_dim0_v2_template % {'p': 'float'},\n operation=\"out[i] = inp[i % width]\",\n name=\"expand_dim0_float_v2\",\n)\nexpand_dim0_double_v2_ker = ElementwiseKernel(\n arguments=expand_dim0_v2_template % {'p': 'double'},\n operation=\"out[i] = inp[i % width]\",\n name=\"expand_dim0_double_v2\",\n)\n\nexpand_ker = {\n \"v1\": {\n 0: {\n np.float32: expand_dim0_float_ker,\n np.float64: expand_dim0_double_ker,\n },\n 1: {\n np.float32: expand_dim1_float_ker,\n np.float64: expand_dim1_double_ker,\n }\n },\n \"v2\": {\n 0: {\n np.float32: expand_dim0_float_v2_ker,\n np.float64: expand_dim0_double_v2_ker,\n },\n 1: {\n np.float32: expand_dim1_float_v2_ker,\n np.float64: expand_dim1_double_v2_ker,\n }\n }\n}\n\n\ndef expand_gpu_v1(x: gpuarray.GPUArray, dim: int, copies):\n expand_func = expand_ker[\"v1\"][dim][x.dtype.type]\n if dim == 0:\n y = gpuarray.empty((copies, x.shape[0]), dtype=x.dtype)\n expand_func(x, y, np.int32(copies), np.int32(x.shape[0]))\n else:\n y = gpuarray.empty((x.shape[0], copies), dtype=x.dtype)\n expand_func(x, y, np.int32(copies))\n return y\n\n\ndef expand_gpu(x: gpuarray.GPUArray, dim: int, copies):\n expand_func = expand_ker[\"v2\"][dim][x.dtype.type]\n if dim == 0:\n y = gpuarray.empty((copies, x.shape[0]), dtype=x.dtype)\n expand_func(y, x, np.int32(x.shape[0]))\n else:\n y = gpuarray.empty((x.shape[0], copies), dtype=x.dtype)\n expand_func(y, x, np.int32(copies))\n return y\n\n\ndef softmax_gpu2d(x: gpuarray.GPUArray, dim):\n assert len(x.shape) == 2, 'expected 2-dimension array'\n assert 0 <= dim <= 1, \"expected 0 <= dim <=1\"\n exp_ker = exp_float_ker if x.dtype == np.float32 else exp_double_ker\n x_exp = gpuarray.empty_like(x)\n exp_ker(x, x_exp)\n x_exp_sum = misc.sum(x_gpu=x_exp, axis=dim)\n x_exp = misc.div_matvec(x_gpu=x_exp, a_gpu=x_exp_sum, axis=1 - dim)\n return x_exp\n\n\ndef square_gpu(x: gpuarray.GPUArray) -> gpuarray.GPUArray:\n square = square_float_ker if x.dtype == np.float32 else square_double_ker\n y = pycuda.gpuarray.empty_like(x)\n square(y, x)\n return y\n\n\ndef dropout_mask_gpu(x: gpuarray.GPUArray, p=0.):\n assert x.dtype in [np.int32, np.float32, np.float64], 'invalid dtype'\n assert len(x.shape) in [1, 2], 'invalid number of dims'\n mask = gpuarray.empty_like(x)\n random_func = random_float_func if x.dtype == np.float32 else random_double_func\n random_func(mask, np.int32(mask.size), x.dtype.type(p), block=(mask.size if mask.size < 1024 else 1024, 1, 1), grid=(1, 1, 1))\n return mask\n\n\ndef get_mask_gpu(shape, dtype=np.float32, p=0.):\n assert len(shape) in [1, 2], 'invalid number of dims'\n mask = gpuarray.empty(shape=shape, dtype=dtype)\n random_func = random_float_func if x.dtype == np.float32 else random_double_func\n random_func(mask, np.int32(mask.size), dtype(p), block=(mask.size if mask.size < 1024 else 1024, 1, 1), grid=(1, 1, 1))\n return mask\n\n\nlstm_ker = {\n np.int32: random_lstm_int_func,\n np.float32: random_lstm_float_func,\n np.float64: random_lstm_double_func,\n}\n\n\ndef dropout_mask_lstm_gpu(x: gpuarray.GPUArray, p=0.):\n assert x.dtype in [np.int32, np.float32, np.float64], 'invalid dtype'\n assert len(x.shape) == 2, 'x must have 2 dims'\n mask = gpuarray.empty_like(x)\n lstm_func = lstm_ker[x.dtype.type]\n # lstm_func(mask, np.int32(x.shape[1]), np.float32(p), block=(*x.shape, 1), grid=(1, 1, 1))\n lstm_func(mask, np.int32(x.shape[1]), np.float32(p), block=(32, 32, 1),\n grid=((x.shape[0] - 1) // 32 + 1, (x.shape[1] - 1) // 32 + 1, 1))\n return mask\n\n\nnorm_ker = {\n np.int32: norm_int_gpu,\n np.float32: norm_float_gpu,\n np.float64: norm_double_gpu,\n}\n\n\ndef norm_gpu(x: gpuarray.GPUArray):\n norm_func = norm_ker[x.dtype.type]\n return norm_func(x).get() ** 0.5\n\n\n# embedding indices select\nindices_select_ker_template = \"%(p)s *out, int *indices, %(p)s *embedding, int embedding_dim\"\nindices_select_float_ker = ElementwiseKernel(\n arguments=indices_select_ker_template % {'p': 'float'},\n operation=\"\"\"\n int vec_i = i / embedding_dim;\n int pos_in_vec = i % embedding_dim;\n out[i] = embedding[indices[vec_i] * embedding_dim + pos_in_vec];\n \"\"\",\n name=\"index_select\",\n)\n\nindices_select_double_ker = ElementwiseKernel(\n arguments=indices_select_ker_template % {'p': 'double'},\n operation=\"\"\"\n int vec_i = i / embedding_dim;\n int pos_in_vec = i % embedding_dim;\n out[i] = embedding[indices[vec_i] * embedding_dim + pos_in_vec];\n \"\"\",\n name=\"index_select_double_ker\",\n)\n\n\ndef indices_select(embedding: gpuarray.GPUArray, indices: gpuarray.GPUArray):\n indices_select_func = indices_select_float_ker if embedding.dtype == np.float32 else indices_select_double_ker\n y = gpuarray.empty((*indices.shape, embedding.shape[1]), dtype=embedding.dtype)\n indices_select_func(y, indices, embedding, np.int32(embedding.shape[1]))\n return y\n\n\n# loss\ndef bce_with_logits(predicted, target):\n if predicted.shape != target.shape:\n raise ValueError(\"logits and labels must have the same shape ({} vs {})\".format\n (predicted.shape, target.shape))\n\n \"\"\"\n Logistic loss formula is x - x * z + log(1 + exp(-x))\n For x < 0, a more stable formula is -x * z + log(1 + exp(x))\n Generally the formula we need is max(x, 0) - x * z + log(1 + exp(-abs(x)))\n \"\"\"\n\n zeros = np.zeros_like(predicted, dtype=predicted.dtype)\n cond = (predicted >= zeros)\n relu_pred = np.where(cond, predicted, zeros)\n neg_abs_pred = np.where(cond, -predicted, predicted)\n\n return np.add(relu_pred - predicted * target, np.log1p(np.exp(neg_abs_pred)))\n\n\n# adam support func gpu\nadam_mean_float_ker = ElementwiseKernel(\n arguments=\"float *out, float *mean, float *grad, float d\",\n operation=\"\"\"\n out[i] = d * mean[i] + (1 - d) * grad[i]\n \"\"\",\n name=\"adam_mean_float_ker\",\n)\nadam_mean_double_ker = ElementwiseKernel(\n arguments=\"double *out, double *mean, double *grad, double d\",\n operation=\"\"\"\n out[i] = d * mean[i] + (1 - d) * grad[i]\n \"\"\",\n name=\"adam_mean_double_ker\",\n)\n\nadam_var_float_ker = ElementwiseKernel(\n arguments=\"float *out, float *var, float * grad, float d\",\n operation=\"out[i] = d * var[i] + (1 - d) * grad[i] * grad[i]\",\n name=\"adam_var_float_ker\",\n)\n\nadam_var_double_ker = ElementwiseKernel(\n arguments=\"double *out, double *var, double * grad, double d\",\n operation=\"out[i] = d * var[i] + (1 - d) * grad[i] * grad[i]\",\n name=\"adam_var_double_ker\",\n)\n\nadam_grad_float_ker = ElementwiseKernel(\n arguments=\"float *out, float *mean, float *var, float d1_t, float d2_t, float eps\",\n operation=\"out[i] = (mean[i] / (1 - d1_t)) / (sqrt(var[i] / (1 - d2_t)) + eps)\",\n name=\"adam_grad_float_ker\"\n)\n\nadam_grad_double_ker = ElementwiseKernel(\n arguments=\"double *out, double *mean, double *var, double d1_t, double d2_t, double eps\",\n operation=\"out[i] = (mean[i] / (1 - d1_t)) / (sqrt(var[i] / (1 - d2_t)) + eps)\",\n name=\"adam_grad_double_ker\"\n)\n\n\ndef adam_mean(mean: gpuarray.GPUArray, grad: gpuarray.GPUArray, d1, out: gpuarray.GPUArray = None):\n adam_mean_func = adam_mean_float_ker if mean.dtype == np.float32 else adam_mean_double_ker\n if out is None:\n out = gpuarray.empty_like(mean)\n adam_mean_func(out, mean, grad, mean.dtype.type(d1))\n return out\n\n\ndef adam_var(var: gpuarray.GPUArray, grad: gpuarray.GPUArray, d2, out: gpuarray.GPUArray = None):\n adam_var_func = adam_var_float_ker if var.dtype == np.float32 else adam_var_double_ker\n if out is None:\n out = gpuarray.empty_like(var)\n adam_var_func(out, var, grad, var.dtype.type(d2))\n return out\n\n\ndef adam_grad(mean: gpuarray.GPUArray, var: gpuarray.GPUArray, d1, d2, eps, t, out: gpuarray.GPUArray = None):\n adam_grad_func = adam_grad_float_ker if mean.dtype == np.float32 else adam_grad_double_ker\n if out is None:\n out = gpuarray.empty_like(var)\n adam_grad_func(out, mean, var, mean.dtype.type(d1 ** t), mean.dtype.type(d2 ** t), mean.dtype.type(eps))\n return out\n\n\n# add inplace\nadd_inplace_float_ker = ElementwiseKernel(\n arguments=\"float *x, float *y\",\n operation=\"x[i] += y[i]\",\n name=\"add_inplace_float\",\n)\n\nadd_inplace_double_ker = ElementwiseKernel(\n arguments=\"double *x, double *y\",\n operation=\"x[i] += y[i]\",\n name=\"add_inplace_double\",\n)\n\n\ndef add_(x: gpuarray.GPUArray, y: gpuarray.GPUArray):\n assert x.shape == y.shape, f\"x and y must have same shape\"\n assert x.dtype == y.dtype, f\"x and y must have same dtype\"\n add_func = add_inplace_float_ker if x.dtype == np.float32 else add_inplace_double_ker\n add_func(x, y)\n return x\n\n\n# sub inplace\nsub_inplace_float_ker = ElementwiseKernel(\n arguments=\"float *x, float *y, float c\",\n operation=\"x[i] -= c * y[i]\",\n name=\"sub_inplace_float\"\n)\n\nsub_inplace_double_ker = ElementwiseKernel(\n arguments=\"double *x, double *y, double c\",\n operation=\"x[i] -= c * y[i]\",\n name=\"sub_inplace_double\"\n)\n\n\ndef sub_(x: gpuarray.GPUArray, y: gpuarray.GPUArray, c):\n assert x.shape == y.shape, f\"x and y must have same shape\"\n assert x.dtype == y.dtype, f\"x and y must have same dtype\"\n sub_func = sub_inplace_float_ker if x.dtype == np.float32 else sub_inplace_double_ker\n sub_func(x, y, x.dtype.type(c))\n return x\n\n\n# zero inplace\nzero_inplace_float_ker = ElementwiseKernel(\n arguments=\"float *x\",\n operation=\"x[i] = 0.0\",\n name=\"zero_float\"\n)\n\nzero_inplace_double_ker = ElementwiseKernel(\n arguments=\"double *x\",\n operation=\"x[i] = 0.0\",\n name=\"zero_double\"\n)\n\n\ndef zero_(x: gpuarray.GPUArray):\n zero_func = zero_inplace_float_ker if x.dtype == np.float32 else zero_inplace_double_ker\n zero_func(x)\n return x\n\n\n# CPU Support\n\n\ndef sigmoid(x: np.ndarray) -> np.ndarray:\n func = np.vectorize(lambda x: 1 / (1 + np.exp(-x)))\n return func(x)\n\n\ndef tanh(x: np.ndarray) -> np.ndarray:\n func = np.vectorize(lambda x: np.tanh(x))\n return func(x)\n\n\ndef relu(x: np.ndarray):\n func = np.vectorize(lambda x: max(x, 0))\n return func(x)\n\n\ndef relu_grad(x: np.ndarray):\n func = np.vectorize(lambda x: 1 if x > 0 else 0)\n return func(x)\n\n\ndef softmax(x: np.ndarray) -> np.ndarray:\n temp = np.exp(x)\n softmax_output = temp / np.sum(temp,\n axis=len(x.shape) - 1,\n keepdims=True)\n return softmax_output\n\n\ndef dropout_mask(x: np.ndarray, p=0.):\n mask = np.random.choice([0, 1], size=x.shape, p=[p, 1 - p]).astype(x.dtype)\n return mask\n\n\ndef get_mask(shape, dtype=np.float32, p=0.):\n mask = np.random.choice([0, 1], size=shape, p=[p, 1 - p]).astype(dtype)\n return mask\n\n\ndef dropout_mask_lstm(x: np.ndarray, p=0.):\n mask = np.random.choice([0, 1], size=(x.shape[0],), p=[p, 1 - p]).astype(x.dtype)\n return mask\n","sub_path":"model/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":24098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"521317998","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# In[2]:\n\n\nimport math\nimport numpy as np\nfrom numpy import linalg as la\nfrom matplotlib import pyplot as plt\nimport scipy.integrate as inte\nfrom scipy.optimize import fsolve\nfrom numba import jit\n\n#hbar = 1.05e-34\n#m_e = 9.11e-31\n#k_b = 1.38e-23\n\nhbar = 1.\nm_e = 1.\nk_b = 1.\n\n#Temperature = 0.1\n\n\n# In[3]:\n\n\n@jit\ndef dispersion(mu,k_x,k_y,a,t1,t2,t3):\n #This is the dispersion relation for the band.\n #(contains both tight binding as well as quadratic dispersion relations)\n #mu : chemical potential\n #k_x : x - momentum (p = hbar*k)\n #k_y : y - momentum\n #a : lattice parameter\n #t1 : nearest neighbor hopping integral\n #t2 : next nearest neighbor hopping\n #t3 : next next nearest neighbor hopping\n ret = mu + 0.5*t1*(np.cos(k_x*a)+np.cos(k_y*a)) + t2*np.cos(k_x*a)*np.cos(k_y*a) + 0.5*t3*(np.cos(2.*k_x*a)+np.cos(2.*k_y*a))\n #ret = mu - t1*(np.cos(k_x*a)+np.cos(k_y*a)) - t2*np.cos(k_x*a)*np.cos(k_y*a)\n #ret = 0.5*(np.power(k_x,2.) + np.power(k_y,2.))\n #return np.absolute(ret)\n return ret\n\n\n# In[4]:\n\n\n@jit\ndef SC_dispersion(delta,e_k):\n #This is the analytic expression for the superconductor dispersion relation\n #delta : super conducting order parameter\n #e_k = : dispersion relation in normal state\n ret_plus = np.sqrt(delta**2. + e_k**2.)\n ret_minus = -np.sqrt(delta**2. + e_k**2.)\n return ret_plus, ret_minus\n\n@jit\ndef SC_dispersion_plus(delta, e_k):\n #only returns the positive root of the superconducting dispersion relation\n ret = np.sqrt(np.power(delta,2.) + np.power(e_k,2.))\n return ret\n\n\n# In[5]:\n\n\n@jit\ndef SC_dispersion_comp_OAAT(delta,e_k):\n #This computes the eigenvalues and eigenvectors of the Supecconductor Hamiltonian matrix H\n #The eigenvalues determines the SC dispersion numerically only one k point at a time\n H = np.array([[e_k,-delta],[-delta,-e_k]])\n evals,evecs = la.eig(H)\n return evals,evecs\n@jit\ndef SC_dispersion_comp(delta,e_k):\n #This determines the SC dispersion numerically at each k point on the grid.\n #It only returns the positive branch\n #by making SC_dispersion_comp_OAAT step through each k point on the grid.\n #the eigen values are sorted using np.max() as positive first and negative second.\n #This is done because Pythpn flips the order of the eigenvalues to (-,+) when the sign of xi flips from + to -\n #therefore to make all the positive/(negative) values to go together\n #the eigen values are sorted using np.max()\n num_k = len(e_k[0])\n ret = np.zeros((num_k,num_k))\n for i in range(0,num_k):\n for j in range(0,num_k):\n evals, evecs = SC_dispersion_comp_OAAT(delta,e_k[i][j])\n Evals = evals.astype(float)\n ret[i][j] = np.max(Evals)\n return ret\n\n\n# In[6]:\n\n\n@jit\ndef SC_coherence_comp_OAAT(delta,k_x,k_y,k_xp,k_yp,mu,a,t1,t2,t3):\n #This determines the coherence matrix from the eigenvectors of H only one k point at a time\n #The eigen vectors need to be sorted based on the sign of E\n #The Bogoliubov matrix (evecs_k) is contructed with the eigenvectors belonging to +E as the first coloumn\n #and those belonging to _E as the second coloumn.\n #(evecs_k) is the matrix of eigenvectors that python autamtically returns.\n #Because of the above mentioned flipping the vectors need to be sorted too.\n #So if python flips the order of the eigen values to (-,+) we flip back the order of the eigenvectors\n #by putting the first column for the +E and the second coloumn for -E\n #the coherence matrix C is constructed by forming the product transpose(evecs_kp).S.evecs_k\n\n\n evals_k, evecs_k = SC_dispersion_comp_OAAT(delta,dispersion(mu,k_x,k_y,a,t1,t2,t3))\n if evals_k[0] < 0.:\n v1 = evecs_k[:,1]\n v2 = evecs_k[:,0]\n evecs_k[:,0] = v1\n evecs_k[:,1] = v2\n evals_kp, evecs_kp = SC_dispersion_comp_OAAT(delta,dispersion(mu,k_xp,k_yp,a,t1,t2,t3))\n if evals_kp[0] < 0.:\n v1 = evecs_kp[:,1]\n v2 = evecs_kp[:,0]\n evecs_kp[:,0] = v1\n evecs_kp[:,1] = v2\n S = np.array([[1.,0.],[0.,-1.]])\n return (np.dot(np.transpose(evecs_kp),np.dot(S,evecs_k))[0][0])**2.\n@jit\ndef SC_coherence_comp(delta,k_x,k_y,k_xp,k_yp,mu,a,t1,t2,t3):\n #This determines the coherence matrix numerically at each k point on the grid.\n #by making SC_coherence_comp_OAAT step through each k point on the grid.\n num_k = len(k_xp[0])\n ret = np.zeros((num_k,num_k))\n for i in range(0,num_k):\n for j in range(0,num_k):\n ret[i][j] = SC_coherence_comp_OAAT(delta,k_x,k_y,k_xp[i][j],k_yp[i][j],mu,a,t1,t2,t3)\n return ret\n\ndef coherence(delta,E,k_x,k_y):\n #gives the analytic expression for the coherence factors\n ret = 1. + (np.sqrt(E**2. - delta**2.)*dispersion(0.,k_x,k_y,1.,1.,0.,0.) - delta**2.)/(E*SC_dispersion_plus(delta,dispersion(0.,k_x,k_y,1.,1.,0.,0.)))\n return 0.5*ret\n\n#print coherence(.3,0.4,1.,1.)\n#print SC_coherence_comp_OAAT(.3,0.4,1.,1.)\n\n\n# In[7]:\n\n\n@jit\ndef integrator_delta_herm(integrate,dispersion,dk,E,n,f):\n #integrate : 2D array of the function we wish to integrate over k-space\n #dispersion : 2D array with all dispersion relation values over k-space i.e E(k')\n #dk : distance between k values in our grid\n #E : energy that we're currently integrating at ie E(k)\n #n : number of terms in hermite polynomial expansion\n #To summarize we fix E(k) and integrate over all E(k')\n\n #creating the coefficients of even hermiite polynomials\n coeff = np.zeros(n+1)\n for i in range(0,len(coeff)):\n if i % 2 == 0:\n j=float(i/2)\n coeff[i] = ((-1)**float(j))/(math.factorial(float(j))*4**float(i)*np.sqrt(np.pi))\n else:\n coeff[i] = 0.\n dispersion_array = np.array(dispersion)\n integrate_array = np.array(integrate)\n\n ##the variuos choices of the gaussian##\n #exp = np.array(np.exp(-(((E-dispersion_array)**2.)/(2.*f**2.))))\n exp = np.array(np.exp(-(((E-dispersion_array)**2.)/(4.*f))))\n hermite = np.array(np.polynomial.hermite.hermval(E-dispersion_array,coeff))\n\n ##Multiplying the gaussian with the hermite polynomial expansion##\n #func = (1./np.sqrt(2*np.pi*f))*exp*hermite\n func = exp*hermite*(1./(2.*np.sqrt(np.pi*f)))\n\n ret = func*integrate_array\n #print integrate_array, func, ret\n #print np.sum(ret)\n return np.sum(ret)*dk*dk\n@jit\ndef integrator_delta_grad(integrate,dispersion,dk,E):\n dispersion_array = np.array(dispersion)\n integrate_array = np.array(integrate)\n\n delta_mask = dispersion_array == E\n grad_disp_x = np.gradient(dispersion_array,dk)[1]\n grad_disp_y = np.gradient(dispersion_array,dk)[0]\n\n grad_disp = np.sqrt(grad_disp_x**2. + grad_disp_y**2.)\n grad_disp_delta = grad_disp[delta_mask]\n\n if (type(integrate) is float) or (type(integrate) is int):\n integrate_delta = integrate_array\n else:\n integrate_delta = integrate_array[delta_mask]\n #print grad_disp_delta\n #print integrate_delta\n if not integrate_delta.all():\n return 0.\n else:\n ret = integrate_delta/grad_disp_delta\n return np.sum(ret)*dk*dk\n\n\n@jit\ndef BZ_integrator(function,dk):\n #takes an array over the BZ (function), and integrates it by summing the points up\n\n func = np.array(function)\n return np.sum(func)*dk*dk\n\n\n# In[8]:\n\n\n# def gaussian(e,e_k,f):\n# #e : energy\n# #e_k : dispersion relation\n# #f : full width half max of gaussian\n\n# #gaussian used to approximate delta function\n\n# ret = (2./f)*math.sqrt(math.log(2)/math.pi)*math.exp(-(4.*math.log(2.)*(e-e_k)**2.)/f**2.)\n# return ret\n\n@jit\ndef scattering_SC(delta, a, k_x, k_y, mu, t1, t2, t3, num_k, n, f):\n #delta : superconducting order parameter\n #a : lattice parameter\n #num_k : number of k opints along a single axis\n\n #forming the kprime grid with meshgrid\n\n k_xp = np.linspace(-np.pi/a,np.pi/a,num_k)\n k_yp = np.linspace(-np.pi/a,np.pi/a,num_k)\n X,Y = np.meshgrid(k_xp,k_yp)\n\n\n dk = 2.*np.pi/(a*num_k)\n\n # the energy at which we are integrating E(k)\n evals,evecs = SC_dispersion_comp_OAAT(delta,dispersion(mu,k_x,k_y,a,t1,t2,t3))\n E = np.max(evals)\n\n #computing the inverse scattering rate by integrating over the kprime grid\n Tau = integrator_delta_herm(SC_coherence_comp(delta,k_x,k_y,X,Y,mu,a,t1,t2,t3),SC_dispersion_comp(delta,dispersion(mu,X,Y,a,t1,t2,t3)),dk,E,n,f)\n #Tau = integrator_delta_grad(SC_coherence_comp(delta,E,X,Y,mu,a,t1,t2,t3),SC_dispersion_comp(delta,dispersion(mu,X,Y,a,t1,t2,t3)),dk,E)\n\n return np.power(Tau,-1)\n@jit\ndef scattering_n(a,E,mu,t1,t2,t3,num_k,n,f):\n #scattering rate in the normal (non-superconducting) state\n\n k_x = np.linspace(-np.pi/a,np.pi/a,num_k)\n k_y = np.linspace(-np.pi/a,np.pi/a,num_k)\n X,Y = np.meshgrid(k_x,k_y)\n dk = 2.*np.pi/(a*num_k)\n\n Tau = integrator_delta_herm(1.,dispersion(mu,X,Y,a,t1,t2,t3),dk,E,n,f)\n #Tau = integrator_delta_grad(1.,dispersion(mu,X,Y,a,t1,t2,t3),dk,E)\n\n\n return np.power(Tau,-1)\n\n\n\n# In[9]:\n\n\n@jit\ndef fermi_deriv(E,T):\n #derivative of the fermi function\n energy = np.array(E)\n ret = np.exp(energy/(k_b*T))/((1.+np.exp(energy/(k_b*T)))**2.)\n return ret\n\n\n# In[10]:\n\n\n@jit\ndef FullG(gap,T):\n #selfconsistent equation that determines the gap Delta\n m = 500\n gaps = gap**2.\n f = np.log(T)\n for n in range(1,m+1):\n nh = n - 0.5\n sq2 = np.sqrt((T*nh)**2. + gaps)\n f = 1./nh - T/sq2 + f\n return f\n@jit\ndef Delta(T):\n #solving the self consistent equation using fsolve\n if T < 1.0:\n return np.absolute(2.*np.pi*fsolve(FullG,[0.9],args = T))[0]\n else:\n return 0.0\n\n\n# In[11]:\n\n@jit\ndef thermal_conductivity(a,num_k,n,f,num_T,T_end,mu,t1,t2,t3):\n\n Temp = []\n k_xx = []\n k_xy = []\n\n dT = T_end/num_T\n T = dT\n #forming the k grid with meshgrid\n k_x = np.linspace(-np.pi/a,np.pi/a,num_k)\n k_y = np.linspace(-np.pi/a,np.pi/a,num_k)\n X,Y = np.meshgrid(k_x,k_y)\n dk = 2.*np.pi/(a*num_k)\n\n #dispersion values on the k grid of the normal state\n disp = dispersion(mu,X,Y,a,t1,t2,t3)\n\n disp_SC_comp = np.zeros((int(num_k),int(num_k)))\n\n #creating the tau values on the k grid for the normal state\n Tau = np.zeros((len(disp),len(disp[0])))\n for i in range(0,len(disp)):\n for j in range(0,len(disp[0])):\n Tau[i][j] = scattering_n(a,disp[i][j],mu,t1,t2,t3,num_k,n,f)\n\n #normal state E**2 on the grid\n E_squared = np.array(disp)**2.\n #print Tau\n\n #Velocities in the normal state on the k grid\n #np.gradient returns 2 arrays (the x-deriv & y_deriv), so I just matched them up here\n v_x = np.gradient(disp,dk)[1]\n v_y = np.gradient(disp,dk)[0]\n\n\n\n #Everything for the Sc should be in the temperature loop\n for t in range(0,num_T):\n\n #The gap values for all T\n delta = Delta(T)\n\n #the values of the superconducting dispersion on the grid\n disp_SC = SC_dispersion_comp(delta,disp)\n #disp_SC = SC_dispersion_plus(delta,disp)\n\n \"\"\"\n for i in range(0,int(num_k)):\n for j in range(0,int(num_k)):\n disp_SC_comp[i][j], junkData = np.max(SC_dispersion_comp_OAAT(delta,disp[i][j]))\n \"\"\"\n #print disp_SC_comp\n #print \" \"\n\n #creating the tau values on the grid for the superconducting state\n Tau_SC = np.zeros((len(disp_SC),len(disp_SC[0])))\n for i in range(0,len(disp_SC)):\n for j in range(0,len(disp_SC[0])):\n Tau_SC[i][j] = scattering_SC(delta,a,X[i][j],Y[i][j],mu,t1,t2,t3,num_k,n,f)\n #print Tau_SC\n\n #Superconducting E**2 on the grid\n E_squared_SC = np.power(disp_SC,2.)\n\n\n #Velocities in superconducting state on the k grid\n v_x_SC = np.gradient(disp_SC,dk)[1]\n v_y_SC = np.gradient(disp_SC,dk)[0]\n\n #the fermi function derivatives of the normal and superconducting state on the grid\n fermi = fermi_deriv(disp,T)\n fermi_SC = fermi_deriv(disp_SC,T)\n\n #storing the values of the temperature\n Temp.append(T)\n\n #normal state thermal conductivities\n k_xx_n = BZ_integrator(E_squared*Tau*fermi*v_x*v_x,dk)/(T*T)\n k_xy_n = BZ_integrator(E_squared*Tau*fermi*v_x*v_y,dk)/(T*T)\n\n #superconducting state thermal conductivities\n k_xx_SC = BZ_integrator(E_squared_SC*Tau_SC*fermi_SC*v_x_SC*v_x_SC,dk)/(T*T)\n k_xy_SC = BZ_integrator(E_squared_SC*Tau_SC*fermi_SC*v_x_SC*v_y_SC,dk)/(T*T)\n\n #storing normalized thermal conductivities\n k_xx.append(k_xx_SC/k_xx_n)\n k_xy.append(k_xy_SC/k_xx_n)\n\n print(\"{0:<20} {1:<20} {2:<20} {3:<20} {4:<}\".format(T, delta, k_xx_SC/k_xx_n, k_xy_SC/k_xx_n,k_xx_SC, k_xx_n))\n #print (T, delta, k_xx_SC/k_xx_n, k_xy_SC/k_xx_n,k_xx_SC, k_xx_n)\n T = T + dT\n #Temperature = T\n\n# get_ipython().run_line_magic('matplotlib', 'qt')\n # plt.plot(Temp,k_xx)\n # plt.plot(Temp,k_xy)\n # plt.show()\n\n#thermal_conductivity(a,num_k,n,f,num_T,T_end,mu,t1,t2,t3)\nthermal_conductivity(1.,10.,3,.01,30,1.1,0.29,-1.,0.4,0.)\n#scattering_SC(0.3,1.,2.,200,3,.1)\n","sub_path":"sourav-code/SC_numba_prime.py","file_name":"SC_numba_prime.py","file_ext":"py","file_size_in_byte":13240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"161034006","text":"import typing\nimport warnings\nfrom vkbottle.utils import logger\n\nfrom vbml import Patcher\n\nfrom vkbottle.framework.framework.handler.bot.events import BotEvents\nfrom vkbottle.const import __version__\nfrom vkbottle.framework.framework.rule.filters import AbstractFilter\nfrom vkbottle.framework.framework.rule import (\n AbstractRule,\n ChatMessage,\n PrivateMessage,\n Any,\n AbstractMessageRule,\n)\n\nfrom ..handler import ABCHandler\nfrom ..message import ABCMessageHandler\n\n\nclass MessageHandler(ABCMessageHandler):\n def __init__(self, *, default_rules: typing.List[AbstractMessageRule]):\n super().__init__()\n self._default_rules = default_rules\n self._patcher = Patcher.get_current()\n\n def add_rules(self, rules: typing.List[AbstractRule], func: typing.Callable):\n current = list()\n for rule in self.default_rules + rules:\n if not isinstance(rule, (AbstractRule, AbstractFilter)):\n warnings.warn(\n f\"Wrong rule! Got type {rule.__class__} instead of AbstractRule. Rule will be ignored\",\n Warning,\n )\n continue\n if not isinstance(rule, AbstractFilter):\n rule.create(func)\n current.append(rule)\n self.rules.append(current)\n\n\nclass BotHandler(ABCHandler):\n def __init__(self, group_id: int = 0, patcher: Patcher = Patcher()):\n self.group_id: int = group_id\n self.message_rules: typing.List[typing.List[AbstractRule]] = list()\n\n self.message: MessageHandler = MessageHandler(default_rules=[PrivateMessage()])\n self.chat_message: MessageHandler = MessageHandler(\n default_rules=[ChatMessage()]\n )\n self.message_handler: MessageHandler = MessageHandler(default_rules=[Any()])\n self.event: BotEvents = BotEvents()\n\n self._pre_p: typing.Optional[typing.Callable] = None\n self._patcher = Patcher.get_current() or patcher\n\n def concatenate(self, handler: \"BotHandler\"):\n \"\"\"\n Concatenate handlers from current handler and another handler\n :param handler: another handler\n :return:\n \"\"\"\n self.message.concatenate(handler.message)\n self.chat_message.concatenate(handler.chat_message)\n self.message_handler.concatenate(handler.message_handler)\n self.event.rules += handler.event.rules\n if not self._pre_p:\n self._pre_p = handler.pre_p\n\n logger.debug(\n \"BotHandler was concatenated with {handler}\",\n handler=handler.__class__.__name__,\n )\n\n async def dispatch(self, get_current_rest: typing.Callable = None) -> None:\n \"\"\"\n Dispatch handlers from only-handlers and both-handlers\n :param get_current_rest: REST from vkbottle-rest\n :return:\n \"\"\"\n\n self.message_handler.rules += self.message.rules + self.chat_message.rules\n self.message_rules += self.message_handler.rules\n\n if get_current_rest:\n # Check updates from timoniq/vkbottle-rest\n current_rest = await get_current_rest()\n if current_rest.get(\"version\") != __version__:\n logger.info(\n \"You are using old version of VKBottle. Update is found: {} | {}\",\n current_rest.get(\"version\"),\n current_rest.get(\"description\"),\n )\n logger.debug(\"Bot was successfully dispatched\")\n","sub_path":"vkbottle/framework/framework/handler/bot/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"255345618","text":"# MIT License\n\n# Copyright (c) 2018 Addison Lynch\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nfrom pyTD.auth import auth_check\nfrom pyTD.accounts.base import AccountsAndTrading\nfrom pyTD.utils.exceptions import ResourceNotFound\n\n\nclass Watchlists(AccountsAndTrading):\n \"\"\"\n Class for retrieving and posting data via the Watchlists endpoint.\n\n Parameters\n ----------\n account_num: account number, optional\n Account number used for the watchlist\n api: pyTD.api.api object, optional\n A pyTD api object. If not passed, API requestor defaults to\n pyTD.api.default_api\n updated_list: list(WatchlistItem), optional\n list of watchlistitems, if adding a list\n \"\"\"\n\n def __init__(self, **kwargs):\n self.method = kwargs.pop(\"method\")\n self.account_num = kwargs.pop(\"account_num\", None)\n self.watchlist_id = kwargs.pop(\"watchlist_id\", None)\n self.updated_list = kwargs.pop(\"updated_list\", None)\n\n self.opt = kwargs\n api = kwargs.get(\"api\")\n super(AccountsAndTrading, self).__init__(api)\n\n @property\n def params(self):\n # if this doesn't work, try sending json instead or as data param\n p = {\n \"name\": self.watchlist_id,\n \"watchlistItems\": self.updated_list,\n }\n # clear out keys with empty values\n pars = {k: v for k, v in p.items() if v is not None}\n return pars\n\n def set_list_from_strings(self, new_symbols, asset_type):\n new_list = []\n for symbol in new_symbols:\n w = WatchlistItem(instrument=(symbol, asset_type))\n new_list.append(w.get_dict())\n self.updated_list = new_list\n\n @property\n def resource(self):\n return \"watchlists\"\n\n @property\n def url(self):\n if self.method == \"POST\":\n return \"%s%s/%s/%s\" % (self._BASE_URL, self.endpoint, self.account_num, self.resource)\n else:\n if self.watchlist_id:\n return \"%s%s/%s/%s/%s\" % (self._BASE_URL, self.endpoint, self.account_num, self.resource, self.watchlist_id)\n elif self.account_num:\n return \"%s%s/%s/%s\" % (self._BASE_URL, self.endpoint, self.account_num, self.resource)\n else:\n return \"%s%s/%s\" % (self._BASE_URL, self.endpoint, self.resource)\n\n\n @auth_check\n def execute(self):\n # TODO: add in this URL accordingly\n if self.method == \"GET\":\n return self.get(url=self.url)\n # if self.method == \"POST\":\n # return self.post(url=self.url.format(self.account_num))\n if self.method == \"PUT\":\n return self.put(url=self.url)\n if self.method == \"DELETE\":\n return self.delete(url=self.url)\n\n\nclass WatchlistItem:\n \"\"\"\n Class for storing a watchlist item.\n\n Parameters\n ----------\n quantity: int, optional\n quantity of shares, defaults to 0\n average_price: float, optional\n average price of purchase, defaults to 0\n commission: float, optional\n price of commission, defaults to 0\n purchased_date: datetime object, optional\n date of purchase, defaults to DateParam\\\"\n instrument: tuple\n tuple of symbol and asset type. see below for types (symbol, asset type)\n assetType\": \"'EQUITY' or 'OPTION' or 'MUTUAL_FUND' or 'FIXED_INCOME' or 'INDEX'\"\n \"\"\"\n\n def __init__(self, **kwargs):\n self.quantity = kwargs.pop(\"quantity\", 0)\n self.average_price = kwargs.pop(\"average_price\", 0)\n self.commission = kwargs.pop(\"commission\", 0)\n self.purchased_date = kwargs.pop(\"purchased_date\", \"DateParam\\\"\")\n self.instrument = kwargs.pop(\"instrument\")\n\n @property\n def quantity(self):\n return self.quantity\n\n @property\n def average_price(self):\n return self.average_price\n\n @property\n def commission(self):\n return self.commission\n\n @property\n def purchased_date(self):\n return self.purchased_date\n\n @property\n def instrument(self):\n return self.instrument\n\n def get_dict(self):\n return {\n \"quantity\": self.quantity,\n \"averagePrice\": self.average_price,\n \"commission\": self.commission,\n \"purchasedDate\": self.purchased_date,\n \"instrument\": {\n \"symbol\": self.instrument[0],\n \"assetType\": self.instrument[1]\n }\n }\n","sub_path":"pyTD/accounts/watchlists.py","file_name":"watchlists.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"520923775","text":"#!/usr/bin/env python\n\n'''\nConnects to trajectory topic and report\nand publishes next goal in robot plan (geometry_msgs::PoseStamped)\n\n\nMPC controller receives the following from VEN\n1. a command activating a trajectory (2) with id_i\n2. a command starting tracking (3) with time t_i\n3. a trajectory (id_i)\n\nAnd MPC keeps sending to VEN (and coordinator)\n- reports, with chunk and step of trajectory id_i just completed\n\nDynamicConstraints intercepts commands and trajectory and sends\n\n'''\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped\nfrom orunav_msgs.msg import ControllerTrajectoryChunkVec, ControllerReport, ControllerTrajectoryChunk, ControllerCommand, ControllerConstraints\nfrom std_msgs.msg import Float64MultiArray\nimport tf\nfrom threading import Lock\n\n\nclass DynamicConstraints():\n\n # Must have __init__(self) function for a class, similar to a C++ class constructor.\n def __init__(self):\n\n # ................................................................\n # read ros parameters\n self.loadROSParams()\n\n # ................................................................\n # Other config params\n self.commands = []\n self.local_traj_id = 0\n self.curr_chunk = -1\n\n # ................................................................\n # start ros subs/pubs/servs....\n self.initROS()\n\n rospy.loginfo(\"Node [\" + rospy.get_name() + \"] STARTED\")\n\n rospy.spin()\n\n def loadROSParams(self):\n self.robot_id = rospy.get_param('~robot_id', 4)\n self.goal_frame_id = rospy.get_param('~goal_frame_id', 'world')\n\n self.tangential_velocity_topic = rospy.get_param(\n '~bounds_tangential_velocity_topic', '/robot'+str(self.robot_id)+'/control/controller/bounds_tangential_velocity')\n\n self.steering_velocity_topic = rospy.get_param(\n '~bounds_steering_velocity_topic', '/robot'+str(self.robot_id)+'/control/controller/bounds_steering_velocity')\n\n self.spatial_coefs_topic = rospy.get_param(\n '~spatial_coefs_topic', '/robot'+str(self.robot_id)+'/control/controller/spatial_coefs')\n\n self.in_command_topic = rospy.get_param(\n '~in_command_topic', '/robot'+str(self.robot_id)+'/control/controller/commands')\n\n self.out_command_topic = rospy.get_param(\n '~out_command_topic', '/robot'+str(self.robot_id)+'/control/controller/commands_mpc')\n\n self.in_trajectory_topic = rospy.get_param(\n '~in_trajectory_topic', '/robot'+str(self.robot_id)+'/control/controller/trajectories')\n\n self.out_trajectory_topic = rospy.get_param(\n '~out_trajectory_topic', '/robot'+str(self.robot_id)+'/control/controller/trajectories_mpc')\n\n self.in_reports_topic = rospy.get_param(\n '~reports_topic', '/robot' + str(self.robot_id) + '/control/controller/reports_mpc')\n self.out_reports_topic = rospy.get_param(\n '~reports_topic', '/robot' + str(self.robot_id) + '/control/controller/reports')\n\n isPositionConstraintEnabled = rospy.get_param(\n '/robot'+str(self.robot_id)+'/params/controller/enable_position_constraints')\n if not isPositionConstraintEnabled:\n rospy.logerr(\"Node [\" + rospy.get_name() +\n \"] Position constraints disabled. Enabling them in this node \")\n rospy.set_param('/robot'+str(self.robot_id) +\n '/params/controller/enable_position_constraints', True)\n\n def initROS(self):\n self.trajectory_pub = rospy.Publisher(\n self.out_trajectory_topic, ControllerTrajectoryChunkVec, queue_size=1)\n self.command_pub = rospy.Publisher(self.out_command_topic, ControllerCommand, queue_size=1)\n self.reports_pub = rospy.Publisher(self.out_reports_topic, ControllerReport, queue_size=1)\n\n rospy.Subscriber(self.in_trajectory_topic, ControllerTrajectoryChunkVec,\n self.trajectory_callback, queue_size=1)\n rospy.Subscriber(self.in_command_topic, ControllerCommand,\n self.command_callback, queue_size=1)\n rospy.Subscriber(self.in_reports_topic, ControllerReport,\n self.reports_callback, queue_size=1)\n\n rospy.Subscriber(self.tangential_velocity_topic, Float64MultiArray,\n self.bounds_tangential_velocity_callback, queue_size=1)\n rospy.Subscriber(self.steering_velocity_topic, Float64MultiArray,\n self.bounds_steering_velocity_callback, queue_size=1)\n rospy.Subscriber(self.spatial_coefs_topic, Float64MultiArray,\n self.spatial_coefs_callback, queue_size=1)\n # .............................................................................................................\n\n def bounds_tangential_velocity_callback(self, msg):\n coefs = msg.data\n if len(coefs) == 2:\n if coefs[0] < coefs[1]:\n self.bounds_tangential_velocity = coefs\n else:\n rospy.logerr(\"Node [\" + rospy.get_name() + \"] Lower tangential velocity bound bigger than higher one. \" + str(\n coefs[0])+\"> \" + str(coefs[1])+\" \")\n else:\n rospy.logerr(\"Node [\" + rospy.get_name() +\n \"] More than 2 tangential vel bounds provided. (\" + str(len(coefs))+\") \")\n\n def bounds_steering_velocity_callback(self, msg):\n coefs = msg.data\n if len(coefs) == 2:\n if coefs[0] < coefs[1]:\n self.steering_velocity = coefs\n else:\n rospy.logerr(\"Node [\" + rospy.get_name() + \"] Lower steering velocity bound bigger than higher one. \" + str(\n coefs[0])+\"> \" + str(coefs[1])+\" \")\n else:\n rospy.logerr(\"Node [\" + rospy.get_name() +\n \"] More than 2 steering vel bounds provided. (\" + str(len(coefs))+\") \")\n\n def spatial_coefs_callback(self, msg):\n coefs = msg.data\n l_coefs = len(coefs)\n if (l_coefs % 3) == 0:\n self.spatial_coef_a0 = coefs[0:l_coefs/3]\n self.spatial_coef_a1 = coefs[(l_coefs/3):(2*l_coefs/3)]\n self.spatial_coef_b = coefs[(2*l_coefs/3):]\n else:\n rospy.logerr(\"Node [\" + rospy.get_name() +\n \"] Spatial coefs can't be split into three same-lenght vectors. Len is (\" + str(len(coefs))+\") \")\n\n '''\n Reports are continously sent. They contain current controller status and\n car state.\n We will use them to trigger sucesive local trajectory transmissions\n '''\n\n def reports_callback(self, msg):\n\n has_sent = False\n\n # you need it to be idle. Using CONTROLLER_STATUS_FINALIZE (finishing) didn't work well.\n if (msg.status == ControllerReport.CONTROLLER_STATUS_WAIT):\n has_sent = self.sendNext()\n\n # if it didn't transmit more trajectories\n if not has_sent:\n # We need to report in terms of the current reference trajectory,\n # chunk and step, not the local ones.\n msg = self.translateChunks(msg)\n # and send them\n self.reports_pub.publish(msg)\n\n def translateChunks(self, msg):\n # what we just completed ...\n local_chunk_ind = msg.traj_chunk_sequence_num\n local_step_ind = msg.traj_step_sequence_num\n if len(msg.traj_values) > 0:\n local_traj_id = msg.traj_values[0].traj_id\n\n # what we are telling VEN we just did\n global_chunk_ind = max(self.curr_chunk - 1, 0)\n global_step_ind = msg.traj_step_sequence_num\n if len(msg.traj_values) > 0:\n global_traj_id = self.trajectories.chunks[0].traj_id\n\n # repopulate msg.\n # finished transmitting...\n if (self.curr_chunk == -1):\n msg.traj_chunk_sequence_num = 0\n msg.traj_step_sequence_num = 0\n msg.traj_values = []\n else:\n msg.traj_chunk_sequence_num = int(global_chunk_ind)\n msg.traj_step_sequence_num = int(global_step_ind)\n if len(msg.traj_values) > 0:\n msg.traj_values[0].traj_id = global_traj_id\n return msg\n\n def command_callback(self, msg):\n rospy.loginfo(\"Node [\" + rospy.get_name() + \"] command (\" +\n str(msg.command)+\") received. Just for the record\")\n self.commands.append(msg)\n\n def trajectory_callback(self, msg):\n rospy.loginfo(\"Node [\" + rospy.get_name() + \"] trajectory received\")\n self.trajectories = msg\n self.curr_chunk = 0\n\n def sendNext(self):\n '''\n Let's divide 1 trajectory with N chunks into N trajectories with 1 chunk\n '''\n ans = False\n # do we have anything to transmit?\n if (self.curr_chunk >= 0):\n # do we have any chunk to transmit?\n if self.curr_chunk < len(self.trajectories.chunks):\n # index to my chunk list\n chunk = self.trajectories.chunks[self.curr_chunk]\n self.curr_chunk = self.curr_chunk + 1\n\n chunk.sequence_num = 0\n chunk.traj_id = self.local_traj_id\n self.local_traj_id = self.local_traj_id + 1\n chunk.final = True\n\n # constraints\n chunk.constraints = self.getCurrentConstraints(chunk.constraints)\n\n trajCV = ControllerTrajectoryChunkVec()\n trajCV.chunks = []\n trajCV.chunks.append(chunk)\n self.transmitCommands(chunk.traj_id)\n self.retransmitTraj(trajCV)\n ans = True\n # finished transmitting...\n else:\n self.curr_chunk = -1\n # tells if has transmitted\n return ans\n\n def transmitCommands(self, traj_id):\n comm = ControllerCommand()\n comm.robot_id = self.robot_id\n comm.command = comm.COMMAND_ACTIVATE\n comm.traj_id = traj_id\n self.command_pub.publish(comm)\n rospy.loginfo(\"Node [\" + rospy.get_name() + \"] activate sent\")\n\n comm.command = comm.COMMAND_STARTTIME\n comm.start_time = rospy.Time.now()\n self.command_pub.publish(comm)\n rospy.loginfo(\"Node [\" + rospy.get_name() + \"] start time sent\")\n\n def retransmitTraj(self, chunkVec):\n self.trajectory_pub.publish(chunkVec)\n\n ids = []\n for chunk in chunkVec.chunks:\n ids.append(str(chunk.traj_id)+', '+str(chunk.sequence_num))\n ids = ','.join(ids)\n rospy.loginfo(\"Node [\" + rospy.get_name() + \"] retransmitted (traj,seq):\"+ids)\n\n def getCurrentConstraints(self, myConstraints):\n\n # All three arrays must be of the same length.\n # Arrays can be empty.\n '''\n possible spatial constraints:\n a0 a1 b\n 2x +y < 14\n -x +y < 3\n -x -y < 5\n 3x -20y < -1\n '''\n # myConstraints.spatial_coef_a0 = [2, -1, -1, 3]\n # myConstraints.spatial_coef_a1 = [1, 1, -1, -20]\n # myConstraints.spatial_coef_b = [14, 3, 5, -1]\n\n if hasattr(self, 'spatial_coef_a0'):\n myConstraints.spatial_coef_a0 = self.spatial_coef_a0\n myConstraints.spatial_coef_a1 = self.spatial_coef_a1\n myConstraints.spatial_coef_b = self.spatial_coef_b\n\n # Two numbers: minimal and maximal bounds // or an empty array]\n # myConstraints.bounds_tangential_velocity =[ config[\"bounds_tangential_velocity_min\"], config[\"bounds_tangential_velocity_max\"]]\n if hasattr(self, 'bounds_tangential_velocity'):\n myConstraints.bounds_tangential_velocity = self.bounds_tangential_velocity\n\n # Two numbers: minimal and maximal bounds // or an empty array]\n # myConstraints.bounds_steering_velocity =[ config[\"bounds_steering_velocity_min\"], config[\"bounds_steering_velocity_max\"]]\n if hasattr(self, 'bounds_steering_velocity'):\n myConstraints.bounds_steering_velocity = self.bounds_steering_velocity\n\n # TODO other potential constraints...\n # Two numbers: minimal and maximal bounds // or an empty array]\n # myConstraints.bounds_orientation =[ config[\"bounds_orientation_min\"], config[\"bounds_orientation_max\"]]\n\n # Two numbers: minimal and maximal bounds // or an empty array]\n # myConstraints.bounds_tangential_acceleration =[ config[\"bounds_tangential_acceleration_min\"], config[\"bounds_tangential_acceleration_max\"]]\n\n # One number or an empty array\n # myConstraints.bounds_centripetal_acceleration = config[\"bounds_centripetal_acceleration_min\"]\n\n return myConstraints\n\n # def modulateStep(self, traject_ChV):\n # '''\n # takes a full chunk vector and mingles with its positions/speeds\n # controller accepts it\n # '''\n # for chunk in traject_ChV.chunks:\n # for step in chunk.steps:\n # step.velocities.tangential = 2.0 * step.velocities.tangential\n # step.velocities.steering = 2.0 * step.velocities.steering\n # step.state.position_x = 0.5 + step.state.position_x\n # step.state.position_y = 0.5 + step.state.position_y\n #\n # self.retransmit(self.trajectories)\n\n\n# Main function.\nif __name__ == '__main__':\n rospy.init_node('DynamicConstraints') # , log_level=rospy.DEBUG)\n # Go to class functions that do all the heavy lifting. Do error checking.\n try:\n goGo = DynamicConstraints()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"iliad_human_aware_navigation/scripts/deprecated/dynamic_constraints_node.py","file_name":"dynamic_constraints_node.py","file_ext":"py","file_size_in_byte":13628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"630779583","text":"import sys\nfrom pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\n\n\ndef count_words(new_values, last_sum):\n if last_sum is None:\n last_sum = 0\n return sum(new_values, last_sum)\n\n\nif __name__ == \"__main__\":\n batchInterval = int(sys.argv[1])\n hostname = sys.argv[2]\n port = int(sys.argv[3])\n sc = SparkContext(appName=\"streamingErrorCount\")\n ssc = StreamingContext(sc, batchInterval)\n ssc.checkpoint(\"file///tmp/spark\")\n lines = ssc.socketTextStream(hostname, port)\n\n # key=word sum all values associated with the same key works across all entities in the stream\n wordCounts = lines.flatMap(lambda line: line.split(\" \")) \\\n .map(lambda word: (word, 1)) \\\n .updateStateByKey(count_words)\n\n wordCounts.pprint()\n ssc.start()\n ssc.awaitTermination()\n\n","sub_path":"Spark02_Streaming/streaming02_updateStateByKey.py","file_name":"streaming02_updateStateByKey.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"641187610","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns =[\n url(r'^$', views.place_list, name='place_list'),\n url(r'^visited$', views.places_visited, name='places_visited'),\n url(r'^isvisited$', views.place_is_visited, name='place_is_visited'),\n url(r'^place/(?P\\d+)$', views.place, name='place'),\n]\n\n# links the url to the proper view function using regular expressions,\n# originally url(r'^place/(?:place-(?P\\d+)/)?$', views.place, name='place')\n# but /place/place-3/ was redundant\n","sub_path":"django_wishlist/wishlist/travel_wishlist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"64329029","text":"# -*- coding: utf-8 -*-\nimport sys\nimport PyQt4.QtCore as QtCore\nimport PyQt4.QtGui as QtGui\n\ndef print_state(state):\n if state:\n print(\"enabled\")\n else:\n print(\"disabled\")\n\n \ndef main():\n app = QtGui.QApplication(sys.argv)\n\n main_window = QtGui.QMainWindow()\n main_window.setWindowTitle(\"SIGNAL - SLOT Direct connection\")\n\n panel = QtGui.QWidget()\n\n checkbox = QtGui.QCheckBox(\"The Checkbox\", parent=panel)\n button = QtGui.QPushButton(\"Push to change checkbox state\", parent=panel)\n \n layout = QtGui.QVBoxLayout()\n layout.addWidget(checkbox)\n layout.addWidget(button)\n\n panel.setLayout(layout)\n\n button.clicked.connect(checkbox.toggle)\n checkbox.stateChanged.connect(print_state)\n \n main_window.setCentralWidget(panel)\n main_window.show()\n\n app.exec_()\n\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"rc_with_tf/06_gui/sample/PyConJP2011/ConnectSIGNALandSLOT/ConnectSIGNALandSLOT.py","file_name":"ConnectSIGNALandSLOT.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"264752457","text":"# Create maps for hold translation\ndef create_hold_maps () -> int: \n # positions A - K on the moonboard\n categories = [chr(i) for i in range(ord('A'), ord('K')+1)]\n \n #Assign values to positions\n position = dict()\n for cnt, elem in enumerate(categories):\n position[elem] = cnt+1\n \n #Creat unique values for hold positions\n hold_positions = dict()\n for pos in position:\n for cnt in range(1, 19):\n hold_positions[pos + str(cnt)] = (cnt*100) + position[pos]\n \n return hold_positions\n\ndef item_generator (json_input, lookup_key):\n if isinstance(json_input, dict):\n for k, v in json_input.items():\n if k == lookup_key:\n yield v\n else:\n yield from item_generator(v, lookup_key)\n elif isinstance(json_input, list):\n for item in json_input:\n yield from item_generator(item, lookup_key)\n \ndef climbing_grade_to_number(grade):\n grades = {0 : ('6b+', 'V4/V5'), 1 : ('6c', 'V5'), 2 : ('6c+', 'V5/V6'), 3 : ('7a', 'V6'), \n 4 : ('7a+', 'V7'), 5 : ('7b', 'V8'), 6 : ('7b+', 'V8/V9'), 7 : ('7c', 'V9'),\n 8 : ('7c+', 'V10'), 9 : ('8a', 'V11'), 10 : ('8a+', 'V12'), 11 : ('8b', 'V13'), \n 12 : ('8b+', 'V14'), 13 : ('8c', 'V15')}\n \n return grades[grade]","sub_path":"predicting/preprocessing/conversion_functions.py","file_name":"conversion_functions.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"247230930","text":"import json\nimport networkx as nx\nfrom networkx.readwrite import json_graph\nimport http_server\nimport random\n\ndef sen(n1,p1,n2,p2,n3,p3,pa,pb):\n\t\"\"\"Creates a SEN model with an actor network of n1 elements, with a neighbourhood connectivity of p1, a user network of n2 elements, with a neighbourhood connectivity of p2, and a ecological network of n3 elements with a neighbourhood connectivity of p3. The probability of connections between the actor network and the user netwrok, and between the user network and the ecological network, are respectively passed through pa and pb\"\"\"\n\n\t# Actor network\n\tA = nx.newman_watts_strogatz_graph(n1,p1,1)\n\tA.graph['Network']='Actors'\n\t# Adding id\n\tfor i in range(len(A)):\n\t\tA.node[i]['num'] = i+1\n\t# Subnetwork\n\tfor i in range(len(A)):\n\t\tA.node[i]['subnetwork'] = 1\n\t# Adding random class (office dwellers/field people)\n\tp_class_bureau = 0.75\n\tfor i in range(len(A)):\n\t\tif random.random() <= p_class_bureau:\n\t\t\tA.node[i]['group'] = 0\n\t\telse:\n\t\t\tA.node[i]['group'] = 0\n\t# Adding randow weight\n#\tfor n,nbrs in A.adjacency_iter():\n#\t\tfor nbr,eattr in nbrs.items():\n#\t\t\tA[n][nbr]['weight'] = int(random.random()*8)\n\n\n\t# User network\n\tU = nx.newman_watts_strogatz_graph(n2,p2,1)\n\tU.graph['Network']='Actors'\n\t# Adding id\n\tfor i in range(len(U)):\n\t\tU.node[i]['num'] = i+1001\n\t# Subnetwork\n\tfor i in range(len(U)):\n\t\tU.node[i]['subnetwork'] = 2\n\t# Adding random class (office dwellers/field people)\n\tfor i in range(len(U)):\n\t\trnd=random.random()\n\t\tif rnd <= .2:\n\t\t\tU.node[i]['group'] = 1\n\t\tif rnd > .2 and rnd <= .4:\n\t\t\tU.node[i]['group'] = 1\n\t\tif rnd > .4 and rnd <= .6:\n\t\t\tU.node[i]['group'] = 1\n\t\tif rnd > .6 and rnd <= .8:\n\t\t\tU.node[i]['group'] = 1\n\t\tif rnd > .8:\n\t\t\tU.node[i]['group'] = 1\n\t# Adding randow weight\n#\tfor n,nbrs in U.adjacency_iter():\n#\t\tfor nbr,eattr in nbrs.items():\n#\t\t\tU[n][nbr]['weight'] = int(random.random()*8)\n\n\t# Ecological network\n\tE = nx.newman_watts_strogatz_graph(n3,p3,1)\n\tE.graph['Network']='Actors'\n\t# Adding id\n\tfor i in range(len(E)):\n\t\tE.node[i]['num'] = i+10001\n\t# Subnetwork\n\tfor i in range(len(E)):\n\t\tE.node[i]['subnetwork'] = 3\n\t# Adding class\n\tfor i in range(len(E)):\n\t\t\tE.node[i]['group'] = 2\n\t# Adding weight\n#\tfor n,nbrs in E.adjacency_iter():\n#\t\tfor nbr,eattr in nbrs.items():\n#\t\t\tE[n][nbr]['weight'] = 5\n\n\t# joint the three subnetworks\n\tG = nx.disjoint_union_all([A,U,E])\n\n\t# link some actors to some users\n\tfor i in range(0, len(G)):\n\t\tfor j in range(0, len(G)):\n\t\t\tif i != j:\n\t\t\t\tif G.node[i]['subnetwork'] == 1 and G.node[j]['subnetwork'] == 2:\n\t\t\t\t\t#if G.node[i]['group'] == 1 and G.node[j]['group'] == 2:\n\t\t\t\t\tif random.random() < pa:\n\t\t\t\t\t\tG.add_edge(i,j)\n\n\t# link some users to some patches\n\tfor i in range(0, len(G)):\n\t\tG.node[i]['degreeold'] = G.degree(i)\n\n\tfor i in range(0, len(G)):\n\t\tfor j in range(0, len(G)):\n\t\t\tif i != j:\n\t\t\t\t#print str(j) + \" \" + str(G.degree(j))\n\t\t\t\tif G.node[i]['subnetwork'] == 2 and G.node[j]['subnetwork'] == 3 and G.degree(j) - G.node[j]['degreeold'] < 4:\n\t\t\t\t\tif G.degree(j) - G.node[j]['degreeold'] < 4:\n\t\t\t\t\t\tif random.random() < pb:\n\t\t\t\t\t\t\tG.add_edge(i,j)\n\n\t# write json formatted data\n\td = json_graph.node_link_data(G)\n\tjson.dump(d, open('/Users/Rodolphe/Dropbox/Public/d3/examples/force/force.json','w'))\n\n\tnx.write_graphml(G, \"graph.graphml\")\n\t\n\treturn G\n\nsen(100,3,100,3,100,4,.01,.02)","sub_path":"sen.py","file_name":"sen.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"365203024","text":"\"\"\"\nMIT License\n\nAutoencoder-based Attribute Noise Handling Method for Medical Data\n\nCopyright (c) 2022 Thomas RANVIER\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport torch\n\nfrom utils import *\nfrom .common import *\n\ndtype = torch.cuda.FloatTensor\n\n\nclass MIDA_model(nn.Module):\n def __init__(self,\n input_size: int,\n num_layers: int,\n theta: int = 7):\n \"\"\"\n Initialize a MIDA model.\n\n Args:\n input_size (int): The size of the input.\n num_layers (int): Number of layers in both the encoder and decoder.\n theta (int): Number of additional neuron for each deeper layer.\n \"\"\"\n super(MIDA_model, self).__init__()\n\n self._dropout = nn.Dropout(p=.5)\n self._layers = []\n for i in range(num_layers):\n exec(f'self._{i} = nn.Sequential()')\n exec(f'self._{i}.add(nn.Linear({input_size + i * theta}, {input_size + (i + 1) * theta}))')\n exec(f'self._{i}.add(act(\"LeakyReLU\"))')\n exec(f'self._layers.append(self._{i})')\n for i in range(num_layers):\n exec(f'self._{i + num_layers} = nn.Sequential()')\n exec(f'self._{i + num_layers}.add(nn.Linear({input_size + (num_layers - i) * theta}' +\n f', {input_size + (num_layers - 1 - i) * theta}))')\n exec(f'self._{i + num_layers}.add(act(\"LeakyReLU\"))')\n exec(f'self._layers.append(self._{i + num_layers})')\n\n def forward(self, x: object):\n \"\"\"\n Forward propagation through the MIDA model.\n\n Args:\n x (torch Tensor): The data to propagate.\n\n Returns:\n A torch Tensor object, the output from the model.\n \"\"\"\n x = self._dropout(x)\n for lay in self._layers:\n x = lay(x)\n return x\n\n\ndef mida(data_missing_nans: object, num_layers: int, num_epochs: int = 500, nb_batches: int = 10, theta: int = 7):\n \"\"\"\n Implementation of the MIDA optimization function described by Gondara and Wang.\n\n Args:\n data_missing_nans (numpy array): The data with missing values replaced as NaNs.\n num_layers (int): Number of layers in both the encoder and decoder of the MIDA model.\n num_epochs (int): Number of epochs to train the model for. Defaults to 500.\n nb_batches (int): Number of batches. Defaults to 10.\n theta (int): Number of additional neuron for each deeper layer. Defaults to 7.\n\n Returns:\n A numpy array, the best obtained output.\n \"\"\"\n imputer = SimpleImputer(missing_values=np.nan, strategy='mean')\n data_imputed = imputer.fit_transform(data_missing_nans)\n net = MIDA_model(input_size=data_imputed.shape[1], num_layers=num_layers, theta=theta).train().type(dtype)\n optimizer = torch.optim.SGD(net.parameters(), lr=.01, momentum=.99, nesterov=True)\n loss_function = torch.nn.MSELoss().type(dtype)\n loss_hist = []\n best_net_dict = None\n for epoch in range(num_epochs):\n optimizer.zero_grad()\n total_loss = 0\n net_input_splitted = split_batches(data_imputed.copy(), nb_batches)\n for net_input in net_input_splitted:\n input_var = torch.from_numpy(net_input).type(dtype)\n out = net(input_var)\n loss = loss_function(out, input_var)\n loss.backward()\n total_loss += loss.item()\n total_loss /= nb_batches\n if best_net_dict is None or total_loss < min(loss_hist):\n best_net_dict = net.state_dict()\n loss_hist.append(total_loss)\n if total_loss <= 1e-6:\n break\n optimizer.step()\n print(f'Stop training at epoch: {epoch + 1}/{num_epochs}, return best output')\n net.load_state_dict(best_net_dict)\n net.eval()\n best_output = net(torch.from_numpy(data_imputed).type(dtype)).detach().cpu().numpy().squeeze()\n return best_output\n","sub_path":"models/mida.py","file_name":"mida.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"359303675","text":"#-*- coding:utf8 -*-\nfrom pywinauto.application import Application\nfrom subprocess import check_output\nimport time\nfrom pymongo import MongoClient\nimport pymongo\n\nclient=MongoClient(\"localhost\",27017)\ndb=client.db\n#用户名密码验证\ndb.authenticate(\"chen\",\"dview\")\n#db.creare_collection(\"test\",{\"capteed\":True,\"size\":10000,\"max\":10})\ncollection=db.stu\nstudent = {\n 'id': '20170101',\n 'name':['chen',\"kk\"],\n 'age': 20,\n 'gender': 'male',\n 'istrue':True,\n 'qty':260\n}\ncollection.drop()\nresult=collection.insert_one(student)\ncollection.update_many({},{'$pull':{\"name\":\"chen\"}})\n\ncollection.update_many({},{'$unset':{\"qty\":1}})\ncollection.update_many({},{\"$setOnInsert\":{\"createAt\":\"4444\"}},upsert=True)\n#print(result)\ncollection.drop_indexes()\n#collection.drop()\ncollection.create_index([(\"age\",pymongo.DESCENDING),(\"name\",pymongo.ASCENDING)],expireAfterSeconds=3600)\n\ncha=collection.find({\"age\":{\"$gte\":20}})\ncollection.update_many({},{\"$set\":{\"nameee\":\"na\"}},True)\n\ncha=collection.find().sort(\"_id\",pymongo.ASCENDING)#.skip(0).limit(4)\n\nff=collection.aggregate([{\"$project\":{\"name\":1,\"age\":1}},{\"$group\":{\"_id\":\"$name\",\"num\":{\"$sum\":\"$age\"}}},{\"$sort\":{\"num\":pymongo.ASCENDING}}])\n\n\n\n\nstudent=db.student\nstudent.insert_one({\"name\":\"cheng\",\"address\":[\"dalian\",\"beijing\"]})\n\nstudent.update_many({\"address\":{\"$ne\":\"beida\"}},{\"$push\":{\"address\":{\"$each\":['a','b']}}})\nstudent.update_many({},{\"$addToSet\":{\"address\":{\"$each\":[\"dalian\",\"qingdao\"]}}})\n\n\n\n\ncol=db.col\n\ncol.insert_one({\"name\":\"test\",\"score\":[1,2,3,4,5]})\n\nfor x in col.find({\"score\":[1,2,3,4,5]}):\n print(x)\n\n# ss=db.ss\n#\n# ss.drop()\n# ss.insert_one(student)\n#\n# fc=ss.aggregate({\"$project\":{\"name\":1,\"count\":{\"$cond\":[\"$iftrue\",\"hh\",'kk']}}})\n#\n# for i in ff:\n# print(i)\n#collection.drop()\n# #pid=check_output([\"pidof\",\"-s\",\"pycharm64.exe\"])\n# app=Application().connect(title_re=\"TAF.*\")\n# #\n# # #select=app.window(title=\"Select Library\")\n# #\n# # app.print_control_identifiers()\n#\n# mainwindow = app.window(title_re=\"TAF.*\")\n# #loginwindow = mainwindow.child_window(title=\"Select Library\")\n#\n# mainwindow.print_control_identifiers()\n# ss=0\n#Application.window(title=\"Select Library\")\n","sub_path":"MongoDB/pyauto.py","file_name":"pyauto.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"433944085","text":"#-*- coding: utf-8 -*-\n\n# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org\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\nfrom PySide import QtGui, QtCore\nfrom more import LabelWordWrap, show_msg\nimport datetime\n\n_('The user should not be root')\nclass HelpWgt(QtGui.QWidget):\n def __init__(self, parent):\n QtGui.QWidget.__init__(self)\n\n cur_year = str(datetime.date.today().year)\n copy_right = \"©\"\n motto = 'Easy Linux from the Source.
'\n help_text = '%s v%s. \\n' %(parent.ClientObj.Name, \\\n parent.ClientObj.Version) + \\\n _('Makes part of Calculate Utilities 3.0.0') + '
' + \\\n _('Company') + ' Calculate %s 2007-%s' %(copy_right,cur_year)\n\n html_help = (\"\"\n \"\" + help_text + \"\")\n\n helpLabel = LabelWordWrap(html_help, self)\n helpLabel.setContentsMargins(10,10,10,5)\n company_name = _('Company website')\n company_site = 'http://www.calculate.ru'\n distr_name = _('Distribution website')\n distr_site = 'http://www.calculate-linux.org'\n linkLabel = LabelWordWrap(company_name + \\\n \":
\" + \\\n company_site + \"

\" + distr_name+ \\\n \":
\" + \\\n distr_site + \"\", self)\n\n linkLabel.setContentsMargins(10,5,10,5)\n linkLabel.setOpenExternalLinks(True)\n helpQuit = QtGui.QPushButton(_(\"Close\"), self)\n helpQuit.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Escape))\n helpQuit.setFixedWidth(100)\n\n self.image_lbl = QtGui.QLabel(self)\n\n filename = '/usr/share/icons/Calculate/128x128/apps/' \\\n 'calculate-console.png'\n ir = QtGui.QImageReader(filename)\n\n diff = ir.size().width() / 140.0\n w = ir.size().width() / diff\n h = ir.size().height() / diff\n if w > 2 * h:\n ir.setScaledSize(QtCore.QSize(1.7 * w, 1.7 * h))\n else:\n ir.setScaledSize(QtCore.QSize(w, h))\n img = ir.read()\n pm2 = QtGui.QPixmap().fromImage(img)\n\n self.image_lbl.setPixmap(pm2)\n\n layout = QtGui.QGridLayout(self)\n layout.setContentsMargins(24,10,24,10)\n layout.setAlignment(QtCore.Qt.AlignTop)\n\n layout.addWidget(self.image_lbl, 0,0,3,1)\n layout.addWidget(helpLabel,0,1)\n layout.addWidget(linkLabel,1,1)\n layout.addWidget(helpQuit,2,1, QtCore.Qt.AlignRight)\n self.setLayout(layout)\n helpQuit.clicked.connect(self.close)\n\n# self.setFixedSize(400 + x ,200)\n self.setFixedSize(self.sizeHint().width() + 50, \\\n self.sizeHint().height())\n self.setWindowTitle (_('Calculate Console '))\n help_icon = QtGui.QIcon \\\n ('/usr/share/pixmaps/calculate-console-online.png')\n if help_icon.isNull():\n help_icon = QtGui.QIcon.fromTheme(\"help-about\")\n self.setWindowIcon (help_icon)\n\n self.move(parent.window().geometry().x() + \\\n parent.window().geometry().width() / 2 \\\n - self.size().width() / 2, \\\n parent.window().geometry().y() + \\\n parent.window().geometry().height() / 2 \\\n - self.size().height() / 2)\n\n # for clear memory after closed this window\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n\nclass HandBookWgt(HelpWgt):\n def __init__(self, parent, window):\n HelpWgt.__init__(self, parent)\n\n# send report Bug in email\nimport smtplib, re\nimport email.utils\nfrom email.mime.text import MIMEText\n\nclass BugWgt(QtGui.QWidget):\n def __init__(self, parent):\n QtGui.QWidget.__init__(self)\n\n name_lbl = QtGui.QLabel(_('Your name:'), self)\n self.name_edit = QtGui.QLineEdit(self)\n\n send_mail_lbl = QtGui.QLabel(_('Your email:') + ' *', self)\n send_mail_lbl.setToolTip(_('Please enter a valid email. ') + '\\n' + \\\n _('If the email does not exist, you will receive no letter'))\n self.send_mail_edit = QtGui.QLineEdit(self)\n self.send_mail_edit.setToolTip(_('Please enter a valid email. ')+'\\n'+\\\n _('If the email does not exist, you will receive no letter'))\n\n subject_lbl = QtGui.QLabel(_('Subject:'), self)\n self.subject_edit = QtGui.QLineEdit(self)\n\n message_lbl = QtGui.QLabel(_('Message:'), self)\n self.message_edit = QtGui.QTextEdit(self)\n\n Send_button = QtGui.QPushButton(_(\"Send a Bug\"), self)\n Send_button.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return))\n Send_button.setMinimumWidth(Send_button.sizeHint().width())\n Send_button.clicked.connect(self.send_bug)\n\n Quit_button = QtGui.QPushButton(_(\"Close\"), self)\n Quit_button.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Escape))\n Quit_button.clicked.connect(self.close)\n\n layout = QtGui.QGridLayout(self)\n layout.setColumnStretch(0,0)\n layout.setColumnStretch(1,1)\n\n layout.addWidget(name_lbl, 0,0, QtCore.Qt.AlignRight)\n layout.addWidget(self.name_edit, 0, 1, 1, 2) \n\n layout.addWidget(send_mail_lbl, 1,0, QtCore.Qt.AlignRight)\n layout.addWidget(self.send_mail_edit, 1, 1, 1, 2)\n\n layout.addWidget(subject_lbl, 2,0, QtCore.Qt.AlignRight)\n layout.addWidget(self.subject_edit, 2, 1, 1, 2)\n\n layout.addWidget(message_lbl, 3,0, QtCore.Qt.AlignRight | \\\n QtCore.Qt.AlignTop)\n layout.addWidget(self.message_edit, 3,1, 2, 2)\n\n button_layout = QtGui.QHBoxLayout()\n button_layout.addWidget(Send_button)\n button_layout.addWidget(Quit_button)\n layout.addLayout(button_layout, 5, 1, 1, 2, QtCore.Qt.AlignRight)\n self.setLayout(layout)\n\n self.resize(350, 250)\n\n # Set title and icon\n self.setWindowTitle (_('Calculate Console '))\n bug_icons = ['tools-report-bug','system-help','help-browser']\n themeName = QtGui.QIcon.themeName()\n bug_icon = QtGui.QIcon()\n for image in bug_icons:\n bug_icon.setThemeName(themeName)\n bug_icon = bug_icon.fromTheme(image)\n if not bug_icon.isNull():\n break\n bug_icon.setThemeName('Tango')\n bug_icon = bug_icon.fromTheme(image)\n if not bug_icon.isNull():\n break\n\n self.setWindowIcon(bug_icon)\n self.setWindowTitle(_(\"Report a Bug\"))\n\n self.move(parent.window().geometry().x() +\n parent.window().geometry().width() / 2\n - self.size().width() / 2,\n parent.window().geometry().y() +\n parent.window().geometry().height() / 2\n - self.size().height() / 2) \n\n # for clear memory after closed this window\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n\n def set_message_text(self, text):\n self.message_edit.setText(text)\n\n def send_bug(self):\n name = self.name_edit.text()\n\n sender = self.send_mail_edit.text()\n mail_re = re.compile(\"^[a-zA-Z_0-9\\.\\-]{1,32}[\\@]{1}[a-zA-Z_0-9]\"+\\\n \"{1,16}[\\.]{1}[a-zA-Z]{1,3}$\")\n if not mail_re.findall(sender):\n show_msg (_('Enter a valid email!'))\n return 1\n\n to_name = 'calculate bug report'\n receivers = 'mh@calculate.ru'\n subject = self.subject_edit.text()\n\n body = self.message_edit.toPlainText()\n try:\n body = body.encode('utf-8')\n except:\n body = str(body)\n\n # assemble the message\n performDebugging = False\n msg = MIMEText(body)\n msg.set_charset('utf-8')\n msg['To'] = email.utils.formataddr((to_name, receivers))\n msg['From'] = email.utils.formataddr((name, sender))\n msg['Subject'] = 'Bug Report: ' + subject\n\n server = smtplib.SMTP('mail')\n server.set_debuglevel(performDebugging)\n try:\n server.sendmail(sender, [receivers], msg.as_string())\n show_msg (_(\"Message sent!\"))\n server.quit()\n self.close()\n except:\n show_msg (_(\"Sending error\"))\n server.quit()","sub_path":"consolegui/application/helpwidget.py","file_name":"helpwidget.py","file_ext":"py","file_size_in_byte":9074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304802686","text":"\"\"\"\n Turn radius projection demo\n How and why to use the Ackermann steering model. https://www.youtube.com/watch?v=i6uBwudwA5o\n\"\"\"\n\nimport math\nimport numpy as np\nimport cv2\nfrom argparse import Namespace\n\nFILTER_NEGATIVE_POINTS = True\nFILTER_NONMONOTONIC_POINTS = True\n\nCAR_L = 2.634 # Wheel base\nCAR_T = 1.733 # Tread\nMIN_TURNING_RADIUS = 5.\nMAX_STEER = 500\n\nCAMERA_POSITION = [0, 1.5422, 1.657]\nCAMERA_MATRIX = [\n np.array([[1173.122620, 0.000000, 969.335924],\n [0.000000, 1179.612539, 549.524382],\n [0., 0., 1.]])\n]\nRVEC = np.array([0.04, 0.0, 0.0])\nTVEC = np.array([0, 0, 0], np.float) # translation vector\nDISTORTION = np.array([0.053314, -0.117603, -0.004064, -0.001819, 0.000000])\n\nCAMERA_HEIGHT = 1.56\ncauciucuri_exterior = 1.69\n\n\ndef get_radius(angle, car_l=CAR_L, car_t=CAR_T):\n r = car_l / np.tan(np.deg2rad(angle, dtype=np.float32))\n return r\n\n\ndef get_delta(r, car_l=CAR_L, car_t=CAR_T):\n \"\"\"\n :param r: Turn radius ( calculated against back center)\n :param car_l: Wheel base\n :param car_t: Tread\n :return: Angles of front center, inner wheel, outer wheel\n \"\"\"\n delta_i = np.rad2deg(np.arctan(car_l / (r - car_t / 2.)))\n delta = np.rad2deg(np.arctan(car_l / r))\n delta_o = np.rad2deg(np.arctan(car_l / (r + car_t / 2.)))\n return delta, delta_i, delta_o\n\n\ndef get_car_path(r, distance=1., no_points=100, center_x=True, car_l=CAR_L, car_t=CAR_T):\n \"\"\"\n :param r: Car turn radius ( against back center )\n :param distance: Distance to draw points\n :param no_points: No of points to draw on path\n :param center_x: If center point on the oX axis\n :param car_l: Wheel base\n :param car_t: Tread\n :return: center_points, inner_points, outer_points (on car path)\n \"\"\"\n r_center = r\n r_inner = r_center - car_t / 2.\n r_outer = r_center + car_t / 2.\n\n d_inner = r_inner / r_center * distance\n d_outer = r_outer / r_center * distance\n center_points = point_on_circle(r_center, distance=distance, no_points=no_points,\n center_x=False)\n inner_points = point_on_circle(r_inner, distance=d_inner, no_points=no_points, center_x=False)\n outer_points = point_on_circle(r_outer, distance=d_outer, no_points=no_points, center_x=False)\n if center_x:\n center_points[:, 0] -= r_center\n inner_points[:, 0] -= r_center\n outer_points[:, 0] -= r_center\n\n return center_points, inner_points, outer_points\n\n\ndef point_on_circle(r, distance=1., no_points=100, center_x=True):\n \"\"\"\n Returns a fix number of points on a circle circumference.\n :param r: circle radius\n :param distance: length of circumference to generate points for\n :param no_points: number of points to generate\n :param center: center points on the x axis ( - r)\n :return: np. array of 2D points\n \"\"\"\n fc = 2 * np.pi * r\n p = distance / fc\n step = 2 * np.pi * p / float(no_points)\n points = np.array(\n [(math.cos(step * x) * r, math.sin(step * x) * r) for x in range(0, no_points + 1)]\n )\n if center_x:\n points[:, 0] = points[:, 0] - r\n return points\n\n\nclass TurnRadius:\n def __init__(self, cfg):\n self.car_l = cfg.car_l\n self.car_t = cfg.car_t\n self.min_turning_radius = cfg.min_turning_radius\n\n self.num_points = num_points = 400\n max_wheel_angle = np.rad2deg(np.arctan(CAR_L / MIN_TURNING_RADIUS))\n self.angles = np.linspace(-max_wheel_angle, max_wheel_angle, num_points)\n\n def get_car_path(self, steer_factor, distance=20):\n \"\"\"\n :param steer_factor: [-1, 1] (max left max right)\n :return:\n \"\"\"\n num_points = self.num_points\n idx = np.clip(int(num_points/2. * steer_factor + num_points/2.), 0, num_points-1)\n r = get_radius(self.angles[idx])\n c, lw, rw = get_car_path(r, distance=distance)\n return c, lw, rw\n\n\nclass TrajectoryVisualizer:\n \"\"\"\n Class that takes input a configuration file that contain information about line color and\n width, parameters about the camera and other data about the distance marks.\n Provides a method that projects the trajectory of the car given a steering angle on an\n image based on parameters from configuration.\n \"\"\"\n\n def __init__(self, cfg):\n self.cfg = cfg\n self.rvec = cfg.RVEC\n self.center_color = cfg.center_color\n self.center_width = cfg.center_width\n self.side_color = cfg.side_color\n self.side_width = cfg.side_width\n self.curve_length = cfg.curve_length\n self.initial_steering = cfg.initial_steering\n self.RVEC = cfg.RVEC\n self.TVEC = cfg.TVEC\n self.CAMERA_MATRIX = cfg.CAMERA_MATRIX\n self.CAMERA_POSITION = cfg.CAMERA_POSITION\n self.DISTORTION = cfg.DISTORTION\n self.MARK_COUNT = cfg.MARK_COUNT\n self.START_DIST = cfg.START_DIST\n self.GAP_DIST = cfg.GAP_DIST\n self.CAMEAR_Y = cfg.CAMEAR_Y\n\n def project_points_on_image_space(self, points_3d):\n rvec = self.RVEC\n tvec = self.TVEC\n camera_matrix = self.CAMERA_MATRIX\n distortion = self.DISTORTION\n\n points = np.array(points_3d).astype(np.float32)\n points, _ = cv2.projectPoints(points, rvec, tvec, camera_matrix, distortion)\n points = points.astype(np.int)\n points = points.reshape(-1, 2)\n return points\n\n def render_line(self, image, points, color=None, thickness=None):\n points = self.project_points_on_image_space(points)\n\n h, w, _ = image.shape\n\n if FILTER_NEGATIVE_POINTS:\n idx = 0\n while (points[idx] < 0).any() or points[idx+1][1] < points[idx][1]:\n idx += 1\n if idx >= len(points) - 1:\n break\n\n points = points[idx:]\n\n # TODO Check validity - expect monotonic modification on x\n # monotonic decrease on y\n if len(points) <= 0:\n return image\n\n prev_x, prev_y = points[0]\n idx = 1\n if len(points) > 1:\n while points[idx][1] < prev_y:\n prev_x, prev_y = points[idx]\n idx += 1\n if idx >= len(points):\n break\n print(points[idx])\n\n valid_points = []\n while points[idx][0] >= 0 and points[idx][0] < w and idx < len(points)-1:\n valid_points.append([points[idx][0], points[idx][1]])\n idx += 1\n else:\n valid_points = [[prev_x, prev_y]]\n\n if FILTER_NONMONOTONIC_POINTS:\n points = np.array(valid_points)\n\n for p in zip(points, points[1:]):\n image = cv2.line(image, tuple(p[0]), tuple(p[1]), color=color, thickness=thickness)\n\n return image\n\n def detect_indexes_on_lane_points_for_distance_marks(self, mark_count, start_dist, dist_gap):\n initial_steering = self.initial_steering\n curve_length = self.curve_length\n\n c, lw, rw = get_car_path(initial_steering, distance=curve_length)\n lw = self.add_3rd_dim(lw)\n\n def create_horizontal_line_at_depth(distance_from_camera, left_limit=-CAR_T/2, right_limit=CAR_T/2, n=2):\n x = np.expand_dims(np.linspace(left_limit, right_limit, num=n), axis=1)\n y = np.ones((n, 1)) * CAMERA_HEIGHT\n z = np.ones((n, 1)) * distance_from_camera\n xy = np.concatenate((x, y), axis=1)\n xyz = np.concatenate((xy, z), axis=1)\n return xyz\n\n def get_idx_closest_point_to(points, point):\n dists = list(map(lambda x : np.linalg.norm(x - point), points))\n min_idx = dists.index(min(dists))\n return min_idx\n\n indexes = []\n for dist in np.arange(start_dist, start_dist + mark_count * dist_gap, dist_gap):\n line_at_dist = create_horizontal_line_at_depth(dist)\n indexes.append(get_idx_closest_point_to(lw, line_at_dist[0]))\n\n return indexes\n\n def add_3rd_dim(self, points):\n camera_position = self.CAMERA_POSITION\n\n points3d = []\n for point in points:\n points3d.append([\n point[0] + camera_position[0],\n 0 + camera_position[1],\n point[1]]) # - camera_position[2]])\n\n return np.array(points3d)\n\n def render(self, image, steering_angle):\n MARK_COUNT = self.MARK_COUNT\n START_DIST = self.START_DIST\n GAP_DIST = self.GAP_DIST\n curve_length = self.curve_length\n center_color = self.center_color\n center_width = self.center_width\n side_color = self.side_color\n side_width = self.side_width\n\n indexes = self.detect_indexes_on_lane_points_for_distance_marks(MARK_COUNT,\n START_DIST,\n GAP_DIST)\n\n c, lw, rw = get_car_path(steering_angle, distance=curve_length)\n c = self.add_3rd_dim(c)\n lw = self.add_3rd_dim(lw)\n rw = self.add_3rd_dim(rw)\n\n image = self.render_line(image, c, color=center_color, thickness=center_width)\n image = self.render_line(image, lw, color=side_color, thickness=side_width)\n image = self.render_line(image, rw, color=side_color, thickness=side_width)\n\n for index in indexes:\n image = self.render_line(image, np.array([lw[index], rw[index]]), color=side_color,\n thickness=side_width)\n\n return image\n\n\ndef main_revised():\n\n cfg_i = {'center_color': (0, 255, 0),\n 'center_width': 4,\n 'side_color': (0, 255, 255),\n 'side_width': 2,\n 'curve_length': 30.0,\n 'initial_steering': -1994.999999999999971, # for this steering we have a straight line of trajectory\n\n 'RVEC': RVEC,\n 'TVEC': TVEC,\n 'CAMERA_MATRIX': CAMERA_MATRIX[0],\n 'CAMERA_POSITION': CAMERA_POSITION,\n 'DISTORTION': DISTORTION,\n 'MARK_COUNT': 10,\n 'START_DIST': 6.0,\n 'GAP_DIST': 1.0,\n 'CAMEAR_Y': CAMERA_HEIGHT}\n cfg = Namespace()\n cfg.__dict__ = cfg_i\n\n tv = TrajectoryVisualizer(cfg)\n num = 400\n max_wheel_angle = np.rad2deg(np.arctan(CAR_L / MIN_TURNING_RADIUS))\n angles = np.linspace(-max_wheel_angle, max_wheel_angle, num)\n idx = int(angles.size / 2)\n r = -10.0\n\n data = {\n \"r\": r,\n }\n\n cap = cv2.VideoCapture(0) # 0 for built-in webcam, 1 for secondary, 2 for third ...\n #cap = cv2.VideoCapture('camera_3.mp4')\n cv2.destroyAllWindows()\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\n\n def get_frame_from_image():\n rgb = cv2.imread(\"/media/andrei/Samsung_T51/nemodrive/18_nov/session_0/1542535225.01_camera_1_off_7ms.jpg\")\n # return cv2.resize(rgb, (1280, 720))\n return rgb\n\n def get_frame_from_webcam():\n ret, rgb = cap.read()\n h, w = rgb.shape[:2]\n rgb[h//2:h//2 + 2, :] = np.array([0, 255, 128], dtype = np.uint8)\n rgb[:, w // 2:w // 2 + 2] = np.array([0, 255, 128], dtype=np.uint8)\n\n return rgb\n\n def loop():\n r = data['r']\n background_img = get_frame_from_image()\n #background_img = get_frame_from_webcam()\n # print(r)\n image = tv.render(background_img, r)\n image = cv2.resize(image, (1280, 720))\n cv2.imshow(\"image\", image)\n\n def update(val):\n data['r'] = get_radius(angles[400 - val - 1])\n loop()\n\n cv2.namedWindow('image')\n cv2.createTrackbar('angle', 'image', idx, 400 - 1, update)\n\n while True:\n loop()\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n\nif __name__ == \"__main__\":\n main_revised()\n","sub_path":"trajectory_visualizer.py","file_name":"trajectory_visualizer.py","file_ext":"py","file_size_in_byte":11871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"258487908","text":"__author__ = 'MA573RWARR10R'\nimport sys\nfrom termcolor import colored\n\nQUIET = False\n\nDATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\nDATE_FORMAT = \"%Y-%m-%d\"\n\nDEFAULT_DYNAMIC_TYPE = \"comments_count\"\nDYNAMIC_TYPES = [\"likes_count\", \"dislikes_count\", \"reposts_count\", \"comments_count\"]\n# DYNAMIC_TYPES_INDEXES = {\n# k: v for k, v in zip(DYNAMIC_TYPES, range(6, 11))\n# }\n\nLEAD_ELEMENT_TYPE = 1\nTITLE_ELEMENT_TYPE = 2\nCONTENT_ELEMENT_TYPE = 3\n\nDATABASE_TYPE = 'mysql_local'\n# DATABASE_TYPE = 'mysql_remote'\n\nVALID_TEXT_LENGTH = 15\nVALID_TEXT_WORDS_COUNT = 3\nWORDS_PER_LINK = 5\nWORDS_PER_LIST_MARKER = 5\n\nKEYWORDS_COUNT = 8\n\nLDA_CHUNKSIZE = 500\nLDA_PASSES = 50\nLDA_TOPIC_WORD_COUNT = 5\nLDA_TOPICS_COUNT = 15\n\nMINI_LDA_TOPIC_WORD_COUNT = 3\nMINI_LDA_TOPICS_COUNT = 5\nMINI_LDA_RESULT_TOPIC_WORD_COUNT = 3\n\nR_PLUMBER_SERVICE_ADDRESS = \"http://127.0.0.1:8000/\"\n\nR_EMOTION_COLORS_VALUES_COUNT = 20\n\nWARNING_FLAG = colored(\" [! WARNING !] \", 'yellow', None, ['bold'])\nSUCCESS_FLAG = colored(\" [! SUCCESS !] \", 'green', None, ['bold'])\nERROR_FLAG = colored(\" [! ERROR !] \", 'red', None, ['bold'])\nEXCEPTION_FLAG = colored(\" [! EXCEPTION !] \", 'magenta', None, ['bold'])\nINFO_FLAG = colored(\" [ INFO ] \", 'white', None, ['bold'])\n\nCOMPARE_WITH_TOP_COUNT = 5\nDISPLAYED_TOP_COUNT = 5\n\nSUPPORTED_LANGUAGES = ['en', 'us', 'de']\n\nTRENDS_SUPPORTED_GEOS = ['US', 'DE', 'GB']\nTRENDS_TOP_PER_CATEGORY_LIMIT = 50\nTRENDS_INITIAL_COUNT = 5\nTRENDS_INITIAL_CATEGORY_NAME = 'all'\n\nimport os\n\nDEFAULT_PROJECT_PATH = os.environ['EXPONENTA_PROJECT_PATH']\n\nRT_TFIDF_PATH = DEFAULT_PROJECT_PATH + \"relevant_trends/models_data/\"\nRT_W2V_PATH = DEFAULT_PROJECT_PATH + \"relevant_trends/models_data/\"\n\nREDIS_HOST = 'localhost'\nREDIS_PORT = 6379\n# RT_REDIS_EDITION_TRENDS_NOW_URL = 'http://127.0.0.1:6378/trends_now/'\n# RT_REDIS_EDITION_TRENDS_NOW_RESULT_URL = 'http://127.0.0.1:6378/trends_result/'\n\n\nCATEGORIES_SHORT = {\n 'business': 'b',\n 'entertainment': 'e',\n 'sports': 's',\n 'sci/tech': 't',\n 'health': 'm',\n}\n\nSSL_CERT_PATH = \"/home/ec2-user/keys/privkey.pem\"\nSSL_KEY_PATH = \"/home/ec2-user/keys/fullchain.pem\"\n# SSL_CERT_PATH = \"ssl_keys/cert.pem\"\n# SSL_KEY_PATH = \"ssl_keys/key.pem\"\n\nEXPONENTA_DASHBOARD_NOISY_DEBUG = True\nONLY_CONTENT_RESOURCES = ['facebook.com']\n\nif DEFAULT_PROJECT_PATH not in sys.path:\n sys.path.append(DEFAULT_PROJECT_PATH)\n","sub_path":"psettings.py","file_name":"psettings.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"156683533","text":"#!/usr/bin/python\n\n\"\"\"\nsipros_post_module.py\n\nsipros_post_module.py module includes common classes, definitions,\nand funcitons for sipros post-processing programs.\n\nCreated by Tae-Hyuk (Ted) Ahn on 10/10/2012.\nCopyright (c) 2012 Tae-Hyuk Ahn (ORNL). Allrights reserved.\n\nModified by Xuan Guo on 07/13/2016\n\"\"\"\n\n# # Import standard modules\nimport sys, os, re, math\nfrom datetime import datetime\nfrom collections import namedtuple\nfrom multiprocessing import Process\n\n# # Class Usage\nclass Usage(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n\n# # Class for ignoring comments '#' in sipros file\nclass CommentedFile:\n def __init__(self, f, comment_string=\"#\"):\n self.f = f\n self.comment_string = comment_string\n def next(self):\n line = self.f.next()\n while line.startswith(self.comment_string):\n line = self.f.next()\n return line\n def __iter__(self):\n return self\n\n\n# # Exit system with error message\ndef die(msg=None):\n if msg is not None:\n print >> sys.stderr, msg\n sys.exit(1)\n\n\n# # Returns the current time in a nice format\ndef curr_time():\n curr_time = datetime.now()\n return curr_time.strftime(\"%c\")\n\n\n# # Format time as a pretty string\ndef format_time(td):\n hours = td.seconds // 3600\n minutes = (td.seconds % 3600) // 60\n seconds = td.seconds % 60\n return '%02d:%02d:%02d' % (hours, minutes, seconds)\n\n\n# # Find string between two substrings\ndef find_between(s, first, last):\n try:\n start = s.index(first) + len(first)\n end = s.index(last, start)\n return s[start:end]\n except ValueError:\n return \"\"\n\n\n# # Division error handling\ndef divide(x, y):\n try:\n result = x / y\n except ZeroDivisionError as detail:\n print >> sys.stderr, 'Handling run-time error:', detail\n die('Program exit!')\n else:\n return result\n\n\n# # Check file exist\ndef check_file_exist(filename):\n\n try:\n with open(filename) as _f: pass\n except IOError as _e:\n print >> sys.stderr, '\\nCannot open', filename\n die(\"Program exit!\")\n\n\n# # Get file(s) list in working dir with specific file extension\ndef get_file_list_with_ext(working_dir, file_ext):\n\n # define sipros file extension\n file_list = []\n\n # working directory\n if os.path.exists(working_dir):\n for file_name in os.listdir(working_dir):\n\n # check the file extension\n if file_name.endswith(file_ext):\n file_path_name = working_dir + file_name\n file_list.append(file_path_name)\n\n if len(file_list) == 0:\n print >> sys.stderr, \"\\nCannot open %s file(s).\" % (file_ext)\n die(\"Program exit!\")\n file_list = sorted(file_list)\n\n else:\n print >> sys.stderr, \"\\nCannot open working directory\", working_dir\n die(\"Program exit!\")\n\n return file_list\n\n# # Get base output filename with input file list and base_out_default\ndef get_base_out(file_list, base_out_default, working_dir):\n\n # Get base output with common prefix\n base_out = os.path.commonprefix(file_list)\n base_out_filename = base_out.split('/')[-1]\n\n # If base common prefix ends with '.pep.txt', then remove '.pep.txt'\n base_out = base_out.replace(\".pep.txt\", \"_\")\n\n # If base_out file name is less than 5, then use default baseout\n if len(base_out_filename) < 5:\n base_out = working_dir + base_out_default\n\n # If base common prefix ends with '_' or '.', then remove\n base_out = base_out[:-1] if (base_out[-1] in ('_', '.')) else base_out\n\n return base_out\n\n\n# # list_to_string\n# # if single element, then just convert to string\n# # if multiple elements, then bracket {A,B}\ndef list_to_string(input_list):\n\n if len(input_list) > 1:\n converted_str = '{' + ','.join(input_list) + '}'\n else:\n converted_str = ''.join(input_list)\n\n return converted_str\n\n\n# # list_to_bracket\n# # bracket the list\ndef list_to_bracket(input_list):\n\n converted_str = '{' + ','.join(input_list) + '}'\n\n return converted_str\n\n\n# # Class for sipros fields object\nclass SiprosFields(namedtuple('SiprosFields',\n ['Filename',\n 'ScanNumber',\n 'ParentCharge',\n 'MeasuredParentMass',\n 'CalculatedParentMass',\n 'ScanType',\n 'SearchName',\n 'ScoringFunction',\n 'Rank',\n 'Score',\n 'IdentifiedPeptide',\n 'OriginalPeptide',\n 'ProteinNames'])):\n def __init__(self):\n self.data = self\n\n# # Class for spectrum fields object\nclass SpectrumFields(namedtuple('SpectrumFields',\n ['x',\n 'Filename',\n 'ScanNumber',\n 'ParentCharge',\n 'MeasuredParentMass',\n 'ScanType',\n 'SearchName',\n 'TotalIntensity',\n 'MaxIntensity'])):\n def __init__(self):\n self.data = self\n\n# # Class for psm fields object\nclass PsmFields(namedtuple('PsmFields',\n ['x',\n 'OriginalPeptide',\n 'IdentifiedPeptide',\n 'CalculatedParentMass',\n 'MVH',\n 'Xcorr',\n 'WDP',\n 'ProteinNames'])):\n def __init__(self):\n self.data = self\n\n\n# # Class for sipros4 fields object\nclass Sipros4Fields(namedtuple('SiprosFields',\n ['Filename',\n 'ScanNumber',\n 'ParentCharge',\n 'MeasuredParentMass',\n 'CalculatedParentMass',\n 'ScanType',\n 'SearchName',\n 'Rank',\n 'MVH',\n 'Xcorr',\n 'WeightDotSum',\n 'IdentifiedPeptide',\n 'OriginalPeptide',\n 'ProteinNames',\n 'AveAtom',\n 'StdAtom'])):\n\n def __init__(self):\n self.data = self\n\n\n# # Class for PsmOutFields object\nclass PsmOutFields(namedtuple('PsmOutFields',\n ['Filename',\n 'ScanNumber',\n 'ParentCharge',\n 'MeasuredParentMass',\n 'CalculatedParentMass',\n 'MassErrorDa', # CalculatedParentMass - MeasuredParentMass\n 'MassErrorPPM', # MassErrorDa / CalculatedParentMass\n 'ScanType',\n 'SearchName',\n 'ScoringFunction',\n 'Score',\n 'DeltaZ', # The difference score between the rank 1 and 2\n 'DeltaP', # The difference score between isoform\n 'IdentifiedPeptide',\n 'OriginalPeptide',\n 'ProteinNames',\n 'ProteinCount',\n 'TargetMatch'])):\n def __init__(self):\n self.data = self\n\n\n# # Class for PsmOutFields object (for sipro4)\nclass Psm4OutFields(namedtuple('PsmOutFields',\n ['Filename',\n 'ScanNumber',\n 'ParentCharge',\n 'MeasuredParentMass',\n 'CalculatedParentMass',\n 'MassErrorDa', # CalculatedParentMass - MeasuredParentMass\n 'MassErrorPPM', # MassErrorDa / CalculatedParentMass\n 'ScanType',\n 'SearchName',\n 'ScoringFunction',\n 'Score',\n 'DeltaZ', # The difference score between the rank 1 and 2\n 'DeltaP', # The difference score between isoform\n 'IdentifiedPeptide',\n 'OriginalPeptide',\n 'ProteinNames',\n 'ProteinCount',\n 'TargetMatch',\n 'AveAtom',\n 'StdAtom'])):\n def __init__(self):\n self.data = self\n\n\n# # Class for PepSubFields object\nclass PepSubFields(namedtuple('PepSubFields',\n ['IdentifiedPeptide',\n 'ParentCharge',\n 'OriginalPeptide',\n 'ProteinNames',\n 'Score',\n 'Filename',\n 'ScanNumber',\n 'ScanType',\n 'SearchName'])):\n\n def __init__(self):\n self.data = self\n\n\n# # Class for PepSubFields object\nclass PepDataFields(namedtuple('PepDataFields',\n ['IdentifiedPeptide',\n 'ParentCharge',\n 'BestScore',\n 'ProteinNames'])):\n\n def __init__(self):\n self.data = self\n\n\n# # Class for PepOutFields object\nclass PepOutFields(namedtuple('PepOutFields',\n ['IdentifiedPeptide', # 0\n 'ParentCharge', # 1\n 'OriginalPeptide', # 2\n 'ProteinNames', # 3\n 'ProteinCount', # 4\n 'TargetMatch', # 5\n 'SpectralCount', # 6 number of PSMs matched to this peptide\n 'BestScore', # 7 the highest score of those PSMs\n 'PSMs', # 8 a list of PSMs matched to this peptide. Use {Filename[ScanNumber],Filename[ScanNumber]} format\n 'ScanType', # 9 ScanType\n 'SearchName'])): # 10 SearchName\n\n def __init__(self):\n self.data = self\n\n\n# # Class for pretty float\nclass PrettyFloat(float):\n def __repr__(self):\n return \"%0.5f\" % self\n\n\n# # A range function, that does accept float increments\ndef frange(start, end=None, inc=None):\n\n if end == None:\n end = start + 0.0\n start = 0.0\n\n if inc == None:\n inc = 1.0\n\n L = []\n while 1:\n fnext = start + len(L) * inc\n if inc > 0 and fnext >= end:\n break\n elif inc < 0 and fnext <= end:\n break\n L.append(fnext)\n\n return L\n\n\n# # check sub list\ndef check_sub_list(list_A, list_B):\n\n check_status = True\n\n for list_A_item in list_A:\n if list_A_item not in list_B:\n check_status = False\n else:\n continue\n\n return check_status\n\n\n# # get item list from parenthesis string as {AA,BB}\ndef get_item_list(input_string):\n\n input_string = input_string[1:-1]\n item_list = re.split(r\"\\s*[,]\\s*\", input_string.strip())\n\n return item_list\n\n\n# # get_protein_count\ndef get_protein_count(protein_names):\n\n input_string = protein_names[1:-1]\n item_list = re.split(r\"\\s*[,]\\s*\", input_string.strip())\n protein_count = len(item_list)\n\n return protein_count\n\n\n# # set float digit\ndef set_float_digit(input_val):\n\n if input_val is float:\n output_val = str(\"{0:.5f}\".format(round(input_val, 5)))\n else:\n output_val = str(input_val)\n\n return output_val\n\n# # peptide delete residues\ndef peptide_delete_residues(peptide_string):\n\n try:\n left_braket_index = peptide_string.index('[')\n right_braket_index = peptide_string.index(']')\n if len(peptide_string) > right_braket_index + 1:\n if peptide_string[right_braket_index + 1].isalpha():\n peptide_output = peptide_string[left_braket_index:right_braket_index + 1]\n else:\n peptide_output = peptide_string[left_braket_index:right_braket_index + 2]\n else:\n peptide_output = peptide_string[left_braket_index:right_braket_index + 1]\n\n return peptide_output\n except AttributeError:\n print >> sys.stderr, '\\nCannot parse peptide correctly.\\n'\n die(\"Program exit!\")\n\n\n# # merge protein names\ndef merge_protein_names(first_protein_names, second_protein_names):\n\n first_protein_list = get_item_list(first_protein_names)\n second_protein_list = get_item_list(second_protein_names)\n\n merge_protein_list = list(set(first_protein_list + second_protein_list))\n\n merge_protein_names = list_to_bracket(merge_protein_list)\n\n return merge_protein_names\n\n\n# # Task wrapper\nclass PsmPack:\n\n def __init__(self, _iSize=1000, _iStartScanNumber=0):\n self.iSize = _iSize\n self.lPsm = []\n for _i in range(_iSize):\n self.lPsm.append([])\n self.iStartScanNumber = _iStartScanNumber\n self.bEmpty = True\n self.current = 0\n\n def add(self, lOnePsm, iScanNumber):\n self.lPsm[iScanNumber - self.iStartScanNumber].append(lOnePsm)\n self.bEmpty = False\n\n def empty(self):\n return self.bEmpty\n\n def __iter__(self):\n self.current = 0\n return self\n\n def next(self):\n if self.current >= self.iSize:\n raise StopIteration\n else:\n while not self.lPsm[self.current]:\n self.current += 1\n if self.current >= self.iSize:\n raise StopIteration\n self.current += 1\n return self.lPsm[self.current - 1]\n\n\n# # the mass difference, inverted, larger better.\ndef MassDiff(oPepScores):\n fDiff = abs(oPepScores.fCalculatedParentMass - oPepScores.fMeasuredParentMass)\n return -fDiff\n\n# # the PTM score, the count of PTM, larger better\ndef PtmScore(oPepScores):\n s1 = ''.join([char if char.isalnum() else '$' for char in oPepScores.sIdentifiedPeptide ])\n return -(s1.count('$') - 2)\n\n# # Rank Product\ndef RankProductInvert(liRank):\n fProduct = 1.0\n for i in liRank:\n fProduct *= i\n return 1 / fProduct\n\n# # Pep info in the Spe2Pep file\nclass PepScores:\n\n def __init__(self, _fMeasuredParentMass, _iCharge, _sSearchName, sPeptideLine):\n self.fMeasuredParentMass = _fMeasuredParentMass\n self.iCharge = _iCharge\n asWords = sPeptideLine.split('\\t')\n self.sIdentifiedPeptide = peptide_delete_residues(asWords[1])\n self.sOriginalPeptide = peptide_delete_residues(asWords[2])\n # self.sIdentifiedPeptide = peptide_delete_residues(asWords[2])\n # self.sOriginalPeptide = peptide_delete_residues(asWords[1])\n self.fCalculatedParentMass = float(asWords[3])\n self.lfScores = []\n self.liRanks = []\n self.lfScoreDiff = [] # difference between the current one with the second best one\n for e in asWords[4:-1]:\n self.lfScores.append(float(e))\n # remove the {}\n self.sProteinNames = (asWords[-1])[1:-1]\n self.fRankProduct = 0.0\n self.iRank = 0\n self.sSearchName = _sSearchName\n # delta -> comet way\n # diff -> difference between current one to the next best one\n # diffnor -> difference between current one to the next best one normalized by the current one\n self.lfDeltaRankProduct = []\n self.lfDeltaRankScore = []\n self.lfDiffRankProduct = []\n self.lfDiffRankScore = []\n self.lfDiffNorRankProduct = []\n self.lfDiffNorRankScore = []\n self.DeltaP = 'NA'\n if len(self.sOriginalPeptide) != len(self.sIdentifiedPeptide):\n self.DeltaP = 1\n\ndef numberTopRanks(liRanks):\n iCount = 0\n for i in liRanks:\n if i == 1:\n iCount += 1\n return iCount\n\ndef zero_divide(a, b):\n if b != 0:\n return a / b\n else:\n return 0\n\n# # PSM info in the Spe2Pep file\nclass PepSpectrumMatch:\n\n iPurgeTrigger = 100\n iRankSave = 5\n\n def __init__(self, sSpectrumLine):\n asWords = sSpectrumLine.split('\\t')\n self.sFileName = asWords[1]\n self.iScanNumber = int(asWords[2])\n self.iParentCharge = int(asWords[3])\n self.fMeasuredParentMass = float(asWords[4])\n self.sScanType = asWords[5]\n self.sSearchName = asWords[6]\n self.fTotalIntensity = float(asWords[7])\n self.fMaxIntensity = float(asWords[8])\n self.sRTime = '-1.000'\n if len(asWords) >= 10:\n self.sRTime = asWords[9]\n self.lPepScores = []\n self.oBestPep = None\n self.oSecondBestPep = None\n self.oRestPep = None\n self.lTopPep = []\n\n def addPepScores(self, pep):\n for e in self.lPepScores:\n if e.sIdentifiedPeptide == pep.sIdentifiedPeptide:\n words = pep.sProteinNames.split(',')\n for sProtein in words:\n if e.sProteinNames.find(sProtein) == -1:\n e.sProteinNames += ','\n e.sProteinNames += sProtein\n return\n self.lPepScores.append(pep)\n if len(self.lPepScores) > self.iPurgeTrigger:\n self.purge()\n\n\n def purge(self):\n iNumScores = len(self.lPepScores[0].lfScores)\n for j in self.lPepScores:\n del j.liRanks[:]\n for i in range(iNumScores):\n lPep = sorted(self.lPepScores, key=lambda pep: (pep.lfScores[i], MassDiff(pep), PtmScore(pep), pep.sIdentifiedPeptide), reverse=True)\n iRank = 1\n for j in lPep:\n j.liRanks.append(iRank)\n iRank += 1\n liRanksNew = []\n for j in self.lPepScores:\n if any(i <= self.iRankSave for i in j.liRanks):\n liRanksNew.append(j)\n self.lPepScores = liRanksNew\n\n def ranking(self):\n del self.lTopPep[:]\n for j in self.lPepScores:\n del j.liRanks[:]\n del j.lfScoreDiff[:]\n iNumScores = len(self.lPepScores[0].lfScores)\n pep_rank_list = []\n for i in range(iNumScores):\n lPep = sorted(self.lPepScores, key=lambda pep: (pep.lfScores[i], MassDiff(pep), PtmScore(pep), pep.sIdentifiedPeptide), reverse=True)\n pep_rank_list.append(lPep)\n iRank = 1\n for j in lPep:\n j.liRanks.append(iRank)\n iRank += 1\n # score rank -> score differential\n for j in range(0, len(lPep) - 1):\n lPep[j].lfDeltaRankScore.append(1 - zero_divide(lPep[j + 1].lfScores[i], lPep[0].lfScores[i]))\n '''\n if j == 0:\n lPep[j].lfDeltaRankScore.append(1.0 - zero_divide(lPep[1].lfScores[i], lPep[0].lfScores[i]))\n else:\n lPep[j].lfDeltaRankScore.append(zero_divide(lPep[j].lfScores[i], lPep[0].lfScores[i]) - 1.0)\n '''\n lPep[j].lfDiffRankScore.append(lPep[j].lfScores[i] - lPep[j + 1].lfScores[i])\n lPep[j].lfDiffNorRankScore.append(zero_divide(lPep[j].lfScores[i] - lPep[j + 1].lfScores[i], lPep[j].lfScores[i]))\n lPep[len(lPep) - 1].lfDeltaRankScore.append(0)\n # lPep[len(lPep) - 1].lfDeltaRankScore.append(zero_divide(lPep[len(lPep) - 1].lfScores[i], lPep[0].lfScores[i]) - 1.0)\n lPep[len(lPep) - 1].lfDiffRankScore.append(0)\n lPep[len(lPep) - 1].lfDiffNorRankScore.append(0)\n \n self.lTopPep.append(lPep[0])\n if len(lPep) >= 2:\n for j in lPep:\n j.lfScoreDiff.append(j.lfScores[i] - lPep[1].lfScores[i])\n else:\n j.lfScoreDiff.append(0.0)\n\n # rank product -> score differential\n for i in self.lPepScores:\n i.fRankProduct = RankProductInvert(i.liRanks)\n # lPep: ranked by rank product\n lPep = sorted(self.lPepScores, key=lambda pep: (pep.fRankProduct, MassDiff(pep), PtmScore(pep), pep.sIdentifiedPeptide), reverse=True)\n for j in range(0, len(lPep) - 1):\n lPep[j].iRank = j\n for i in range(iNumScores):\n lPep[j].lfDeltaRankProduct.append(1 - zero_divide(lPep[j + 1].lfScores[i], lPep[0].lfScores[i]))\n lPep[j].lfDiffRankProduct.append(lPep[j].lfScores[i] - lPep[j + 1].lfScores[i])\n lPep[j].lfDiffNorRankProduct.append(zero_divide(lPep[j].lfScores[i] - lPep[j + 1].lfScores[i], lPep[j].lfScores[i]))\n lPep[-1].iRank = len(lPep) - 1\n \n for i in range(iNumScores):\n lPep[len(lPep) - 1].lfDeltaRankProduct.append(0)\n lPep[len(lPep) - 1].lfDiffRankProduct.append(0)\n lPep[len(lPep) - 1].lfDiffNorRankProduct.append(0)\n \n for i in self.lTopPep:\n if numberTopRanks(i.liRanks) >= 2:\n self.oBestPep = i\n self.iParentCharge = self.oBestPep.iCharge\n self.sSearchName = self.oBestPep.sSearchName\n if len(lPep) > 1:\n if self.oBestPep == lPep[0]:\n self.oSecondBestPep = lPep[1]\n else:\n self.oSecondBestPep = lPep[0]\n # PTM in the best pep\n if len(i.sIdentifiedPeptide) != len(i.sOriginalPeptide):\n for pep in lPep:\n if pep.sIdentifiedPeptide != i.sIdentifiedPeptide and \\\n abs(pep.fCalculatedParentMass - i.fCalculatedParentMass) < 0.00005 and \\\n abs(math.fabs(pep.fMeasuredParentMass - pep.fCalculatedParentMass) - math.fabs(i.fMeasuredParentMass - i.fCalculatedParentMass)) < 0.00005 and \\\n pep.sOriginalPeptide == i.sOriginalPeptide and \\\n len(pep.sIdentifiedPeptide) == len(i.sIdentifiedPeptide):\n avg_deltaP = 0.0\n for s in range(iNumScores):\n if self.lTopPep[s].lfScores[s] != 0:\n avg_deltaP += (i.lfScores[s] - pep.lfScores[s])/self.lTopPep[s].lfScores[s]\n avg_deltaP /= float(iNumScores)\n self.oBestPep.DeltaP = avg_deltaP\n return\n return\n # if SA == 1, calculate DeltaP individually\n for s in range(iNumScores):\n for lPep_local in pep_rank_list:\n # contain PTM\n if len(lPep_local[0].sIdentifiedPeptide) != len(lPep_local[0].sOriginalPeptide):\n for pep in lPep_local:\n if pep.sIdentifiedPeptide != lPep_local[0].sIdentifiedPeptide and \\\n abs(pep.fCalculatedParentMass - lPep_local[0].fCalculatedParentMass) < 0.00005 and \\\n abs(math.fabs(pep.fMeasuredParentMass - pep.fCalculatedParentMass) - math.fabs(lPep_local[0].fMeasuredParentMass - lPep[0].fCalculatedParentMass)) < 0.00005 and \\\n pep.sOriginalPeptide == lPep_local[0].sOriginalPeptide and \\\n len(pep.sIdentifiedPeptide) == len(lPep_local[0].sIdentifiedPeptide):\n avg_deltaP = 0.0\n for si in range(iNumScores):\n if self.lTopPep[si].lfScores[si] != 0:\n avg_deltaP += (lPep_local[0].lfScores[si] - pep.lfScores[si])/self.lTopPep[si].lfScores[si]\n avg_deltaP /= float(iNumScores)\n lPep_local[0].DeltaP = avg_deltaP\n break\n self.oBestPep = lPep[0]\n self.iParentCharge = self.oBestPep.iCharge\n self.sSearchName = self.oBestPep.sSearchName\n if len(lPep) > 1:\n if self.oBestPep == lPep[0]:\n self.oSecondBestPep = lPep[1]\n else:\n self.oSecondBestPep = lPep[0]\n # debug\n # if protein_type(self.oBestPep.sProteinNames) == -1:\n # pass\n\n def __repr__(self):\n # Filename ScanNumber ParentCharge MeasuredParentMass ScanType SearchName\n # IdentifiedPeptide OriginalPeptide CalculatedParentMass MVH WDP Xcorr ProteinNames\n return \"%s\\t%d\\t%d\\t%f\\t%s\\t%s\\t%s\\t%s\\t%f\\t%f\\t%f\\t%f\\t{%s}\" % (self.sFileName,\n self.iScanNumber,\n self.iParentCharge,\n self.fMeasuredParentMass,\n self.sScanType,\n self.sSearchName,\n self.oBestPep.sIdentifiedPeptide,\n self.oBestPep.sOriginalPeptide,\n self.oBestPep.fCalculatedParentMass,\n self.oBestPep.lfScores[0],\n self.oBestPep.lfScores[1],\n self.oBestPep.lfScores[2],\n self.oBestPep.sProteinNames)\n\n def get_other_features(self):\n # score differential\n # comet way\n # difference\n # difference normalization\n if len(self.oBestPep.lfDeltaRankProduct) == 0:\n return '0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000'\n \n return \"%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\" % (self.oBestPep.lfDeltaRankProduct[0],\n self.oBestPep.lfDeltaRankProduct[1],\n self.oBestPep.lfDeltaRankProduct[2],\n self.oBestPep.lfDeltaRankScore[0],\n self.oBestPep.lfDeltaRankScore[1],\n self.oBestPep.lfDeltaRankScore[2],\n self.oBestPep.lfDiffRankProduct[0],\n self.oBestPep.lfDiffRankProduct[1],\n self.oBestPep.lfDiffRankProduct[2],\n self.oBestPep.lfDiffRankScore[0],\n self.oBestPep.lfDiffRankScore[1],\n self.oBestPep.lfDiffRankScore[2],\n self.oBestPep.lfDiffNorRankProduct[0],\n self.oBestPep.lfDiffNorRankProduct[1],\n self.oBestPep.lfDiffNorRankProduct[2],\n self.oBestPep.lfDiffNorRankScore[0],\n self.oBestPep.lfDiffNorRankScore[1],\n self.oBestPep.lfDiffNorRankScore[2])\n \n def get_second_pep(self):\n return \"%s\\t%d\\t%d\\t%f\\t%s\\t%s\\t%s\\t%s\\t%f\\t%f\\t%f\\t%f\\t{%s}\" % (self.sFileName,\n self.iScanNumber,\n self.oSecondBestPep.iCharge,\n self.fMeasuredParentMass,\n self.sScanType,\n self.oSecondBestPep.sSearchName,\n self.oSecondBestPep.sIdentifiedPeptide,\n self.oSecondBestPep.sOriginalPeptide,\n self.oSecondBestPep.fCalculatedParentMass,\n self.oSecondBestPep.lfScores[0],\n self.oSecondBestPep.lfScores[1],\n self.oSecondBestPep.lfScores[2],\n self.oSecondBestPep.sProteinNames)\n \n def get_other_features_second_pep(self):\n if len(self.oSecondBestPep.lfDeltaRankProduct) == 0:\n return '0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000\\t0.000'\n return \"%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\" % (self.oBestPep.lfDeltaRankProduct[0],\n self.oSecondBestPep.lfDeltaRankProduct[1],\n self.oSecondBestPep.lfDeltaRankProduct[2],\n self.oSecondBestPep.lfDeltaRankScore[0],\n self.oSecondBestPep.lfDeltaRankScore[1],\n self.oSecondBestPep.lfDeltaRankScore[2],\n self.oSecondBestPep.lfDiffRankProduct[0],\n self.oSecondBestPep.lfDiffRankProduct[1],\n self.oSecondBestPep.lfDiffRankProduct[2],\n self.oSecondBestPep.lfDiffRankScore[0],\n self.oSecondBestPep.lfDiffRankScore[1],\n self.oSecondBestPep.lfDiffRankScore[2],\n self.oSecondBestPep.lfDiffNorRankProduct[0],\n self.oSecondBestPep.lfDiffNorRankProduct[1],\n self.oSecondBestPep.lfDiffNorRankProduct[2],\n self.oSecondBestPep.lfDiffNorRankScore[0],\n self.oSecondBestPep.lfDiffNorRankScore[1],\n self.oSecondBestPep.lfDiffNorRankScore[2])\n \n def all_top_ranked_psm(self):\n str_list = []\n for pep in self.lTopPep:\n feature_list = []\n feature_list.append(self.sFileName)\n feature_list.append(str(self.iScanNumber))\n feature_list.append(str(self.iParentCharge))\n feature_list.append(str(self.fMeasuredParentMass))\n feature_list.append(self.sScanType)\n feature_list.append(self.sSearchName)\n feature_list.append(pep.sIdentifiedPeptide)\n feature_list.append(pep.sOriginalPeptide)\n feature_list.append(str(pep.fCalculatedParentMass))\n feature_list.extend((str(x) for x in pep.lfScores))\n feature_list.append('{'+pep.sProteinNames+'}')\n feature_list.append(str(num_agreement(pep.liRanks)))\n feature_list.extend((str(x) for x in pep.lfDeltaRankProduct))\n feature_list.extend((str(x) for x in pep.lfDeltaRankScore))\n feature_list.extend((str(x) for x in pep.lfDiffRankProduct))\n feature_list.extend((str(x) for x in pep.lfDiffRankScore))\n feature_list.extend((str(x) for x in pep.lfDiffNorRankProduct))\n feature_list.extend((str(x) for x in pep.lfDiffNorRankScore))\n feature_list.append(self.sRTime)\n feature_list.append((str(pep.iRank)))\n feature_list.append((str(pep.DeltaP)))\n str_list.append('\\t'.join(feature_list))\n return '\\n'.join(str_list)\n \n def pin(self):\n lPin = []\n '''\n id label ScanNr \n ScoreAgreement \n deltCn Xcorr Mass \n PepLen Charge1 Charge2 \n Charge3 Charge4 Charge5 \n Charge6 enzInt dM absdM \n peptide proteinId1\n '''\n lPin.append((self.sFileName\n + '_'\n + str(self.iScanNumber)\n + '_'\n + str(self.iParentCharge)))\n lProteins = []\n iType = protein_type(self.oBestPep.sProteinNames, lProteins)\n if iType == 2:\n lPin.append('-1')\n else:\n lPin.append('1')\n lProteins = self.removeReverse(lProteins)\n lPin.append(str(self.iScanNumber))\n lPin.append(str(num_agreement(self.oBestPep.liRanks)))\n lPin.append(str(self.oBestPep.lfScoreDiff[0]))\n lPin.append(str(self.oBestPep.lfScores[0]))\n lPin.append(str(math.log(self.oBestPep.liRanks[0])))\n lPin.append(str(self.oBestPep.lfScoreDiff[1]))\n lPin.append(str(self.oBestPep.lfScores[1]))\n lPin.append(str(math.log(self.oBestPep.liRanks[1])))\n lPin.append(str(self.oBestPep.lfScoreDiff[2]))\n lPin.append(str(self.oBestPep.lfScores[2]))\n lPin.append(str(math.log(self.oBestPep.liRanks[2])))\n lPin.append(str(self.fMeasuredParentMass))\n lPin.append(str(len(self.oBestPep.sOriginalPeptide) - 2))\n for i in range(1, 6, 1):\n if self.iParentCharge == i:\n lPin.append('1')\n else:\n lPin.append('0')\n if self.iParentCharge >= 6:\n lPin.append('1')\n else:\n lPin.append('0')\n lPin.append(str(self.enzInt()))\n fTemp = self.fMeasuredParentMass - self.oBestPep.fCalculatedParentMass\n lPin.append(str(fTemp))\n lPin.append(str(abs(fTemp)))\n lPin.append(self.percolatorPeptide())\n # lPin.extend(lProteins)\n lPin.append(lProteins[0])\n return ('\\t'.join(lPin), len(lProteins))\n\n def removeReverse(self, lProteins):\n newlist = []\n for sProtein in lProteins:\n if not sProtein.startswith('Rev_'):\n newlist.append(sProtein)\n return newlist\n\n def percolatorPeptide(self):\n return 'K.' + self.oBestPep.sIdentifiedPeptide[1:-1] + '.A'\n\n def enzInt(self):\n iNumIntEnz = -1\n iNumIntEnz += self.oBestPep.sIdentifiedPeptide.count('K')\n iNumIntEnz += self.oBestPep.sIdentifiedPeptide.count('R')\n return iNumIntEnz\n\n# # lOnePsm: + spectrum * peptide * peptide + spectrum\ndef SelectTopRankedPsm(lOnePsm):\n psm = PepSpectrumMatch(lOnePsm[0][0])\n '''\n if psm.iScanNumber == 18472:\n print 'check'\n '''\n iCharge = 0\n sSearchName = ''\n for PsmInOneFile in lOnePsm:\n for sline in PsmInOneFile:\n if sline[0] == '+':\n # a spectrum line\n iCharge = get_charge(sline)\n sSearchName = get_search_name(sline)\n else:\n # a peptide line\n pep = PepScores(psm.fMeasuredParentMass, iCharge, sSearchName, sline)\n psm.addPepScores(pep)\n # sorting and then ranking\n psm.ranking()\n return psm\n\n# # peak a line from the file\ndef peek_line(f):\n pos = f.tell()\n sline = f.readline()\n f.seek(pos)\n return sline\n\n# # get the scan number from a line\ndef get_scan_number(sLine, sDelimiter='\\t', iFirstDelimiter=2):\n iPos = -1\n while iFirstDelimiter > 0:\n iPos = sLine.find(sDelimiter, iPos + 1)\n iFirstDelimiter -= 1\n iBegin = iPos + 1\n iPos = sLine.find(sDelimiter, iBegin)\n iScanNumber = int(sLine[iBegin:iPos])\n return iScanNumber\n\n# # get the charge from a line\ndef get_charge(sLine, sDelimiter='\\t', iFirstDelimiter=3):\n iPos = -1\n while iFirstDelimiter > 0:\n iPos = sLine.find(sDelimiter, iPos + 1)\n iFirstDelimiter -= 1\n iBegin = iPos + 1\n iPos = sLine.find(sDelimiter, iBegin)\n iCharge = int(sLine[iBegin:iPos])\n return iCharge\n\n# # get the search name from a line\ndef get_search_name(sLine, sDelimiter='\\t', iFirstDelimiter=6):\n iPos = -1\n while iFirstDelimiter > 0:\n iPos = sLine.find(sDelimiter, iPos + 1)\n iFirstDelimiter -= 1\n iBegin = iPos + 1\n iPos = sLine.find(sDelimiter, iBegin)\n sSearchName = sLine[iBegin:iPos]\n return sSearchName\n\n# # get the PSM with scan number less than the upper scan number bound\ndef get_psm(f, lPsm, sSpectrum='+', sPeptide='*', iUpperScanNumber=0):\n bEof = True\n lOnePsm = []\n while True:\n pos = f.tell()\n sline = f.readline().strip()\n # # end of file\n if not sline:\n break\n iScanNumber = 0\n if sline[0] == sSpectrum:\n iScanNumber = get_scan_number(sline)\n if iScanNumber < iUpperScanNumber:\n bEof = False\n lOnePsm = []\n lOnePsm.append(sline)\n lPsm.add(lOnePsm, iScanNumber)\n else:\n # roll back the previous position\n f.seek(pos)\n bEof = False\n break\n else:\n lOnePsm.append(sline)\n return bEof\n\n# # skip the comment area and the header\ndef skip_comment(f, sComment='#', iLineHeader=0):\n pos = f.tell()\n sline = f.readline()\n while(sline[0] == sComment):\n pos = f.tell()\n sline = f.readline()\n f.seek(pos)\n for _i in range(iLineHeader):\n f.readline()\n # print f.readline()\n\n# # Spe2Pep reader\nclass Spe2PepReader(Process):\n\n def __init__(self, queue=None, name=None, searchname=None, inputFolder=None):\n super(Spe2PepReader, self).__init__()\n self.name = name\n self.qPsmUnprocessed = queue;\n self.iNumScanProcessed = 0\n self.sSearchName = searchname\n self.FileList = []\n self.iScanInterval = 1000\n self.sInputFolder = inputFolder\n\n # # list files with 'Spe2Pep.txt' extensions\n # # put the search results for the same FT2 file into a list\n def categorizeSpe2PepFile(self, sWorkingDirectory):\n lFileList = get_file_list_with_ext(sWorkingDirectory, 'Spe2Pep.txt')\n sFt2Name = ''\n lFt2Name = []\n iIndexFt2 = 0\n for sFileName in lFileList:\n iPos = sFileName.rfind(self.sSearchName)\n if iPos != -1:\n # a '.' is before the search name, so iPos-1\n sFt2Name = sFileName[0:iPos - 1]\n if sFt2Name in lFt2Name:\n iIndexFt2 = lFt2Name.index(sFt2Name)\n self.FileList[iIndexFt2].append(sFileName)\n else:\n lFt2Name.append(sFt2Name)\n lNewFt2 = []\n lNewFt2.append(sFileName)\n self.FileList.append(lNewFt2)\n\n def readData(self):\n for _id, lFiles in enumerate(self.FileList):\n lFileReader = []\n for sFiles in lFiles:\n oFile = open(sFiles, 'r')\n skip_comment(oFile, iLineHeader=2)\n lFileReader.append(oFile)\n # # peek the first scan number\n iSmallestScanNumer = sys.maxint\n for f in lFileReader:\n sLine = peek_line(f)\n iScanNumber = get_scan_number(sLine)\n if iScanNumber < iSmallestScanNumer:\n iSmallestScanNumer = iScanNumber\n # #\n iLastScanExcluded = iSmallestScanNumer\n bReachEof = False\n while(not bReachEof):\n psmPack = PsmPack(_iSize=self.iScanInterval, _iStartScanNumber=iLastScanExcluded)\n iLastScanExcluded = iLastScanExcluded + self.iScanInterval\n bReachEof = True\n for f in lFileReader:\n bReachEof = bReachEof & (get_psm(f, psmPack, iUpperScanNumber=iLastScanExcluded))\n if not psmPack.empty():\n # # add to the job queue\n for psm in psmPack:\n self.qPsmUnprocessed.put(psm, True)\n self.iNumScanProcessed += 1\n if self.iNumScanProcessed % 100 == 0:\n pass\n # print 'Read # scans %d' % self.iNumScanProcessed\n # print 'Queue size %f' % self.qPsmUnprocessed.qsize()\n\n # # close the file reader\n for f in lFileReader:\n f.close()\n\n def run(self):\n if not self.qPsmUnprocessed:\n sys.stderr.write(\"Job Queue error in PSM reading.\")\n self.categorizeSpe2PepFile(self.sInputFolder)\n self.readData()\n self.qPsmUnprocessed.put(None)\n\n# # thread class for ranking the PSM\nclass RankPsm(Process):\n\n def __init__(self, qPsmUnprocessed, qPsmProcessed, name=None):\n super(RankPsm, self).__init__()\n self.name = name\n self.qPsmUnprocessed = qPsmUnprocessed\n self.qPsmProcessed = qPsmProcessed\n self.iCount = 0\n return\n\n def run(self):\n if not self.qPsmUnprocessed:\n sys.stderr.write(\"Job Queue error in PSM ranking.\")\n if not self.qPsmProcessed:\n sys.stderr.write(\"Job Queue error in PSM ranking.\")\n while True:\n psm = self.qPsmUnprocessed.get(True)\n if psm is None:\n break\n oPsm = SelectTopRankedPsm(psm)\n del psm\n self.iCount += 1\n if self.iCount % 10 == 0:\n pass\n # print \"Rank # scans %i\" % self.iCount\n self.qPsmProcessed.put(oPsm, True)\n self.qPsmProcessed.put(None)\n self.qPsmUnprocessed.put(None)\n return\n\n\n# # Decoy Reverse Forward protein\ndef protein_type(protein_sequence, lProtein=None):\n sProteins = protein_sequence.replace('{', '')\n sProteins = sProteins.replace('}', '')\n asProteins = sProteins.split(',')\n if lProtein != None:\n del lProtein[:]\n lProtein.extend(asProteins[:])\n for sProtein in asProteins:\n if not (sProtein.startswith('Rev_') or sProtein.startswith('Dec_')):\n return 1\n for sProtein in asProteins:\n if sProtein.startswith('Dec_'):\n return 3\n return 2\n\n# # score agreement recode\ndef agreement(liRank):\n iIndex = 0\n for i in liRank:\n if i == 1:\n iIndex = (iIndex << 1) + 1;\n else:\n iIndex = (iIndex << 1)\n return iIndex\n\n# # number of score agreement\ndef num_agreement(liRanks):\n iNum = 0\n for i in liRanks:\n if i == 1:\n iNum += 1\n return iNum\n\n# # write the PSM table\ndef writePin(sOutputFile, qPsmProcessed, iNumRankers):\n iNumTarget = 0\n iNumReverse = 0\n iNumShuffle = 0\n iNumProcessedScans = 0\n liAgreeRecord = []\n liTarget = []\n liReverse = []\n liShuffle = []\n for _i in range(8):\n liAgreeRecord.append(0)\n liTarget.append(0)\n liReverse.append(0)\n liShuffle.append(0)\n iMaxNumProtein = 0\n with open(sOutputFile, 'w') as f:\n # PSM\n while True:\n psm = qPsmProcessed.get(True)\n if psm is None:\n iNumRankers -= 1\n if iNumRankers == 0:\n break\n else:\n continue\n (sLine, iNumProteins) = psm.pin()\n if iNumProteins > iMaxNumProtein:\n iMaxNumProtein = iNumProteins\n f.write(sLine)\n f.write('\\n')\n iTemp2 = agreement(psm.oBestPep.liRanks)\n liAgreeRecord[iTemp2] += 1\n iTemp = protein_type(psm.oBestPep.sProteinNames)\n if iTemp == 1:\n iNumTarget += 1\n liTarget[iTemp2] += 1\n elif iTemp == 2:\n iNumReverse += 1\n liReverse[iTemp2] += 1\n else:\n iNumShuffle += 1\n liShuffle[iTemp2] += 1\n del psm\n iNumProcessedScans += 1\n if iNumProcessedScans % 100 == 0:\n print(\" Processed & Saved %i Scans\\r\" % iNumProcessedScans)\n\n print(\"\\nTarget #: %d\\tReverse #: %d\\tShuffle #: %d\" % (iNumTarget, iNumReverse, iNumShuffle))\n print(liAgreeRecord)\n print(liTarget)\n print(liReverse)\n print(liShuffle)\n print('Max number of proteins: %i' % iMaxNumProtein)\n\nbAdditionalFeatures = True\nheader_message_additional_feature = '\\tDeltaRP1\\tDeltaRP2\\tDeltaRP3\\tDeltaRS1\\tDeltaRS2\\tDeltaRS3\\tDiffRP1\\tDiffRP2\\tDiffRP3\\tDiffRS1\\tDiffRS2\\tDiffRS3\\tDiffNorRP1\\tDiffNorRP2\\tDiffNorRP3\\tDiffNorRS1\\tDiffNorRS2\\tDiffNorRS3'\nbExtraNegativePsm = False\nbRTime = True\nbAdditionPepScoreAgreementNotThree = True\n\n# # write the PSM table\ndef writePsm(sOutputFile, qPsmProcessed, iNumRankers):\n iNumTarget = 0\n iNumReverse = 0\n iNumShuffle = 0\n iNumProcessedScans = 0\n liAgreeRecord = []\n liTarget = []\n liReverse = []\n liShuffle = []\n for _i in range(8):\n liAgreeRecord.append(0)\n liTarget.append(0)\n liReverse.append(0)\n liShuffle.append(0)\n if bExtraNegativePsm:\n sOutputFileExtraNegativePsm = sOutputFile[:-4] + '_nagative.tab'\n fExtra = open(sOutputFileExtraNegativePsm, 'w')\n \n with open(sOutputFile, 'w') as f:\n # header\n f.write('FileName\\t')\n f.write('ScanNumber\\t')\n f.write('ParentCharge\\t')\n f.write('MeasuredParentMass\\t')\n f.write('ScanType\\t')\n f.write('SearchName\\t')\n f.write('IdentifiedPeptide\\t')\n f.write('OriginalPeptide\\t')\n f.write('CalculatedParentMass\\t')\n f.write('MVH\\t')\n f.write('Xcorr\\t')\n f.write('WDP\\t')\n f.write('ProteinNames\\t')\n f.write('ScoreAgreement')\n if bAdditionalFeatures:\n f.write(header_message_additional_feature)\n if bRTime:\n f.write('\\tRetentionTime')\n f.write('\\n')\n \n if bExtraNegativePsm:\n fExtra.write('FileName\\t')\n fExtra.write('ScanNumber\\t')\n fExtra.write('ParentCharge\\t')\n fExtra.write('MeasuredParentMass\\t')\n fExtra.write('ScanType\\t')\n fExtra.write('SearchName\\t')\n fExtra.write('IdentifiedPeptide\\t')\n fExtra.write('OriginalPeptide\\t')\n fExtra.write('CalculatedParentMass\\t')\n fExtra.write('MVH\\t')\n fExtra.write('Xcorr\\t')\n fExtra.write('WDP\\t')\n fExtra.write('ProteinNames\\t')\n fExtra.write('ScoreAgreement')\n if bAdditionalFeatures:\n fExtra.write(header_message_additional_feature)\n fExtra.write('\\n')\n \n # PSM\n while True:\n psm = qPsmProcessed.get(True)\n if psm is None:\n iNumRankers -= 1\n if iNumRankers == 0:\n break\n else:\n continue\n \n if bAdditionPepScoreAgreementNotThree and num_agreement(psm.oBestPep.liRanks) < 2:\n f.write(psm.all_top_ranked_psm())\n else:\n f.write(repr(psm))\n f.write('\\t')\n #f.write(str(agreement(psm.oBestPep.liRanks)))\n if bAdditionalFeatures:\n f.write(str(num_agreement(psm.oBestPep.liRanks)))\n f.write('\\t')\n f.write(psm.get_other_features())\n else:\n f.write(str(num_agreement(psm.oBestPep.liRanks)))\n if bRTime:\n f.write('\\t')\n f.write(psm.sRTime)\n f.write('\\t')\n f.write(str(psm.oBestPep.iRank))\n f.write('\\t')\n f.write(str(psm.oBestPep.DeltaP))\n \n f.write('\\n')\n iTemp2 = agreement(psm.oBestPep.liRanks)\n liAgreeRecord[iTemp2] += 1\n iTemp = protein_type(psm.oBestPep.sProteinNames)\n if iTemp == 1:\n iNumTarget += 1\n liTarget[iTemp2] += 1\n elif iTemp == 2:\n iNumReverse += 1\n liReverse[iTemp2] += 1\n else:\n iNumShuffle += 1\n liShuffle[iTemp2] += 1\n \n if bExtraNegativePsm and psm.oSecondBestPep != None:\n fExtra.write(psm.get_second_pep())\n fExtra.write('\\t')\n if bAdditionalFeatures:\n fExtra.write(str(num_agreement(psm.oSecondBestPep.liRanks)))\n fExtra.write('\\t')\n fExtra.write(psm.get_other_features())\n else:\n fExtra.write(str(num_agreement(psm.oSecondBestPep.liRanks)))\n fExtra.write('\\n')\n \n del psm\n iNumProcessedScans += 1\n if iNumProcessedScans % 100 == 0:\n print(\" Processed & Saved %i Scans\\r\" % iNumProcessedScans)\n \n if bExtraNegativePsm:\n fExtra.close()\n \n print(\"\\nTarget #: %d\\tReverse #: %d\\tShuffle #: %d\" % (iNumTarget, iNumReverse, iNumShuffle))\n print(liAgreeRecord)\n print(liTarget)\n print(liReverse)\n print(liShuffle)\n\nfrom lxml.etree import ElementTree, Element, SubElement\n\npep_iden_str = '[Peptide_Identification]'\nsearch_name_str = 'Search_Name'\nFASTA_Database_str = 'FASTA_Database'\nMaximum_Missed_Cleavages_str = 'Maximum_Missed_Cleavages'\nCleave_After_Residues_str = 'Cleave_After_Residues'\n\ndef get_num_missed_cleavages(peptide_str, cleave_residues_str):\n num = 0\n for c in cleave_residues_str:\n num += peptide_str.count(c)\n\n return str(num - 1)\n\ndef get_modification_info(peptide_str, modification_label_dict):\n modification_dict = {}\n for key, value in modification_label_dict.iteritems():\n beg = -1\n beg = peptide_str.find(key, beg + 1)\n while beg != -1:\n modification_dict[str(beg - len(modification_dict))] = value\n beg = peptide_str.find(key, beg + 1)\n return modification_dict\n\ndef write_PepXML(output_folder, qPsmProcessed, iNumRankers, config_dict):\n\n input_filename = ''\n root = Element('msms_pipeline_analysis')\n iIndexUnique = 1\n iScoreId = 1 # 0: MVH, 1: Xcorr, 2: WDP\n score_list_str = ['mvh', 'xcorr', 'mvh']\n search_engine_str = ['MyriMatch', 'Comet', 'MyriMatch']\n iNumProcessedScans = 0\n cleave_residues_str = config_dict[Cleave_After_Residues_str]\n\n modification_label_dict = {'~':'15.994915', '!': '0.984016'}\n\n while True:\n psm = qPsmProcessed.get(True)\n if psm is None:\n iNumRankers -= 1\n if iNumRankers == 0:\n break\n else:\n continue\n if input_filename != psm.sFileName.split('.')[0]:\n if input_filename != '':\n document = ElementTree(root)\n document.write((output_folder + input_filename + '.pep.xml'),\n encoding='ISO-8859-1',\n xml_declaration=True,\n pretty_print=True)\n iIndexUnique = 1\n input_filename = psm.sFileName.split('.')[0]\n xmlns = \"http://regis-web.systemsbiology.net/pepXML\"\n xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n schemaLocation = \"http://sashimi.sourceforge.net/schema_revision/pepXML/pepXML_v117.xsd\"\n root = Element(\"{\" + xmlns + \"}msms_pipeline_analysis\",\n nsmap={'xsi':xsi, None:xmlns},\n attrib={\"{\" + xsi + \"}schemaLocation\" : schemaLocation})\n root.set('date', datetime.now().isoformat())\n root.set('summary_xml', (input_filename + '.pepXML'))\n # root.set('xmlns', \"http://regis-web.systemsbiology.net/pepXML\")\n # root.set('xmlns:xsi', \"http://www.w3.org/2001/XMLSchema-instance\")\n # root.set('xsi:schemaLocation', \"http://sashimi.sourceforge.net/schema_revision/pepXML/pepXML_v117.xsd\")\n\n if iScoreId != 1: # Xcorr does not need analysis summary\n analysis_summary = SubElement(root, 'analysis_summary')\n analysis_summary.set('analysis', \"Sipros\")\n analysis_summary.set('version', \"10\")\n analysis_summary.set('time', (datetime.now().isoformat()))\n\n msms_run_summary = SubElement(root, 'msms_run_summary')\n msms_run_summary.set('base_name', input_filename)\n msms_run_summary.set('raw_data_type', \"raw\")\n msms_run_summary.set('raw_data', \"ms2\")\n\n sample_enzyme = SubElement(msms_run_summary, 'sample_enzyme')\n sample_enzyme.set('name', \"Trypsin/P\")\n sample_enzyme.set('independent', \"false\")\n sample_enzyme.set('fidelity', \"specific\")\n\n specificity = SubElement(sample_enzyme, 'specificity')\n specificity.set('sense', \"C\")\n specificity.set('cut', \"KR\")\n specificity.set('no_cut', \"\")\n specificity.set('min_spacing', \"1\")\n\n search_summary = SubElement(msms_run_summary, \"search_summary\")\n search_summary.set('base_name', input_filename)\n search_summary.set('search_engine', search_engine_str[iScoreId])\n search_summary.set('precursor_mass_type', 'monoisotopic')\n search_summary.set('fragment_mass_type', 'monoisotopic')\n search_summary.set('out_data_type', '')\n search_summary.set('out_data', '')\n\n search_database = SubElement(search_summary, 'search_database')\n search_database.set('local_path', config_dict[FASTA_Database_str])\n search_database.set('database_name', 'SDB')\n search_database.set('type', 'AA')\n\n enzymatic_search_constraint = SubElement(search_summary, 'enzymatic_search_constraint')\n enzymatic_search_constraint.set('enzyme', 'Trypsin/P')\n enzymatic_search_constraint.set('max_num_internal_cleavages', config_dict[Maximum_Missed_Cleavages_str])\n enzymatic_search_constraint.set('min_number_termini', '2')\n\n aminoacid_modification = SubElement(search_summary, 'aminoacid_modification')\n aminoacid_modification.set('aminoacid', 'M')\n aminoacid_modification.set('massdiff', '15.994915')\n aminoacid_modification.set('mass', '147.0353846062')\n aminoacid_modification.set('variable', 'Y')\n # aminoacid_modification.set('symbol', '~')\n\n aminoacid_modification = SubElement(search_summary, 'aminoacid_modification')\n aminoacid_modification.set('aminoacid', 'C')\n aminoacid_modification.set('massdiff', '57.021464')\n aminoacid_modification.set('mass', '160.030649')\n aminoacid_modification.set('variable', 'N')\n\n # aminoacid_modification = SubElement(search_summary, 'aminoacid_modification')\n # aminoacid_modification.set('aminoacid', 'N')\n # aminoacid_modification.set('massdiff', '0.984016')\n # aminoacid_modification.set('variable', 'Y')\n # aminoacid_modification.set('symbol', '!')\n\n # aminoacid_modification = SubElement(search_summary, 'aminoacid_modification')\n # aminoacid_modification.set('aminoacid', 'Q')\n # aminoacid_modification.set('massdiff', '0.984016')\n # aminoacid_modification.set('variable', 'Y')\n # aminoacid_modification.set('symbol', '!')\n\n # query results\n spectrum_query = SubElement(msms_run_summary, 'spectrum_query')\n ScanNumber_str = str(psm.iScanNumber)\n ParentCharge_str = str(psm.iParentCharge)\n spectrum_query.set('spectrum', input_filename + '.' + ScanNumber_str + '.' + ScanNumber_str + '.' + ParentCharge_str)\n spectrum_query.set('start_scan', ScanNumber_str)\n spectrum_query.set('end_scan', ScanNumber_str)\n spectrum_query.set('precursor_neutral_mass', str(psm.fMeasuredParentMass))\n spectrum_query.set('assumed_charge', ParentCharge_str)\n spectrum_query.set('index', str(iIndexUnique))\n\n search_result = SubElement(spectrum_query, 'search_result')\n for oPepScores in psm.lPepScores:\n if oPepScores.liRanks[iScoreId] > 5:\n continue\n search_hit = SubElement(search_result, 'search_hit')\n search_hit.set('hit_rank', str(oPepScores.liRanks[iScoreId]))\n search_hit.set('peptide', oPepScores.sOriginalPeptide[1:-1])\n lProteins = oPepScores.sProteinNames.split(',')\n search_hit.set('protein', lProteins[0])\n search_hit.set('num_tot_proteins', str(len(lProteins)))\n search_hit.set('calc_neutral_pep_mass', str(oPepScores.fCalculatedParentMass))\n search_hit.set('massdiff', str(psm.fMeasuredParentMass - oPepScores.fCalculatedParentMass))\n search_hit.set('num_tol_term', '2')\n search_hit.set('num_missed_cleavages', get_num_missed_cleavages(oPepScores.sIdentifiedPeptide, cleave_residues_str))\n # alternative_protein\n if len(lProteins) > 1:\n for iProteins in range(1, len(lProteins)):\n alternative_protein = SubElement(search_hit, 'alternative_protein')\n alternative_protein.set('protein', lProteins[iProteins])\n # modification_info\n modification_dict = get_modification_info(oPepScores.sIdentifiedPeptide[1:-1], modification_label_dict)\n if modification_dict:\n modification_info = SubElement(search_hit, \"modification_info\")\n for key, value in modification_dict.iteritems():\n mod_aminoacid_mass = SubElement(modification_info, 'mod_aminoacid_mass')\n mod_aminoacid_mass.set('position', key)\n mod_aminoacid_mass.set('mass', value)\n # search_score\n search_score = SubElement(search_hit, 'search_score')\n search_score.set('name', score_list_str[iScoreId])\n search_score.set('value', str(oPepScores.lfScores[iScoreId]))\n\n if iScoreId == 1:\n search_score = SubElement(search_hit, 'search_score')\n search_score.set('name', 'deltacn')\n search_score.set('value', '0.000')\n search_score = SubElement(search_hit, 'search_score')\n search_score.set('name', 'deltacnstar')\n search_score.set('value', '0.000')\n search_score = SubElement(search_hit, 'search_score')\n search_score.set('name', 'spscore')\n search_score.set('value', '0.000')\n search_score = SubElement(search_hit, 'search_score')\n search_score.set('name', 'sprank')\n search_score.set('value', str(oPepScores.liRanks[iScoreId]))\n search_score = SubElement(search_hit, 'search_score')\n search_score.set('name', 'expect')\n search_score.set('value', '0.000')\n\n iNumProcessedScans += 1\n if iNumProcessedScans % 100 == 0:\n print(\" Processed & Saved %i Scans\\r\" % iNumProcessedScans)\n\n if input_filename != '':\n document = ElementTree(root)\n document.write((output_folder + input_filename + '.pep.xml'),\n encoding='ISO-8859-1',\n xml_declaration=True,\n pretty_print=True)\n\n print('Done.')\n","sub_path":"SiprosEnsemble/sipros_post_module.py","file_name":"sipros_post_module.py","file_ext":"py","file_size_in_byte":59425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"336555181","text":"# -*- coding: utf-8 -*-\nfrom google.appengine.api import users\n\nfrom tools.common import decode\n\ndef login_required(func):\n \"\"\"You can use the @login_required decorator to disallow access to specific\n BaseRequestHandler methods (eg. get(), post()). Example:\n\n class Secrets(BaseRequestHandler):\n @login_required\n def post(self):\n self.render(\"secrets.html\")\n\n \"\"\"\n def _wrapper(request, *args, **kw):\n if request.userprefs:\n return func(request, *args, **kw)\n else:\n \"\"\"\n return request.redirect( \\\n users.create_login_url(request.request.uri))\n \"\"\"\n target_url = \"/account?continue=%s\" % \\\n decode(request.get('continue'))\n\n action = decode(request.get('action'))\n if action and action == \"verify\":\n fid = decode(request.get('openid_identifier'))\n url = users.create_login_url(target_url, federated_identity=fid)\n request.redirect(url)\n else:\n # BaseRequestHandler provides .render() for rendering a template\n request.render(\"login.html\", {\"continue_to\": target_url})\n\n return _wrapper\n\ndef admin_required(func):\n \n def _wrapper(request, *args, **kw):\n if users.is_current_user_admin():\n return func(request, *args, **kw)\n else:\n return request.redirect(users.create_login_url(request.request.url))\n \n return _wrapper\n","sub_path":"tools/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"643701449","text":"import os\n\nimport pytest\n\nfrom qcodes.dataset.database_fix_functions import (\n fix_version_4a_run_description_bug, fix_wrong_run_descriptions)\nimport qcodes.tests.dataset\nfrom qcodes.dataset.sqlite.db_upgrades import get_user_version\nfrom qcodes.tests.dataset.temporary_databases import temporarily_copied_DB\nfrom qcodes.dataset.data_set import DataSet\nfrom qcodes.dataset.dependencies import InterDependencies_\nfrom qcodes.dataset.descriptions import RunDescriber\n\n\nfixturepath = os.sep.join(qcodes.tests.dataset.__file__.split(os.sep)[:-1])\nfixturepath = os.path.join(fixturepath, 'fixtures')\n\n\ndef test_version_4a_bugfix():\n v4fixpath = os.path.join(fixturepath, 'db_files', 'version4a')\n\n dbname_old = os.path.join(v4fixpath, 'some_runs.db')\n\n if not os.path.exists(dbname_old):\n pytest.skip(\"No db-file fixtures found. You can generate test db-files\"\n \" using the scripts in the legacy_DB_generation folder\")\n\n with temporarily_copied_DB(dbname_old, debug=False, version=4) as conn:\n\n dd = fix_version_4a_run_description_bug(conn)\n\n assert dd['runs_inspected'] == 10\n assert dd['runs_fixed'] == 10\n\n dd = fix_version_4a_run_description_bug(conn)\n\n assert dd['runs_inspected'] == 10\n assert dd['runs_fixed'] == 0\n\n\ndef test_version_4a_bugfix_raises():\n\n v3fixpath = os.path.join(fixturepath, 'db_files', 'version3')\n dbname_old = os.path.join(v3fixpath, 'some_runs_without_run_description.db')\n\n if not os.path.exists(dbname_old):\n pytest.skip(\n \"No db-file fixtures found. You can generate test db-files\"\n \" using the scripts in the legacy_DB_generation folder\")\n\n with temporarily_copied_DB(dbname_old, debug=False, version=3) as conn:\n with pytest.raises(RuntimeError):\n fix_version_4a_run_description_bug(conn)\n\n\ndef test_fix_wrong_run_descriptions():\n v3fixpath = os.path.join(fixturepath, 'db_files', 'version3')\n\n dbname_old = os.path.join(v3fixpath, 'some_runs_without_run_description.db')\n\n if not os.path.exists(dbname_old):\n pytest.skip(\n \"No db-file fixtures found. You can generate test db-files\"\n \" using the scripts in the legacy_DB_generation folder\")\n\n with temporarily_copied_DB(dbname_old, debug=False, version=3) as conn:\n\n assert get_user_version(conn) == 3\n\n ds1 = DataSet(conn=conn, run_id=1)\n expected_description = ds1.description\n\n empty_description = RunDescriber(InterDependencies_())\n\n fix_wrong_run_descriptions(conn, [1, 2, 3, 4])\n\n ds2 = DataSet(conn=conn, run_id=2)\n assert expected_description == ds2.description\n\n ds3 = DataSet(conn=conn, run_id=3)\n assert expected_description == ds3.description\n\n ds4 = DataSet(conn=conn, run_id=4)\n assert empty_description == ds4.description\n\n\ndef test_fix_wrong_run_descriptions_raises():\n\n v4fixpath = os.path.join(fixturepath, 'db_files', 'version4a')\n\n dbname_old = os.path.join(v4fixpath, 'some_runs.db')\n\n if not os.path.exists(dbname_old):\n pytest.skip(\"No db-file fixtures found. You can generate test db-files\"\n \" using the scripts in the legacy_DB_generation folder\")\n\n with temporarily_copied_DB(dbname_old, debug=False, version=4) as conn:\n with pytest.raises(RuntimeError):\n fix_wrong_run_descriptions(conn, [1])\n","sub_path":"qcodes/tests/dataset/test_fix_functions.py","file_name":"test_fix_functions.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10669157","text":"import pandas as pd\nimport numpy as np\nfrom reportlab.lib.units import inch\nfrom reportlab.platypus import Table, TableStyle, Paragraph\nfrom reportlab.lib import colors\nfrom reportlab.lib.styles import ParagraphStyle\n\ndef sum_merged_lists(x):\n mylist = []\n listsum = 0\n\n for i in range(len(x[0])):\n for l in x:\n listsum += l[i]\n mylist.append(listsum)\n listsum = 0\n\n return mylist\n\n\ndef clean_quartile_categories(quartile_list):\n return [quartile_list[i][quartile_list[i].index(':') + 1:] for i in range(len(quartile_list))]\n\n\ndef quartile_pct_to_float(mylist):\n nplist = np.array(mylist)\n strip_pct = lambda x: float(x.strip('%'))\n vec_strip_pct = np.vectorize(strip_pct)\n\n return vec_strip_pct(nplist).tolist()\n\n\ndef weighted_na_mean(values, weights):\n temp1 = pd.concat([values, weights], axis=1)\n temp2 = temp1.dropna(axis=0, how='any')\n wmna = np.average(temp2.iloc[:,0],weights=temp2.iloc[:,1])\n return wmna\n\n\ndef sector_quartiles(alldf, df, sector, metric, portmv):\n sector_quartile_table = []\n x = pd.qcut(alldf[metric], 4, retbins=True)\n ranges = [(x[1][0], x[1][1]), (x[1][1], x[1][2]), (x[1][2], x[1][3]), (x[1][3], x[1][4])]\n for i in range(len(ranges)):\n if i == 0:\n sector_quartile_pct = df[(df[metric] >= ranges[i][0]) &\n (df[metric] <= ranges[i][1])]['BaseMarketValue'].sum() / portmv\n else:\n sector_quartile_pct = df[(df[metric] > ranges[i][0]) &\n (df[metric] <= ranges[i][1])]['BaseMarketValue'].sum() / portmv\n\n sector_quartile_table.append(sector_quartile_pct)\n\n df_sq = pd.DataFrame({'ED1': sector_quartile_table[0], 'ED2': sector_quartile_table[1],\n 'ED3': sector_quartile_table[2], 'ED4': sector_quartile_table[3]}, index=[sector])\n\n df_sq['ED1'] = df_sq['ED1'].map('{:.2%}'.format)\n df_sq['ED2'] = df_sq['ED2'].map('{:.2%}'.format)\n df_sq['ED3'] = df_sq['ED3'].map('{:.2%}'.format)\n df_sq['ED4'] = df_sq['ED4'].map('{:.2%}'.format)\n\n return df_sq\n\n\ndef multiple_sector_quartiles(alldf, df, sector, metric_list, portmv):\n sector_quartile_table = []\n table_labels = []\n\n metric_dict = {'EffectiveDuration': 'ED', 'EffectiveConvexity': 'EC', 'Price': 'PX', 'Yield': 'Yld'}\n for metric in metric_list:\n short_label = metric_dict[metric]\n x = pd.qcut(alldf[metric], 4, retbins=True)\n ranges = [(x[1][0], x[1][1]), (x[1][1], x[1][2]), (x[1][2], x[1][3]), (x[1][3], x[1][4])]\n for i in range(len(ranges)):\n if i == 0:\n sector_quartile_pct = df[(df[metric] >= ranges[i][0]) &\n (df[metric] <= ranges[i][1])]['BaseMarketValue'].sum() / portmv\n table_labels.append(short_label + ':[' + '%.2f' % ranges[i][0] + ' - ' + '%.2f' % ranges[i][1] + ']')\n else:\n sector_quartile_pct = df[(df[metric] > ranges[i][0]) &\n (df[metric] <= ranges[i][1])]['BaseMarketValue'].sum() / portmv\n table_labels.append(short_label + ':(' + '%.2f' % ranges[i][0] + ' - ' + '%.2f' % ranges[i][1] + ']')\n\n sector_quartile_table.append(sector_quartile_pct)\n\n df_sq = pd.DataFrame({'V1': sector_quartile_table[0], 'V2': sector_quartile_table[1],\n 'V3': sector_quartile_table[2], 'V4': sector_quartile_table[3],\n 'V5': sector_quartile_table[4], 'V6': sector_quartile_table[5],\n 'V7': sector_quartile_table[6], 'V8': sector_quartile_table[7]}, index=[sector])\n\n df_sq['V1'] = df_sq['V1'].map('{:.2%}'.format)\n df_sq['V2'] = df_sq['V2'].map('{:.2%}'.format)\n df_sq['V3'] = df_sq['V3'].map('{:.2%}'.format)\n df_sq['V4'] = df_sq['V4'].map('{:.2%}'.format)\n\n df_sq['V5'] = df_sq['V5'].map('{:.2%}'.format)\n df_sq['V6'] = df_sq['V6'].map('{:.2%}'.format)\n df_sq['V7'] = df_sq['V7'].map('{:.2%}'.format)\n df_sq['V8'] = df_sq['V8'].map('{:.2%}'.format)\n\n df_sq.columns = table_labels\n\n return df_sq\n\n\ndef top_bonds(df, assetcode, assetsubcode, n, metric):\n top_assets = df[(df['AssetClassCode'] == assetcode) & (df['AssetClassSubCode'] == assetsubcode)]\n dftop = top_assets.nlargest(n, metric)\n\n return dftop\n\n\ndef lowest_bonds(df, assetcode, assetsubcode, n, metric):\n lowest_assets = df[(df['AssetClassCode'] == assetcode) & (df['AssetClassSubCode'] == assetsubcode)]\n dflowest = lowest_assets.nsmallest(n, metric)\n\n return dflowest\n\n\ndef convert_moody_tonumber(grouped_df):\n grouped_sumproduct = 0\n grouped_total = 0\n convert_rating_dict = {'Aaa': 1, 'Aa1': 2, 'Aa2': 3, 'Aa3': 4, 'A1': 5, 'A2': 6, 'A3': 7,\n 'Baa1': 8, 'Baa2': 9, 'Baa3': 10, 'Ba1': 11, 'Ba2': 12, 'Ba3': 13,\n 'B1': 14, 'B2': 15, 'B3': 16, 'Caa1': 17, 'Caa2': 18, 'Caa3': 19,\n 'Ca': 20, 'C': 21}\n\n reverse_rating_dict = dict([[v, k] for k, v in convert_rating_dict.items()])\n\n grouped_dict = dict(grouped_df)\n for k in grouped_dict.keys():\n if k != 'NA':\n grouped_sumproduct += grouped_dict[k] * convert_rating_dict[k]\n grouped_total += grouped_dict[k]\n\n numeric_rating = grouped_sumproduct / grouped_total\n\n return numeric_rating, reverse_rating_dict[round(numeric_rating, 0)]\n\n\ndef create_summary_table(df, offset_text):\n port_summary_table_list = [df.columns.tolist()] + df.reset_index().values.tolist()\n port_summary_table_list[0].insert(0, offset_text)\n summary_table = Table(df.reset_index().values.tolist(), colWidths=[1.2 * inch, .5 * inch, 1 * inch, .6 * inch,\n 1 * inch, .6 * inch, .6 * inch,\n .6 * inch, .6 * inch, .7 * inch,\n .8 * inch, .8 * inch, 1 * inch],\n rowHeights=(.16 * inch))\n\n summary_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('ROWBACKGROUNDS', (0, 0), (-1, -1), (colors.HexColor('#dadada'), None)),\n ('FONTSIZE', (0, 0), (-1, -1), 8)]))\n\n return summary_table\n\n\ndef create_title_table(df, offset_text):\n title_table_list = [df.columns.tolist()] + df.reset_index().values.tolist()\n title_table_list[0].insert(0, offset_text)\n title_table = Table(title_table_list, colWidths=[1.2 * inch, .5 * inch, 0.9 * inch, .6 * inch, 0.9 * inch,\n .6 * inch, .6 * inch, .6 * inch, .6 * inch,\n .7 * inch, .8 * inch, .8 * inch, 1 * inch],\n rowHeights=(.16 * inch), hAlign='LEFT')\n\n title_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#000035')),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8),\n ('TEXTCOLOR', (0, 0), (-1, 0), 'white')]))\n\n return title_table\n\n\ndef underlined_title(title_text):\n mystyle = ParagraphStyle({'fontName': 'Helvetica', 'fontSize': 7, 'alignment': 0})\n p = Paragraph(title_text, style=mystyle)\n summary_title_table = Table([[p]], colWidths=[10 * inch])\n summary_title_table.setStyle(TableStyle([('LINEBELOW', (0, -1), (-1, -1), 1, colors.HexColor('#000035'))]))\n\n return summary_title_table\n\n\ndef comment_text(text):\n mystyle = ParagraphStyle({'fontName': 'Helvetica-Oblique', 'fontSize': 6, 'alignment': 0})\n p = Paragraph(text, style=mystyle)\n comment_table = Table([[p]], colWidths=[10 * inch])\n\n return comment_table\n\n\ndef create_detail_summary_table(df):\n port_summary_table_list = [df.columns.tolist()] + df.reset_index().values.tolist()\n\n summary_table = Table(df.reset_index().values.tolist(), colWidths=[1.2 * inch, .5 * inch, 0.9 * inch, .6 * inch,\n 0.9 * inch, .6 * inch, .6 * inch,\n .6 * inch, .6 * inch, .7 * inch,\n .8 * inch, .8 * inch, 1 * inch],\n rowHeights=(.16 * inch), hAlign='LEFT')\n\n summary_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('FONTSIZE', (0, 0), (-1, -1), 8)]))\n\n shade_list = []\n for i in range(len(df.index)):\n if 'Bonds' in df.index[i]:\n shade_list.append(i)\n if 'Cash' in df.index[i]:\n shade_list.append(i)\n for i in shade_list:\n summary_table.setStyle(TableStyle([('BACKGROUND', (0, i), (-1, i), (colors.HexColor('#dadada')))]))\n\n return summary_table\n\n\ndef create_quartile_table(df):\n\n summary_table = Table(df.reset_index().values.tolist(), colWidths=[1.2 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch,\n 1.1 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch,\n 1.1 * inch], rowHeights=(.16 * inch))\n\n summary_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('FONTSIZE', (0, 0), (-1, -1), 8)]))\n\n shade_list = []\n for i in range(len(df.index)):\n if 'Bonds' in df.index[i]:\n shade_list.append(i)\n\n for i in shade_list:\n summary_table.setStyle(TableStyle([('BACKGROUND', (0, i), (-1, i), (colors.HexColor('#dadada')))]))\n\n return summary_table\n\n\ndef create_quartile_title_table(df, offset_text):\n title_table_list = [df.columns.tolist()] + df.reset_index().values.tolist()\n title_table_list[0].insert(0, offset_text)\n title_table = Table(title_table_list, colWidths=[1.2 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch,\n 1.1 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch],\n rowHeights=(.2 * inch))\n\n title_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#000035')),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8),\n ('TEXTCOLOR', (0, 0), (-1, 0), 'white')]))\n\n return title_table\n\n\ndef multiple_quartile_title_table(df, offset_text, attribute_list):\n\n attribute_list.insert(0,'')\n for i in range(3):\n attribute_list.insert(2, '')\n\n title_table_list = [attribute_list, df.columns.tolist()] + df.reset_index().values.tolist()\n title_table_list[1].insert(0, offset_text)\n title_table = Table(title_table_list, colWidths=[1.2 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch,\n 1.1 * inch, 1.1 * inch, 1.1 * inch, 1.1 * inch],\n rowHeights=(.16 * inch))\n\n title_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('BACKGROUND', (0, 0), (-1, 1), colors.HexColor('#000035')),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8),\n ('SPAN', (1, 0), (4, 0)),\n ('SPAN', (5, 0), (8, 0)),\n ('ALIGN', (0, 0), (-1, 0), 'CENTER'),\n ('LINEBELOW', (1, 0), (-1, 0), 1, colors.white),\n ('LINEAFTER', (4, 1), (4, 1), 1, colors.white),\n ('TEXTCOLOR', (0, 0), (-1, 1), 'white')]))\n\n return title_table\n\n\ndef get_asset_classes(df):\n sector_list = list(df['AssetClassCode'].unique())\n\n return sector_list\n\n\ndef get_asset_subclasses(df):\n subsector = df.groupby('AssetClassSubCode')['CUSIP'].count()\n subsector_list = list(subsector.index)\n\n return subsector_list\n\n\ndef portfolio_totals(df):\n return df['ParAmount'].sum(), df['BaseMarketValue'].sum()\n\n\ndef sectorstats(df, sectorname, portparmv):\n sector_issues = df['CUSIP'].count()\n sector_par = df['ParAmount'].sum()\n sector_par_pct = sector_par / (portparmv[0] * 1.0)\n sector_mktval = df['BaseMarketValue'].sum()\n sector_mktval_pct = sector_mktval / portparmv[1]\n sector_coupon = np.average(df['CurrentCoupon'], weights=df['ParAmount'])\n sector_price = np.average(df['Price'], weights=df['ParAmount'])\n sector_bookprice = np.average(df['BookPrice'], weights=df['ParAmount'])\n sector_yield = np.average(df['Yield'], weights=df['BaseMarketValue'])\n sector_effdur = np.average(df['EffectiveDuration'], weights=df['BaseMarketValue'])\n sector_effcvx = np.average(df['EffectiveConvexity'], weights=df['BaseMarketValue'])\n sector_gainloss = df['gainloss'].sum()\n\n df_sectorstats = pd.DataFrame({'Issues': sector_issues, 'Par Amount(000)': sector_par,\n 'Par %': sector_par_pct,\n 'Market Value(000)': sector_mktval, 'Coupon': sector_coupon,\n 'Market Value %': sector_mktval_pct,\n 'Market Price': sector_price, 'Book Price': sector_bookprice,\n 'Market Yield': sector_yield, 'Effective Duration': sector_effdur,\n 'Effective Convexity': sector_effcvx,\n 'Gain/Loss': sector_gainloss}, index=[sectorname])\n return df_sectorstats\n\n\ndef format_sectorstats(df_format):\n dff = pd.DataFrame()\n dff['Issues'] = df_format['Issues'].map('{:,.0f}'.format)\n dff['Par($000)'] = df_format['Par Amount(000)'].map('{:,.0f}'.format)\n dff['Par%'] = df_format['Par %'].map('{:.1%}'.format)\n dff['Mkt Val($000)'] = df_format['Market Value(000)'].map('{:,.0f}'.format)\n dff['Mkt Val%'] = df_format['Market Value %'].map('{:.1%}'.format)\n dff['Coupon'] = df_format['Coupon'].map('{:.2f}'.format)\n dff['Mkt Yield'] = df_format['Market Yield'].map('{:.2f}'.format)\n dff['Eff Dur'] = df_format['Effective Duration'].map('{:.2f}'.format)\n dff['Eff Cvx'] = df_format['Effective Convexity'].map('{:.2f}'.format)\n dff['Mkt Price'] = df_format['Market Price'].map('{:.3f}'.format)\n dff['Book Price'] = df_format['Book Price'].map('{:.3f}'.format)\n dff['Gain/Loss ($000)'] = df_format['Gain/Loss'].map('{:,.0f}'.format)\n\n return dff\n\n\ndef get_subsector_df(df):\n\n assets = get_asset_classes(df)\n subsector_list = []\n cr_finance = {'FBNK', 'FIND', 'FINS', 'FOTH'}\n cr_industrial = {'ICON', 'IEGY', 'IMAN', 'IOTHC', 'ISRV', 'ITRN'}\n cr_utilities = {'UELC', 'UGAS', 'UTEL', 'UOTH'}\n\n asset_code_dict = {'CA': 'Cash', 'CO': 'Collateralized Bonds', 'TG': 'Sovereign/Agcy Bonds',\n 'MU': 'Municipal Bonds', 'CR': 'Corporate Bonds', 'DR': 'Derivatives'}\n\n for a in assets:\n frame = df[df['AssetClassCode'] == a]\n subsector_list.append((asset_code_dict[a], frame))\n\n subsector_set = set(frame['AssetClassSubCode'])\n\n if a == 'CR' and subsector_set.intersection(cr_finance):\n sub_frame = frame[frame['AssetClassSubCode'].isin(cr_finance)]\n subsector_list.append(('Finance', sub_frame))\n if a == 'CR' and subsector_set.intersection(cr_industrial):\n sub_frame = frame[frame['AssetClassSubCode'].isin(cr_industrial)]\n subsector_list.append(('Industrial', sub_frame))\n if a == 'CR' and subsector_set.intersection(cr_utilities):\n sub_frame = frame[frame['AssetClassSubCode'].isin(cr_utilities)]\n subsector_list.append(('Utility', sub_frame))\n if a == 'MU' and 'N' in frame['BankQualifiedFlag'].unique():\n sub_frame = frame[frame['BankQualifiedFlag'] == 'N']\n subsector_list.append(('Non-Bank Qualified', sub_frame))\n if a == 'MU' and 'Y' in frame['BankQualifiedFlag'].unique():\n sub_frame = frame[frame['BankQualifiedFlag'] == 'Y']\n subsector_list.append(('Bank Qualified', sub_frame))\n\n if a != 'CR' and a != 'MU':\n for s in subsector_set:\n sub_frame = frame[frame['AssetClassSubCode'] == s]\n subsector_list.append((s, sub_frame))\n\n return subsector_list\n\n\ndef mktval_detail_table(df, portsum, byvar):\n mktval = portsum[1]\n ghi = df.groupby([byvar, 'clean_asset_code', 'clean_asset_sub_code'])['BaseMarketValue'].sum() / mktval\n gdata = ghi.unstack(0, fill_value=0)\n\n index_df = gdata.index.to_frame(index=False)\n df = gdata.reset_index(drop=True)\n result = pd.concat([index_df, df], axis=1)\n\n gv = result.values.tolist()\n format_gv = [[\"{:,.1%}\".format(y) if isinstance(y, basestring) is False else y for y in x] for x in gv]\n\n # head_list = result.columns.astype(str).tolist()\n # head_list[0] = 'Sector'\n # head_list[1] = 'Sub-Sector'\n\n current = format_gv[0][0]\n for i in range(1, len(format_gv)):\n if format_gv[i][0] == current:\n format_gv[i][0] = ''\n else:\n current = format_gv[i][0]\n\n table_data = format_gv\n table_data_columns = float(len(table_data[0])-2)\n table_column_width = 7.3 / table_data_columns\n\n duration_table = Table(table_data,\n colWidths=[1.25 * inch, 1.25 * inch, table_column_width * inch],\n rowHeights=(.16 * inch), hAlign='LEFT')\n\n duration_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n # ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#000035')),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8)]))\n\n shade_list = []\n for i in range(len(table_data)):\n if 'Bonds' in table_data[i][0]:\n shade_list.append(i)\n if 'Cash' in table_data[i][0]:\n shade_list.append(i)\n\n for i in shade_list:\n duration_table.setStyle(TableStyle([('BACKGROUND', (0, i), (-1, i), (colors.HexColor('#dadada')))]))\n\n return duration_table\n\n\ndef mktval_by_duration_summary_table(df, offset_text):\n clean_list = np.nan_to_num(df.values.tolist())\n format_gv = [[\"{:,.1%}\".format(y) for y in clean_list]]\n format_gv[0].insert(0, \" \")\n format_gv[0].insert(0, offset_text)\n header_list = df.index.astype(str).tolist()\n header_list.insert(0, \"Sector\")\n header_list.insert(1, \"Sub-Sector\")\n title_table_list = [header_list] + format_gv\n\n table_data_columns = float(len(title_table_list[0]) - 2)\n table_column_width = 7.3 / table_data_columns\n\n title_table = Table(title_table_list,\n colWidths=[1.25 * inch, 1.25 * inch, table_column_width * inch],\n rowHeights=(.16 * inch), hAlign='LEFT')\n\n title_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#000035')),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8),\n ('TEXTCOLOR', (0, 0), (-1, 0), 'white')]))\n\n return title_table\n\n\ndef clean_pivot_table(df, values, index, column_values, index_string, header_string):\n \"\"\" Function to create a pivot table by sector and given index/column and return a formatted table.\n df = dataframe\n values=data to summarize in table\n index=list of one or more variables\n column_values=list of one value for columns\n index_string=string to name index variable\n header_string=string to name columns \"\"\"\n\n z = pd.pivot_table(df, values=values, index=index, columns=column_values, fill_value=0, aggfunc=np.sum)\n zv = z.values.tolist()\n zv_total = sum(sum(x) for x in zv)\n zvpct = [[y / zv_total for y in x] for x in zv]\n format_zv = [[\"{:,.1f}\".format(y) if y > 0 else '' for y in x] for x in zvpct]\n\n zi = z.index.tolist()\n zcat = np.concatenate((zi, format_zv), axis=1)\n\n current = zcat[0][0]\n for i in range(1, len(zcat)):\n if zcat[i][0] == current:\n zcat[i][0] = ''\n else:\n current = zcat[i][0]\n\n header_list = list(z.columns.values)\n header_list.insert(0, index_string)\n header_list.insert(0, 'Sector')\n table_header = ['' for i in range(len(header_list))]\n table_header[2] = header_string\n\n headrow = np.array(header_list)\n finl = np.vstack((table_header, headrow, zcat))\n finl_list = finl.tolist()\n\n table_data_columns = float(len(finl_list[0]) - 2)\n table_column_width = 7.3 / table_data_columns\n\n finl_table = Table(finl_list, colWidths=[1.25 * inch, 1.25 * inch, table_column_width * inch],\n rowHeights=0.15*inch, hAlign='Left')\n\n finl_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8),\n ('BACKGROUND', (0, 0), (-1, 1), colors.HexColor('#000035')),\n ('TEXTCOLOR', (0, 0), (-1, 1), 'white'),\n ('SPAN', (2, 0), (-1, 0)),\n ('ALIGN', (0, 0), (-1, 0), 'CENTER'),\n ('LINEBELOW', (2, 0), (-1, 0), 1, colors.white),\n ('ROWBACKGROUNDS', (2, 4), (-1, -1), (colors.HexColor('#dadada'), None))\n ]))\n shade_list = []\n for i in range(2, len(finl_list)):\n if len(finl_list[i][0]) > 1:\n shade_list.append(i)\n\n for i in shade_list:\n finl_table.setStyle(TableStyle([('BACKGROUND', (0, i), (-1, i), (colors.HexColor('#dadada')))]))\n\n return finl_table\n\n\ndef sector_byvar_table(df, portsum, byvar):\n mktval = portsum[1]\n sector_byvar = df.groupby([byvar, 'clean_asset_code'])['BaseMarketValue'].sum() / mktval\n sector_byvar.dropna(inplace=True)\n sector_byvar = sector_byvar[sector_byvar.values != 0]\n sectordata = sector_byvar.unstack(0, fill_value=0)\n\n index_df = sectordata.index.to_frame(index=False)\n df = sectordata.reset_index(drop=True)\n result = pd.concat([index_df, df], axis=1)\n\n gv = result.values.tolist()\n format_gv = [[\"{:,.1%}\".format(y) if isinstance(y, basestring) is False else y for y in x] for x in gv]\n\n for i in range(len(format_gv)):\n format_gv[i].insert(1, \" \")\n\n table_data = format_gv\n table_data_columns = float(len(table_data[0])-2)\n table_column_width = 7.3 / table_data_columns\n\n sectorbyvar_table = Table(table_data,\n colWidths=[1.25 * inch, 1.25 * inch, table_column_width * inch],\n rowHeights=(.16 * inch), hAlign='LEFT')\n\n sectorbyvar_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'RIGHT'),\n ('FONT', (0, 0), (-1, -1), 'Helvetica'),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('FONTSIZE', (0, 0), (-1, -1), 8)]))\n\n return sectorbyvar_table\n","sub_path":"genericfunctions.py","file_name":"genericfunctions.py","file_ext":"py","file_size_in_byte":24736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"521111209","text":"from flask import request, jsonify, abort\n\nfrom app.models import Student, Enrollment, Professor\nfrom app import app\nfrom operator import itemgetter\n\n\n@app.route('/students/', methods=['GET'])\ndef student_list():\n\n if request.method == \"GET\":\n students = Student.get_all()\n results = []\n\n for student in students:\n obj = {\n 'id': student.student_id,\n 'name': student.student_name,\n 'courses': len(student.courses) if student.courses is not None else 0\n\n }\n results.append(obj)\n\n response = jsonify(sorted(results, key=itemgetter('id')))\n response.status_code = 200\n\n return response\n\n@app.route('/professors/', methods=['GET'])\ndef professor_list():\n if request.method == \"GET\":\n professors = Professor.get_all()\n results = []\n\n for professor in professors:\n obj = {\n 'id': professor.professor_id,\n 'name': professor.professor_name,\n 'students': professor.get_student_count()\n\n }\n results.append(obj)\n\n response = jsonify(sorted(results, key=itemgetter('students'), reverse=True))\n response.status_code = 200\n\n return response\n\n@app.route('/enroll', methods=['POST'])\ndef enroll_student():\n\n if request.method == \"POST\":\n course_id = request.args.get('course_id')\n student_id = request.args.get('student_id')\n\n\n if course_id and student_id:\n enroll = Enrollment()\n enroll.course_id = course_id\n enroll.student_id = student_id\n enroll.save()\n\n return {\n \"message\": \"Student {} added to class {} successfully\".format(enroll.student_id, enroll.course_id)\n }, 201\n\n\n\n@app.route('/enrollupdate', methods=['PUT'])\ndef enroll_update():\n\n if request.method == \"PUT\":\n old_course_id = request.args.get('old_class_id')\n old_student_id = request.args.get('old_student_id')\n new_course_id = request.args.get('new_class_id')\n new_student_id = request.args.get('new_student_id')\n\n if old_course_id != new_course_id and old_student_id != new_student_id:\n enroll = Enrollment.query.filter_by(student_id = old_student_id, class_id = old_course_id).first()\n if not enroll:\n abort(404) #could use better error handling here\n\n enroll.class_id = new_course_id\n enroll.student_id = new_student_id\n enroll.save()\n\n return {\n \"message\": \"Enrollment for student {} and class {} updated to {} and {} \"\n \"successfully\".format(old_student_id, old_course_id, new_student_id, new_course_id)\n }, 200\n\n else:\n return {\n \"message\": \"Enrollment for student {} and class {} \"\n \"already exists\".format(new_student_id, new_course_id)\n }, 200\n\n\n#####################################################################\n##### ALTERNATE ROUTE FOR PASSING IN AN ENROLLMENT_ID #####\n##### UNCOMMENT FUNCTION BELOW AND COMMENT OUT THE #####\n##### FUNCTION ABOVE IF USING ENROLLMENT_ID VERSION OF THE ORM #####\n#####################################################################\n\n# @app.route('/enrollupdate/', methods=['PUT'])\n# def enroll_update():\n#\n# if request.method == \"PUT\":\n# new_class_id = request.args.get('new_class_id')\n# new_student_id = request.args.get('new_student_id')\n# # class_id = str(request.data.get('class_id', ''))\n# # student_id = str(request.data.get('student_id', ''))\n#\n# enroll = Enrollment.query.filter_by(enrollment_id = id).first()\n# if not enroll:\n# abort(404)\n#\n# if enroll.class_id != new_class_id and enroll.student_id != new_student_id:\n#\n# enroll.class_id = new_class_id\n# enroll.student_id = new_student_id\n# enroll.save()\n#\n# return {\n# \"message\": \"Enrollment for student {} and class {} updated to {} and {} \"\n# \"successfully\".format(old_student_id, old_class_id, new_student_id, new_class_id)\n# }, 200\n#\n# else:\n# return {\n# \"message\": \"Enrollment for student {} and class {} \"\n# \"already exists\".format(new_student_id, new_class_id)\n# }, 200\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"654436420","text":"def factorial(n):\n assert n>=0\n if n == 0 or n == 1:\n return 1\n else:\n return n* factorial(n-1)\ndef main():\n num = int(input('Enter the number whose factorial is to be found:'))\n fact = factorial(num)\n print('The Factorial of the number is: ',fact)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Assignment1/204102310 Satya Prakash Singh/Q3.py","file_name":"Q3.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"534401793","text":"from itertools import permutations\r\n\r\nstring=input().split()\r\nsize=int(input())\r\nlist_string=[]\r\nfor i in string:\r\n for j in i:\r\n list_string.append(j)\r\n\r\nprint(list(permutations(list_string,size)))\r\n\r\nstr_list=[]\r\nstr_1=\"\"\r\nfor i in list(permutations(list_string,size)):\r\n for j in i:\r\n str_1=i[0]+i[1]\r\nprint(str_1)\r\n\r\n","sub_path":"Python3/permutation.py","file_name":"permutation.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273106605","text":"# coding=utf8\n\nimport os\nimport sys\nfrom typing import List\n\nfrom termcolor import colored\n\nfrom geektime_dl.data_client.gk_apis import GkApiError\nfrom geektime_dl.utils.ebook import Render\nfrom geektime_dl.utils.mp3_downloader import Downloader\nfrom geektime_dl.cli import Command, add_argument\n\n\nclass Mp3(Command):\n \"\"\"保存专栏音频\"\"\"\n\n def get_all_course_ids(self, dc, type_: str) -> List[int]:\n\n cid_list = []\n data = dc.get_course_list()\n for c in data['1']['list']:\n if type_ == 'all':\n cid_list.append(int(c['id']))\n elif type_ == 'all-sub' and c['had_sub']:\n cid_list.append(int(c['id']))\n elif (type_ == 'all-done' and c['had_sub'] and\n self.is_course_finished(c)):\n cid_list.append(int(c['id']))\n\n return cid_list\n\n @add_argument(\"course_ids\", type=str,\n help=\"specify the target course ids\")\n @add_argument(\"--url-only\", dest=\"url_only\", action='store_true',\n default=False, help=\"download mp3/mp4 url only\")\n @add_argument(\"--workers\", dest=\"workers\", type=int, save=True,\n help=\"specify the number of threads to download mp3/mp4\")\n def run(self, cfg: dict):\n\n dc = self.get_data_client(cfg)\n course_ids = self.parse_course_ids(cfg['course_ids'], dc)\n output_folder = self._format_out_folder(cfg)\n\n dl = Downloader(output_folder, workers=cfg['workers'])\n\n for course_id in course_ids:\n try:\n course_data = dc.get_course_intro(course_id)\n except GkApiError as e:\n sys.stderr.write('{}\\n\\n'.format(e))\n continue\n if int(course_data['column_type']) != 1:\n sys.stderr.write('该课程不提供音频:{} {}\\n\\n'.format(\n course_id, course_data['column_title']))\n continue\n out_dir = os.path.join(\n output_folder,\n Render.format_file_name(course_data['column_title']))\n if not os.path.isdir(out_dir):\n os.makedirs(out_dir)\n\n # fetch raw data\n print(colored('开始下载音频:{}-{}'.format(\n course_id, course_data['column_title']), 'green'))\n pbar_desc = '数据爬取中:{}'.format(course_data['column_title'][:10])\n data = dc.get_course_content(course_id, pbar_desc=pbar_desc)\n\n # save url\n if cfg['url_only']:\n self._parse_and_save_url(course_data, data, out_dir)\n continue\n\n # download mp3\n for post in data:\n fn = Render.format_file_name(\n post['article_title']) + '.mp3'\n if os.path.isfile(os.path.join(out_dir, fn)):\n sys.stdout.write(fn + ' exists\\n')\n continue\n if post['audio_download_url']:\n dl.run(post['audio_download_url'],\n file_name=os.path.join(out_dir, fn))\n dl.shutdown()\n\n @staticmethod\n def _format_out_folder(cfg):\n output_folder = os.path.join(cfg['output_folder'], 'mp3')\n output_folder = os.path.expanduser(output_folder)\n if not os.path.isdir(output_folder):\n os.makedirs(output_folder)\n return output_folder\n\n @staticmethod\n def _parse_and_save_url(course_intro: dict,\n course_data: list, out_dir: str):\n title = Render.format_file_name(course_intro['column_title'])\n fn = os.path.join(out_dir, '{}.mp3.txt'.format(title))\n with open(fn, 'w') as f:\n f.write('\\n'.join([\"{}:\\t\\t{}\".format(\n Render.format_file_name(post['article_title']),\n post['audio_download_url']\n ) for post in course_data]))\n sys.stdout.write('音频链接下载完成:{}\\n\\n'.format(fn))\n\n","sub_path":"geektime_dl/cli/mp3.py","file_name":"mp3.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"252643103","text":"# <>\n# Copyright 2022, Lawrence Livermore National Security, LLC.\n# See the top-level COPYRIGHT file for details.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# <>\n\n\"\"\"\nModule containing dictionaries and helper functions for handling particle ids and symbols.\n\nDefines the following dictionaries:\n symbolFromZ, nameFromZ # look up chemical symbol or name by Z\n ZfromSymbol, nameFromSymbol # look up Z or name by chemical symbol\n ZfromName, symbolFromName # look up Z or symbol by chemical name\n\"\"\"\n\nMaxA = 400\ncontinuumID = 1000000\nsumID = continuumID + 1\n\nimport math\n\nfrom pqu import PQU as PQUModule\nfrom .. import misc as miscModule\n\nchemicalElementZSymbolNames = (\n ( 1, \"H\", \"Hydrogen\" ), ( 2, \"He\", \"Helium\" ), ( 3, \"Li\", \"Lithium\" ),\n ( 4, \"Be\", \"Beryllium\" ), ( 5, \"B\", \"Boron\" ), ( 6, \"C\", \"Carbon\" ),\n ( 7, \"N\", \"Nitrogen\" ), ( 8, \"O\", \"Oxygen\" ), ( 9, \"F\", \"Fluorine\" ),\n ( 10, \"Ne\", \"Neon\" ), ( 11, \"Na\", \"Sodium\" ), ( 12, \"Mg\", \"Magnesium\" ),\n ( 13, \"Al\", \"Aluminium\" ), ( 14, \"Si\", \"Silicon\" ), ( 15, \"P\", \"Phosphorus\" ),\n ( 16, \"S\", \"Sulphur\" ), ( 17, \"Cl\", \"Chlorine\" ), ( 18, \"Ar\", \"Argon\" ),\n ( 19, \"K\", \"Potassium\" ), ( 20, \"Ca\", \"Calcium\" ), ( 21, \"Sc\", \"Scandium\" ),\n ( 22, \"Ti\", \"Titanium\" ), ( 23, \"V\", \"Vanadium\" ), ( 24, \"Cr\", \"Chromium\" ),\n ( 25, \"Mn\", \"Manganese\" ), ( 26, \"Fe\", \"Iron\" ), ( 27, \"Co\", \"Cobalt\" ),\n ( 28, \"Ni\", \"Nickel\" ), ( 29, \"Cu\", \"Copper\" ), ( 30, \"Zn\", \"Zinc\" ),\n ( 31, \"Ga\", \"Gallium\" ), ( 32, \"Ge\", \"Germanium\" ), ( 33, \"As\", \"Arsenic\" ),\n ( 34, \"Se\", \"Selenium\" ), ( 35, \"Br\", \"Bromine\" ), ( 36, \"Kr\", \"Krypton\" ),\n ( 37, \"Rb\", \"Rubidium\" ), ( 38, \"Sr\", \"Strontium\" ), ( 39, \"Y\", \"Yttrium\" ),\n ( 40, \"Zr\", \"Zirconium\" ), ( 41, \"Nb\", \"Niobium\" ), ( 42, \"Mo\", \"Molybdenum\" ),\n ( 43, \"Tc\", \"Technetium\" ), ( 44, \"Ru\", \"Ruthenium\" ), ( 45, \"Rh\", \"Rhodium\" ),\n ( 46, \"Pd\", \"Palladium\" ), ( 47, \"Ag\", \"Silver\" ), ( 48, \"Cd\", \"Cadmium\" ),\n ( 49, \"In\", \"Indium\" ), ( 50, \"Sn\", \"Tin\" ), ( 51, \"Sb\", \"Antimony\" ),\n ( 52, \"Te\", \"Tellurium\" ), ( 53, \"I\", \"Iodine\" ), ( 54, \"Xe\", \"Xenon\" ),\n ( 55, \"Cs\", \"Cesium\" ), ( 56, \"Ba\", \"Barium\" ), ( 57, \"La\", \"Lanthanum\" ),\n ( 58, \"Ce\", \"Cerium\" ), ( 59, \"Pr\", \"Praseodymium\" ), ( 60, \"Nd\", \"Neodymium\" ),\n ( 61, \"Pm\", \"Promethium\" ), ( 62, \"Sm\", \"Samarium\" ), ( 63, \"Eu\", \"Europium\" ),\n ( 64, \"Gd\", \"Gadolinium\" ), ( 65, \"Tb\", \"Terbium\" ), ( 66, \"Dy\", \"Dysprosium\" ),\n ( 67, \"Ho\", \"Holmium\" ), ( 68, \"Er\", \"Erbium\" ), ( 69, \"Tm\", \"Thulium\" ),\n ( 70, \"Yb\", \"Ytterbium\" ), ( 71, \"Lu\", \"Lutetium\" ), ( 72, \"Hf\", \"Hafnium\" ),\n ( 73, \"Ta\", \"Tantalum\" ), ( 74, \"W\", \"Tungsten\" ), ( 75, \"Re\", \"Rhenium\" ),\n ( 76, \"Os\", \"Osmium\" ), ( 77, \"Ir\", \"Iridium\" ), ( 78, \"Pt\", \"Platinum\" ),\n ( 79, \"Au\", \"Gold\" ), ( 80, \"Hg\", \"Mercury\" ), ( 81, \"Tl\", \"Thallium\" ),\n ( 82, \"Pb\", \"Lead\" ), ( 83, \"Bi\", \"Bismuth\" ), ( 84, \"Po\", \"Polonium\" ),\n ( 85, \"At\", \"Astatine\" ), ( 86, \"Rn\", \"Radon\" ), ( 87, \"Fr\", \"Francium\" ),\n ( 88, \"Ra\", \"Radium\" ), ( 89, \"Ac\", \"Actinium\" ), ( 90, \"Th\", \"Thorium\" ),\n ( 91, \"Pa\", \"Protactinium\" ), ( 92, \"U\", \"Uranium\" ), ( 93, \"Np\", \"Neptunium\" ),\n ( 94, \"Pu\", \"Plutonium\" ), ( 95, \"Am\", \"Americium\" ), ( 96, \"Cm\", \"Curium\" ),\n ( 97, \"Bk\", \"Berkelium\" ), ( 98, \"Cf\", \"Californium\" ), ( 99, \"Es\", \"Einsteinium\" ),\n ( 100, \"Fm\", \"Fermium\" ), ( 101, \"Md\", \"Mendelevium\" ), ( 102, \"No\", \"Nobelium\" ),\n ( 103, \"Lr\", \"Lawrencium\" ), ( 104, \"Rf\", \"Rutherfordium\" ), ( 105, \"Db\", \"Dubnium\" ),\n ( 106, \"Sg\", \"Seaborgium\" ), ( 107, \"Bh\", \"Bohrium\" ), ( 108, \"Hs\", \"Hassium\" ),\n ( 109, \"Mt\", \"Meitnerium\" ), ( 110, \"Ds\", \"Darmstadtium\" ), ( 111, \"Rg\", \"Roentgenium\" ),\n ( 112, \"Cn\", \"Copernicium\" ), ( 113, \"Nh\", \"Nihonium\" ), ( 114, \"Fl\", \"Flerovium\" ),\n ( 115, \"Mc\", \"Moscovium\" ), ( 116, \"Lv\", \"Livermorium\" ), ( 117, \"Ts\", \"Tennessine\" ),\n ( 118, \"Og\", \"Oganesson\" ) )\n\nsymbolFromZ = {}\nfor Z, symbol, name in chemicalElementZSymbolNames : symbolFromZ[Z] = symbol\n\nnameFromZ = {}\nfor Z, symbol, name in chemicalElementZSymbolNames : nameFromZ[Z] = name\n\nZFromSymbol = {}\nfor Z, symbol, name in chemicalElementZSymbolNames : ZFromSymbol[symbol] = Z\n\nnameFromSymbol = {}\nfor Z, symbol, name in chemicalElementZSymbolNames : nameFromSymbol[symbol] = name\n\nZFromName = {}\nfor Z, symbol, name in chemicalElementZSymbolNames : ZFromName[name] = Z\n\nsymbolFromName = {}\nfor Z, symbol, name in chemicalElementZSymbolNames : symbolFromName[name] = symbol\n\ndef checkZ( Z ) :\n\n if( not( isinstance( Z, int ) ) ) : raise TypeError( 'Z not an int object.' )\n if( 0 < Z <= chemicalElementZSymbolNames[-1][0] ) : return( Z )\n raise ValueError( 'Z = \"%s\" out of range.' % Z )\n\ndef checkSymbol( symbol ) :\n\n if( not( isinstance( symbol, str ) ) ) : raise TypeError( 'symbol not a str object.' )\n if( symbol not in ZFromSymbol ) : raise ValueError( 'Invalid symbol: %s.' % miscModule.toLimitedString( symbol ) )\n\ndef checkA( A ) :\n\n if( not( isinstance( A, int ) ) ) : raise TypeError( 'A not an int' )\n if( not( 0 <= A < MaxA ) ) : raise ValueError( 'integer A out of range: A = %s' % A )\n return( A )\n\ndef checkIndex( index ) :\n\n if( not( isinstance( index, int ) ) ) : raise TypeError( 'index attribute not int object.' )\n if( index < 0 ) : ValueError( 'Negative level index = %s' % index )\n return( index )\n\ndef chemicalElementALevelIDsAndAnti( id, qualifierAllowed = False ) :\n \"\"\"\n Parse a particle id to extract the following information:\n baseId: particle id with any qualifiers removed\n chemicalElementSymbol: symbol if id is a chemical element, isotope, nuclide or nucleus. None otherwise\n A: total nucleon number (as integer) if id is for an isotope, nuclide or nucleus. None otherwise\n levelId: integer level index if id is a nuclide or nucleus. None otherwise\n isNucleus: True if id is a nucleus, False if id is a chemical element, isotope or nuclide, None otherwise\n anti: '_anti' if id contains that string, empty string otherwise\n qualifier: string qualifier if one is found (qualifiers appear inside {curly brackets}. Empty string otherwise\n\n Unless qualifierAllowed = True, ValueError will be raised if a qualifier is detected in id\n\n :param id: string particle id or symbol\n :param qualifierAllowed: boolean, whether qualifiers are allowed in the id\n :return: tuple(baseId, chemicalElementSymbol, A, levelID, isNucleus, anti, qualifier)\n \"\"\"\n\n baseID, anti, qualifier = miscModule.baseAntiQualifierFromID( id, qualifierAllowed = qualifierAllowed )\n\n chemicalElementSymbol = None\n A = None\n levelID = None\n isNucleus = False\n if( baseID.count( '_e' ) < 2 ) : # Can have 0 or 1 '_e' (e.g., 'O16', 'O16_e3') if chemicalElement derived.\n isotopeID, sep, levelID = baseID.partition( '_e' )\n if( sep == '_e' ) :\n try :\n levelID = int( levelID )\n checkIndex( levelID )\n except :\n levelID = None\n isotopeID = ''\n else :\n levelID = None\n\n if( len( isotopeID ) > 0 ) :\n for i1, character in enumerate( isotopeID ) :\n if( character.isdigit( ) ) : break\n isotopeIDUpper = isotopeID[0].upper( ) + isotopeID[1:]\n if( character.isdigit( ) ) :\n chemicalElementSymbol = isotopeIDUpper[:i1]\n try :\n A = int( isotopeIDUpper[i1:] )\n checkSymbol( chemicalElementSymbol )\n checkA( A )\n isNucleus = isotopeIDUpper != isotopeID\n if( levelID is None ) : levelID = 0\n except :\n chemicalElementSymbol = None\n else :\n try :\n checkSymbol( isotopeID )\n chemicalElementSymbol = isotopeID\n except :\n chemicalElementSymbol = None\n\n if( chemicalElementSymbol is None ) : A, levelID, isNucleus = None, None, None\n return( baseID, chemicalElementSymbol, A, levelID, isNucleus, anti, qualifier )\n\ndef ZAInfo( particle ) :\n \"\"\"\n Compute Z, A, ZA and level index for a particle instance.\n\n :param particle: PoPs particle instance. If the particle is not a baryon, isotope, nuclide or nucleus,\n Z, A, ZA and level index will all be 0.\n :return: tuple( Z, A, ZA, levelIndex ).\n \"\"\"\n\n from .. import IDs as IDsModule\n from ..families import nuclide as nuclideModule\n from ..families import nucleus as nucleusModule\n from ..families import baryon as baryonModule\n from ..families import unorthodox as unorthodoxModule\n from . import isotope as isotopeModule\n\n level = 0\n Z = 0\n A = 0\n if( isinstance( particle, ( isotopeModule.Isotope, ) ) ) :\n Z = particle.Z\n A = particle.A\n elif( isinstance( particle, ( nuclideModule.Particle, nuclideModule.Alias ) ) ) :\n Z = particle.Z\n A = particle.A\n level = particle.index\n elif( isinstance( particle, ( nucleusModule.Particle, nucleusModule.Alias ) ) ) :\n Z = particle.Z\n A = particle.A\n level = particle.index\n elif( isinstance( particle, ( baryonModule.Particle, ) ) ) :\n if( particle.id == IDsModule.neutron ) :\n A = 1\n if( particle.id == IDsModule.proton ) :\n Z = 1\n A = 1\n elif( isinstance( particle, ( unorthodoxModule.Particle, ) ) ) :\n if( 'FissionProductENDL99120' == particle.id ) :\n Z = 99\n A = 120\n elif( 'FissionProductENDL99125' == particle.id ) :\n Z = 99\n A = 125\n elif len(particle.charge) > 0:\n Z = particle.charge[0].value\n\n try :\n return( Z, A, 1000 * Z + A, level ) # FIXME raise if it didn't match anything?\n except :\n raise\n\ndef ZAInfo_fromString( particleName ):\n \"\"\"\n Parses an isotope name (e.g., 'Mn55_e3') to get its Z, A, ZA and nuclear level index.\n If the level is negative, the particle is a metastable name (e.g., 'Am242_m1').\n The name can be an isotope which returns ( Z, A, 1000 * Z + A, level ) (e.g., 'O16' returns (8, 16, 8016, 0)), \n a natural isotope which returns ( Z, 0, 1000 * Z, level) (e.g., 'O0' returns (8, 0, 8000, 0)) \n or just a chemical element's symbol which returns ( Z, 0, 0, 0 ) (e.g., 'O' returns (8, 0, 0, 0)).\n Also handles PoPs (GNDS) nucleus name which is the nucleus' isotope name but with the first character lower-cased\n (e.g., 'o16' for the nucleus of Oyxgen-16) as well as 'n', 'p', 'd', 't', 'h' and 'a'.\n Handles nuclear excited levels (e.g., 'Am242_e2' returns (95, 242, 95242, 2)) and nuclear metastables \n (e.g., 'Am242_m1' returns (95, 242, 95242, -1)).\n\n :param particleName: string\n :return: tuple( Z, A, ZA, levelIndex )\n \"\"\"\n\n import re\n\n if particleName == 'FissionProductENDL99120':\n return 99, 120, 99120, 0\n elif particleName == 'FissionProductENDL99125':\n return 99, 125, 99125, 0\n\n if( len( particleName ) > 1 ) : particleName = particleName.capitalize( )\n\n try :\n return( { 'n' : ( 0, 1, 1, 0 ), \n 'p' : ( 1, 1, 1001, 0 ), 'd' : ( 1, 2, 1002, 0 ), 't' : ( 1, 3, 1003, 0 ),\n 'h' : ( 2, 3, 2003, 0 ), 'a' : ( 2, 4, 2004, 0 ) }[particleName] )\n except :\n pass\n\n pattern = re.compile( \"([A-Za-z]+)([0-9]+)(_[em])?([0-9]+)?\" )\n result = pattern.match( particleName )\n if( result is None ) :\n try :\n Z = ZFromSymbol[particleName] # Assumes that particleName is just the chemical element part (e.g., 'Xe').\n except :\n Z = 0 # Not a valid isotope or chemical element name so return all 0's.\n return( Z, 0, 0, 0 )\n\n symbol, A, levelIndicator, level = result.groups( )\n\n reconstructed = symbol + A\n if( levelIndicator is not None ) :\n if( level is not None ) : reconstructed += levelIndicator + level\n if( particleName != reconstructed ) : return( 0, 0, 0, 0 )\n\n A = int( A )\n if( level is None ) :\n level = 0\n else :\n level = int( level )\n if( levelIndicator == '_m' ) : level = -level\n\n Z = ZFromSymbol[symbol]\n\n return( Z, A, 1000 * Z + A, level )\n\ndef ZA( particle ) :\n \"\"\"\n Uses ZAInfo to compute the particle ZA. See ZAInfo for more detail\n \"\"\"\n\n return( ZAInfo( particle )[2] )\n\ndef idFromZAndA( Z, A ) :\n \"\"\"\n Compute the PoPs id for a particle given Z and A\n :param Z: atomic number (int)\n :param A: nucleon number (int)\n :return: string particle id\n \"\"\"\n\n from .. import IDs as IDsModule\n\n if( ( Z == 0 ) and ( A == 1 ) ) : return( IDsModule.neutron )\n return( isotopeSymbolFromChemicalElementIDAndA( symbolFromZ[Z], A ) )\n\ndef idFromZA( ZA ) :\n \"\"\"\n Compute the PoPs id for a particle given ZA\n :param ZA: 1000 * Z + A (int)\n :return: string particle id\n \"\"\"\n\n return( idFromZAndA( ZA // 1000, ZA % 1000 ) )\n\ndef nucleusIDFromZAndA( Z, A ) :\n \"\"\" Equivalent to calling nucleusIDFromNuclideID( idFromZAndA( Z, A ) ) \"\"\"\n\n nucleusID = idFromZAndA( Z, A )\n return( nucleusID[0].lower( ) + nucleusID[1:] )\n\ndef hasNucleus( particle, nucleusReturnsTrue = False ) :\n \"\"\"\n Checks whether particle contains a nucleus.\n\n :param particle: PoPs particle instance\n :param nucleusReturnsTrue: boolean. If False, hasNucleus returns False when particle is a nucleus instance\n \"\"\"\n\n from . import isotope as isotopeModule\n from ..families import nuclide as nuclideModule\n from ..families import nucleus as nucleusModule\n\n if isinstance(particle, (isotopeModule.Isotope, nuclideModule.Particle)): return True\n return nucleusReturnsTrue and isinstance(particle, nucleusModule.Particle)\n\ndef isotopeSymbolFromChemicalElementIDAndA( elementID, A ) :\n\n checkSymbol( elementID )\n checkA( A )\n return( \"%s%s\" % ( elementID, A ) )\n\ndef nuclideIDFromIsotopeSymbolAndIndex( isotopeSymbol, index ) :\n\n checkIndex( index )\n if( index == 0 ) : return( isotopeSymbol )\n return( \"%s_e%s\" % ( isotopeSymbol, index ) )\n\ndef nucleusIDFromNuclideID( nuclideID ) :\n \"\"\" The nucleus id is computed from nuclide id by converting 1st letter to lower case \"\"\"\n\n return( nuclideID[0].lower( ) + nuclideID[1:] )\n\ndef nuclideIDFromNucleusID( nucleusID ) :\n \"\"\" The nuclide id is computed from nucleus id by converting 1st letter to upper case \"\"\"\n\n return( nucleusID[0].upper( ) + nucleusID[1:] )\n\ndef nuclearBindingEnergyPerNucleonSemiEmpirical(Z, A, unit):\n '''\n Returns the nuclear binding energy per nucleon from a semi empirical formula (see https://en.wikipedia.org/wiki/Nuclear_binding_energy).\n '''\n\n N = A - Z\n pairingTerm = 0\n if A % 2 == 0:\n pairingTerm = 33.0\n if Z % 2 == 1:\n pairingTerm *= -1\n\n energy_MeV = 14.0 - 13.0 * math.pow(A, -1/3) - 0.585 * Z**2 * math.pow(A, -4/3) - 19.3 * (N - Z)**2 / A**2 + pairingTerm * math.pow(A, -7/4)\n\n return PQUModule.PQU(energy_MeV, 'MeV').getValueAs(unit)\n","sub_path":"PoPs/chemicalElements/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":15761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329055226","text":"# container-service-extension\n# Copyright (c) 2017 VMware, Inc. All Rights Reserved.\n# SPDX-License-Identifier: BSD-2-Clause\n\nfrom os.path import expanduser\nfrom os.path import join\n\nimport click\n\nfrom container_service_extension.client.cluster import Cluster\n\nfrom vcd_cli.utils import restore_session\nfrom vcd_cli.utils import stderr\nfrom vcd_cli.utils import stdout\nfrom vcd_cli.vcd import abort_if_false\nfrom vcd_cli.vcd import vcd\n\nimport yaml\n\n@vcd.group(short_help='manage kubernetes clusters')\n@click.pass_context\ndef cse(ctx):\n \"\"\"Work with kubernetes clusters in vCloud Director.\n\n\\b\n Examples\n vcd cse cluster list\n Get list of kubernetes clusters in current virtual datacenter.\n\\b\n vcd cse cluster create dev-cluster --network net1\n Create a kubernetes cluster in current virtual datacenter.\n\\b\n vcd cse cluster create prod-cluster --nodes 4 \\\\\n --network net1 --storage-profile '*'\n Create a kubernetes cluster with 4 worker nodes.\n\\b\n vcd cse cluster delete dev-cluster\n Delete a kubernetes cluster by name.\n\\b\n vcd cse cluster create c1 --nodes 0 --network net1\n Create a single node kubernetes cluster for dev/test.\n\\b\n vcd cse template list\n Get list of CSE templates available.\n \"\"\"\n\n if ctx.invoked_subcommand is not None:\n try:\n restore_session(ctx)\n if not ctx.obj['profiles'].get('vdc_in_use') or \\\n not ctx.obj['profiles'].get('vdc_href'):\n raise Exception('select a virtual datacenter')\n except Exception as e:\n stderr(e, ctx)\n\n\n@cse.group(short_help='work with clusters')\n@click.pass_context\ndef cluster(ctx):\n \"\"\"Work with kubernetes clusters.\"\"\"\n\n if ctx.invoked_subcommand is not None:\n try:\n restore_session(ctx)\n if not ctx.obj['profiles'].get('vdc_in_use') or \\\n not ctx.obj['profiles'].get('vdc_href'):\n raise Exception('select a virtual datacenter')\n except Exception as e:\n stderr(e, ctx)\n\n\n@cse.group(short_help='manage CSE templates')\n@click.pass_context\ndef template(ctx):\n \"\"\"Work with CSE templates.\"\"\"\n\n if ctx.invoked_subcommand is not None:\n try:\n restore_session(ctx)\n if not ctx.obj['profiles'].get('vdc_in_use') or \\\n not ctx.obj['profiles'].get('vdc_href'):\n raise Exception('select a virtual datacenter')\n except Exception as e:\n stderr(e, ctx)\n\n\n@template.command('list', short_help='list templates')\n@click.pass_context\ndef list_templates(ctx):\n try:\n client = ctx.obj['client']\n cluster = Cluster(client)\n result = []\n templates = cluster.get_templates()\n for t in templates:\n result.append({'name': t['name'],\n 'description': t['description'],\n 'catalog': t['catalog'],\n 'catalog_item': t['catalog_item'],\n 'is_default': t['is_default'],\n })\n stdout(result, ctx, show_id=True)\n except Exception as e:\n stderr(e, ctx)\n\n\n@cluster.command('list', short_help='list clusters')\n@click.pass_context\ndef list_clusters(ctx):\n try:\n client = ctx.obj['client']\n cluster = Cluster(client)\n result = []\n clusters = cluster.get_clusters()\n for c in clusters:\n result.append({'name': c['name'],\n 'IP master': c['leader_endpoint'],\n 'template': c['template'],\n 'VMs': c['number_of_vms'],\n 'vdc': c['vdc_name']\n })\n stdout(result, ctx, show_id=True)\n except Exception as e:\n stderr(e, ctx)\n\n\n@cluster.command(short_help='delete cluster')\n@click.pass_context\n@click.argument('name',\n metavar='',\n required=True)\n@click.option('-y',\n '--yes',\n is_flag=True,\n callback=abort_if_false,\n expose_value=False,\n prompt='Are you sure you want to delete the cluster?')\ndef delete(ctx, name):\n try:\n client = ctx.obj['client']\n cluster = Cluster(client)\n result = cluster.delete_cluster(name)\n stdout(result, ctx)\n except Exception as e:\n stderr(e, ctx)\n\n\n@cluster.command(short_help='create cluster')\n@click.pass_context\n@click.argument('name',\n metavar='',\n required=True)\n@click.option('-N',\n '--nodes',\n 'node_count',\n required=False,\n default=2,\n metavar='',\n help='Number of nodes to create')\n@click.option('-c',\n '--cpu',\n 'cpu_count',\n required=False,\n default=None,\n metavar='',\n help='Number of virtual cpus on each node')\n@click.option('-m',\n '--memory',\n 'memory',\n required=False,\n default=None,\n metavar='',\n help='Amount of memory (in MB) on each node')\n@click.option('-n',\n '--network',\n 'network_name',\n default=None,\n required=False,\n metavar='',\n help='Network name')\n@click.option('-s',\n '--storage-profile',\n 'storage_profile',\n required=False,\n default=None,\n metavar='',\n help='Name of the storage profile for the nodes')\n@click.option('-k',\n '--ssh-key',\n 'ssh_key_file',\n required=False,\n default=None,\n type=click.File('r'),\n metavar='',\n help='SSH public key to connect to the guest OS on the VM')\n@click.option('-t',\n '--template',\n 'template',\n required=False,\n default=None,\n metavar='